"use client";

import { useState, useEffect } from "react";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import {
  RotateCcw,
  Plus,
  Search,
  TrendingUp,
  AlertCircle,
  Eye,
  MapPin,
  RefreshCw,
  ExternalLink,
  MessageCircle,
} from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { WildberriesService, type WBClaim, type WBClaimsResponse } from "@/services/wildberries-service";
import { toast } from "sonner";

// Интерфейс для обработанных данных возврата
interface ProcessedClaim {
  id: string;
  productName: string;
  nmId: number;
  returnDate: string;
  status: string;
  reason: string;
  price: number;
  userComment: string;
  wbComment: string;
  photos: string[];
  videoPaths: string[];
  actions: string[];
  orderDate: string;
  lastUpdate: string;
}

export function PvzReturnsTab() {
  const { user } = useAuth();
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [archiveFilter, setArchiveFilter] = useState(false);
  const [claims, setClaims] = useState<ProcessedClaim[]>([]);
  const [loading, setLoading] = useState(false);
  const [refreshing, setRefreshing] = useState(false);
  const [total, setTotal] = useState(0);

  // Загрузка заявок
  const loadClaims = async (showToast = false) => {
    const isInitialLoad = !refreshing;
    if (isInitialLoad) setLoading(true);
    else setRefreshing(true);

    try {
      const wbApiKey = user?.organization?.apiKeys?.find(
        (key) => key.marketplace === "WILDBERRIES" && key.isActive
      );

      if (!wbApiKey) {
        if (showToast) {
          toast.error("API ключ Wildberries не настроен");
        }
        return;
      }

      const apiToken = wbApiKey.apiKey;

      console.log("WB Claims: Loading claims with archive =", archiveFilter);

      const response = await WildberriesService.getClaims(apiToken, {
        isArchive: archiveFilter,
        limit: 100,
        offset: 0,
      });

      const processedClaims = response.claims.map(processClaim);
      setClaims(processedClaims);
      setTotal(response.total);

      console.log(`WB Claims: Loaded ${processedClaims.length} claims`);

      if (showToast) {
        toast.success(`Загружено заявок: ${processedClaims.length}`);
      }
    } catch (error) {
      console.error("Error loading claims:", error);
      if (showToast) {
        toast.error("Ошибка загрузки заявок на возврат");
      }
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  // Обработка данных из API в удобный формат
  const processClaim = (claim: WBClaim): ProcessedClaim => {
    const getStatusLabel = (status: number, statusEx: number) => {
      // Мапинг статусов на основе документации API
      switch (status) {
        case 1:
          return "На рассмотрении";
        case 2:
          return "Одобрена";
        case 3:
          return "Отклонена";
        case 4:
          return "В архиве";
        default:
          return `Статус ${status}`;
      }
    };

    return {
      id: claim.id,
      productName: claim.imt_name,
      nmId: claim.nm_id,
      returnDate: claim.dt,
      status: getStatusLabel(claim.status, claim.status_ex),
      reason: claim.user_comment || "Не указана",
      price: claim.price,
      userComment: claim.user_comment,
      wbComment: claim.wb_comment,
      photos: claim.photos || [],
      videoPaths: claim.video_paths || [],
      actions: claim.actions || [],
      orderDate: claim.order_dt,
      lastUpdate: claim.dt_update,
    };
  };

  // Загрузка при монтировании компонента
  useEffect(() => {
    loadClaims();
  }, [user, archiveFilter]);

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat("ru-RU", {
      style: "currency",
      currency: "RUB",
      minimumFractionDigits: 0,
    }).format(amount);
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString("ru-RU", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
    });
  };

  const getStatusBadge = (status: string) => {
    const statusConfig = {
      "На рассмотрении": {
        color: "text-yellow-300 border-yellow-400/30",
        label: "На рассмотрении",
      },
      "Одобрена": {
        color: "text-green-300 border-green-400/30",
        label: "Одобрена",
      },
      "Отклонена": {
        color: "text-red-300 border-red-400/30",
        label: "Отклонена",
      },
      "В архиве": {
        color: "text-gray-300 border-gray-400/30",
        label: "В архиве",
      },
    };

    const config = statusConfig[status as keyof typeof statusConfig] || {
      color: "text-gray-300 border-gray-400/30",
      label: status,
    };

    return (
      <Badge variant="outline" className={`glass-secondary ${config.color}`}>
        {config.label}
      </Badge>
    );
  };

  const filteredClaims = claims.filter((claim) => {
    const matchesSearch =
      claim.productName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      claim.nmId.toString().includes(searchTerm) ||
      claim.reason.toLowerCase().includes(searchTerm.toLowerCase()) ||
      claim.id.toLowerCase().includes(searchTerm.toLowerCase());

    const matchesStatus =
      statusFilter === "all" || claim.status === statusFilter;

    return matchesSearch && matchesStatus;
  });

  const getTotalValue = () => {
    return filteredClaims.reduce((sum, claim) => sum + claim.price, 0);
  };

  const getPendingCount = () => {
    return filteredClaims.filter((claim) => claim.status === "На рассмотрении")
      .length;
  };

  const getUniqueStatuses = () => {
    const statuses = [...new Set(claims.map((claim) => claim.status))];
    return statuses;
  };

  const hasWBApiKey = user?.organization?.apiKeys?.some(
    (key) => key.marketplace === "WILDBERRIES" && key.isActive
  );

  if (!hasWBApiKey) {
    return (
      <div className="h-full flex flex-col items-center justify-center space-y-4 p-8">
        <AlertCircle className="h-12 w-12 text-yellow-400" />
        <div className="text-center">
          <h3 className="text-lg font-semibold text-white mb-2">
            API ключ Wildberries не настроен
          </h3>
          <p className="text-white/60 mb-4">
            Для просмотра заявок на возврат необходимо настроить API ключ
            Wildberries в настройках организации.
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="h-full flex flex-col space-y-4 p-4">
      {/* Статистика с кнопками */}
      <div className="flex items-center justify-between gap-4">
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 flex-1">
          <Card className="glass-card p-3 h-[60px]">
            <div className="flex items-center space-x-2 h-full">
              <div className="p-1.5 bg-blue-500/20 rounded">
                <RotateCcw className="h-3 w-3 text-blue-400" />
              </div>
              <div>
                <p className="text-white/60 text-xs">Заявок</p>
                <p className="text-lg font-bold text-white">
                  {filteredClaims.length}
                </p>
              </div>
            </div>
          </Card>

          <Card className="glass-card p-3 h-[60px]">
            <div className="flex items-center space-x-2 h-full">
              <div className="p-1.5 bg-yellow-500/20 rounded">
                <AlertCircle className="h-3 w-3 text-yellow-400" />
              </div>
              <div>
                <p className="text-white/60 text-xs">На рассмотрении</p>
                <p className="text-lg font-bold text-white">
                  {getPendingCount()}
                </p>
              </div>
            </div>
          </Card>

          <Card className="glass-card p-3 h-[60px]">
            <div className="flex items-center space-x-2 h-full">
              <div className="p-1.5 bg-green-500/20 rounded">
                <TrendingUp className="h-3 w-3 text-green-400" />
              </div>
              <div>
                <p className="text-white/60 text-xs">Общая стоимость</p>
                <p className="text-lg font-bold text-white">
                  {formatCurrency(getTotalValue())}
                </p>
              </div>
            </div>
          </Card>

          <Card className="glass-card p-3 h-[60px]">
            <div className="flex items-center space-x-2 h-full">
              <div className="p-1.5 bg-purple-500/20 rounded">
                <MapPin className="h-3 w-3 text-purple-400" />
              </div>
              <div>
                <p className="text-white/60 text-xs">Всего в базе</p>
                <p className="text-lg font-bold text-white">{total}</p>
              </div>
            </div>
          </Card>
        </div>

        <div className="flex gap-2">
          <Button
            size="sm"
            variant="outline"
            onClick={() => loadClaims(true)}
            disabled={loading || refreshing}
            className="border-white/20 text-white hover:bg-white/10 h-[60px]"
          >
            <RefreshCw
              className={`h-4 w-4 mr-2 ${refreshing ? "animate-spin" : ""}`}
            />
            Обновить
          </Button>
        </div>
      </div>

      {/* Фильтры */}
      <div className="flex items-center gap-3">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-white/40" />
          <Input
            placeholder="Поиск по товару, номеру заявки, причине..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="glass-input pl-10 text-white placeholder:text-white/40"
          />
        </div>

        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="glass-input text-white text-sm px-3 py-2 rounded-lg bg-white/5 border border-white/10"
        >
          <option value="all">Все статусы</option>
          {getUniqueStatuses().map((status) => (
            <option key={status} value={status}>
              {status}
            </option>
          ))}
        </select>

        <label className="flex items-center gap-2 text-white text-sm">
          <input
            type="checkbox"
            checked={archiveFilter}
            onChange={(e) => setArchiveFilter(e.target.checked)}
            className="rounded"
          />
          Только архив
        </label>
      </div>

      {/* Список заявок */}
      <div className="flex-1 overflow-hidden">
        {loading ? (
          <div className="flex items-center justify-center h-64">
            <div className="animate-spin rounded-full h-8 w-8 border-2 border-white border-t-transparent"></div>
            <span className="ml-3 text-white/60">Загрузка заявок...</span>
          </div>
        ) : (
          <div className="h-full overflow-y-auto space-y-3">
            {filteredClaims.length === 0 ? (
              <Card className="glass-card p-8 text-center">
                <RotateCcw className="h-12 w-12 text-white/40 mx-auto mb-4" />
                <h3 className="text-lg font-semibold text-white mb-2">
                  {claims.length === 0
                    ? "Нет заявок на возврат"
                    : "Нет заявок по фильтру"}
                </h3>
                <p className="text-white/60">
                  {claims.length === 0
                    ? "Заявки на возврат товаров появятся здесь"
                    : "Попробуйте изменить параметры фильтрации"}
                </p>
              </Card>
            ) : (
              filteredClaims.map((claim) => (
                <Card
                  key={claim.id}
                  className="glass-card p-4 hover:bg-white/10 transition-colors"
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1">
                      <div className="flex items-center gap-3 mb-3">
                        <h3 className="text-white font-medium">
                          {claim.productName}
                        </h3>
                        {getStatusBadge(claim.status)}
                      </div>

                      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 text-sm mb-3">
                        <div>
                          <p className="text-white/60">Артикул WB</p>
                          <p className="text-white font-mono">{claim.nmId}</p>
                        </div>
                        <div>
                          <p className="text-white/60">ID заявки</p>
                          <p className="text-white font-mono text-xs">
                            {claim.id.substring(0, 8)}...
                          </p>
                        </div>
                        <div>
                          <p className="text-white/60">Стоимость</p>
                          <p className="text-white font-semibold">
                            {formatCurrency(claim.price)}
                          </p>
                        </div>
                        <div>
                          <p className="text-white/60">Дата заявки</p>
                          <p className="text-white">
                            {formatDate(claim.returnDate)}
                          </p>
                        </div>
                      </div>

                      {claim.userComment && (
                        <div className="mb-3">
                          <p className="text-white/60 text-sm mb-1">
                            Комментарий покупателя:
                          </p>
                          <p className="text-white text-sm bg-white/5 rounded p-2">
                            {claim.userComment}
                          </p>
                        </div>
                      )}

                      {claim.wbComment && (
                        <div className="mb-3">
                          <p className="text-white/60 text-sm mb-1">
                            Ответ WB:
                          </p>
                          <p className="text-white text-sm bg-blue-500/10 rounded p-2">
                            {claim.wbComment}
                          </p>
                        </div>
                      )}

                      {claim.photos.length > 0 && (
                        <div className="mb-3">
                          <p className="text-white/60 text-sm mb-2">
                            Фотографии ({claim.photos.length}):
                          </p>
                          <div className="flex gap-2">
                            {claim.photos.slice(0, 3).map((photo, index) => (
                              <a
                                key={index}
                                href={`https:${photo}`}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="block w-16 h-16 bg-white/10 rounded overflow-hidden hover:bg-white/20 transition-colors"
                              >
                                <img
                                  src={`https:${photo}`}
                                  alt={`Фото ${index + 1}`}
                                  className="w-full h-full object-cover"
                                />
                              </a>
                            ))}
                            {claim.photos.length > 3 && (
                              <div className="w-16 h-16 bg-white/10 rounded flex items-center justify-center text-white/60 text-xs">
                                +{claim.photos.length - 3}
                              </div>
                            )}
                          </div>
                        </div>
                      )}

                      <div className="flex items-center justify-between text-xs text-white/60">
                        <span>
                          Заказ от: {formatDate(claim.orderDate)}
                        </span>
                        <span>
                          Обновлено: {formatDate(claim.lastUpdate)}
                        </span>
                      </div>
                    </div>

                    <div className="flex items-center gap-2 ml-4">
                      <Button
                        size="sm"
                        variant="ghost"
                        className="text-white/60 hover:text-white hover:bg-white/10"
                        title="Подробности"
                      >
                        <Eye className="h-4 w-4" />
                      </Button>
                      {claim.actions.length > 0 && (
                        <Button
                          size="sm"
                          variant="ghost"
                          className="text-white/60 hover:text-white hover:bg-white/10"
                          title="Ответить на заявку"
                        >
                          <MessageCircle className="h-4 w-4" />
                        </Button>
                      )}
                    </div>
                  </div>
                </Card>
              ))
            )}
          </div>
        )}
      </div>
    </div>
  );
}
