"use client";

import React, { useState } from "react";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { StatsCard } from "../ui/stats-card";
import { StatsGrid } from "../ui/stats-grid";
import { useQuery, useMutation } from "@apollo/client";
import { GET_SUPPLY_ORDERS } from "@/graphql/queries";
import { UPDATE_SUPPLY_ORDER_STATUS } from "@/graphql/mutations";
import { useAuth } from "@/hooks/useAuth";
import { toast } from "sonner";
import {
  Calendar,
  Building2,
  TrendingUp,
  DollarSign,
  Wrench,
  Package2,
  ChevronDown,
  ChevronRight,
  User,
  CheckCircle,
  XCircle,
  Clock,
  Truck,
} from "lucide-react";

interface SupplyOrderItem {
  id: string;
  quantity: number;
  price: number;
  totalPrice: number;
  product: {
    id: string;
    name: string;
    article: string;
    description?: string;
    category?: {
      id: string;
      name: string;
    };
  };
}

interface SupplyOrder {
  id: string;
  organizationId: string;
  deliveryDate: string;
  status: "PENDING" | "CONFIRMED" | "IN_TRANSIT" | "DELIVERED" | "CANCELLED";
  totalAmount: number;
  totalItems: number;
  fulfillmentCenterId?: string;
  createdAt: string;
  updatedAt: string;
  partner: {
    id: string;
    name?: string;
    fullName?: string;
    inn: string;
    address?: string;
    phones?: string[];
    emails?: string[];
  };
  organization: {
    id: string;
    name?: string;
    fullName?: string;
    type: string;
  };
  fulfillmentCenter?: {
    id: string;
    name?: string;
    fullName?: string;
    type: string;
  };
  items: SupplyOrderItem[];
}

export function RealSupplyOrdersTab() {
  const [expandedOrders, setExpandedOrders] = useState<Set<string>>(new Set());
  const { user } = useAuth();

  const { data, loading, error, refetch } = useQuery(GET_SUPPLY_ORDERS, {
    fetchPolicy: "cache-and-network",
    notifyOnNetworkStatusChange: true,
  });

  // Мутация для обновления статуса заказа
  const [updateSupplyOrderStatus, { loading: updating }] = useMutation(
    UPDATE_SUPPLY_ORDER_STATUS,
    {
      onCompleted: (data) => {
        if (data.updateSupplyOrderStatus.success) {
          toast.success(data.updateSupplyOrderStatus.message);
          refetch(); // Обновляем список заказов
        } else {
          toast.error(data.updateSupplyOrderStatus.message);
        }
      },
      onError: (error) => {
        console.error("Error updating supply order status:", error);
        toast.error("Ошибка при обновлении статуса заказа");
      },
    }
  );

  // Получаем ID текущей организации (оптовика)
  const currentOrganizationId = user?.organization?.id;

  // Фильтруем заказы где текущая организация является поставщиком (заказы К оптовику)
  const incomingSupplyOrders: SupplyOrder[] = (data?.supplyOrders || []).filter(
    (order: SupplyOrder) => {
      // Показываем заказы где текущий оптовик указан как поставщик (partnerId)
      return order.partner.id === currentOrganizationId;
    }
  );

  const toggleOrderExpansion = (orderId: string) => {
    const newExpanded = new Set(expandedOrders);
    if (newExpanded.has(orderId)) {
      newExpanded.delete(orderId);
    } else {
      newExpanded.add(orderId);
    }
    setExpandedOrders(newExpanded);
  };

  const handleStatusUpdate = async (
    orderId: string,
    newStatus: SupplyOrder["status"]
  ) => {
    try {
      await updateSupplyOrderStatus({
        variables: {
          id: orderId,
          status: newStatus,
        },
      });
    } catch (error) {
      console.error("Error updating status:", error);
    }
  };

  const getStatusBadge = (status: SupplyOrder["status"]) => {
    const statusMap = {
      PENDING: {
        label: "Ожидает одобрения",
        color: "bg-blue-500/20 text-blue-300 border-blue-500/30",
        icon: Clock,
      },
      CONFIRMED: {
        label: "Одобрена",
        color: "bg-green-500/20 text-green-300 border-green-500/30",
        icon: CheckCircle,
      },
      IN_TRANSIT: {
        label: "В пути",
        color: "bg-yellow-500/20 text-yellow-300 border-yellow-500/30",
        icon: Truck,
      },
      DELIVERED: {
        label: "Доставлена",
        color: "bg-purple-500/20 text-purple-300 border-purple-500/30",
        icon: Package2,
      },
      CANCELLED: {
        label: "Отклонена",
        color: "bg-red-500/20 text-red-300 border-red-500/30",
        icon: XCircle,
      },
    };

    const { label, color, icon: Icon } = statusMap[status];

    return (
      <Badge className={`${color} border flex items-center gap-1`}>
        <Icon className="h-3 w-3" />
        {label}
      </Badge>
    );
  };

  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 formatDateTime = (dateString: string) => {
    return new Date(dateString).toLocaleString("ru-RU", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  // Статистика для оптовика
  const totalOrders = incomingSupplyOrders.length;
  const totalAmount = incomingSupplyOrders.reduce(
    (sum, order) => sum + order.totalAmount,
    0
  );
  const totalItems = incomingSupplyOrders.reduce(
    (sum, order) => sum + order.totalItems,
    0
  );
  const pendingOrders = incomingSupplyOrders.filter(
    (order) => order.status === "PENDING"
  ).length;
  const approvedOrders = incomingSupplyOrders.filter(
    (order) => order.status === "CONFIRMED"
  ).length;
  const inTransitOrders = incomingSupplyOrders.filter(
    (order) => order.status === "IN_TRANSIT"
  ).length;

  if (loading) {
    return (
      <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>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <Wrench className="h-12 w-12 text-red-400 mx-auto mb-4" />
          <p className="text-red-400 font-medium">Ошибка загрузки заявок</p>
          <p className="text-white/60 text-sm mt-2">{error.message}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Статистика входящих заявок */}
      <StatsGrid>
        <StatsCard
          title="Всего заявок"
          value={totalOrders}
          icon={Package2}
          iconColor="text-orange-400"
          iconBg="bg-orange-500/20"
          subtitle="Заявки от селлеров"
        />

        <StatsCard
          title="Ожидают одобрения"
          value={pendingOrders}
          icon={Clock}
          iconColor="text-blue-400"
          iconBg="bg-blue-500/20"
          subtitle="Требуют решения"
        />

        <StatsCard
          title="Одобрено"
          value={approvedOrders}
          icon={CheckCircle}
          iconColor="text-green-400"
          iconBg="bg-green-500/20"
          subtitle="Готовы к отправке"
        />

        <StatsCard
          title="В пути"
          value={inTransitOrders}
          icon={Truck}
          iconColor="text-yellow-400"
          iconBg="bg-yellow-500/20"
          subtitle="Доставляются"
        />

        <StatsCard
          title="Общая сумма"
          value={formatCurrency(totalAmount)}
          icon={TrendingUp}
          iconColor="text-green-400"
          iconBg="bg-green-500/20"
          subtitle="Стоимость заявок"
        />

        <StatsCard
          title="Всего единиц"
          value={totalItems}
          icon={Wrench}
          iconColor="text-purple-400"
          iconBg="bg-purple-500/20"
          subtitle="Количество товаров"
        />
      </StatsGrid>

      {/* Список входящих заявок */}
      {incomingSupplyOrders.length === 0 ? (
        <Card className="bg-white/10 backdrop-blur border-white/20 p-8">
          <div className="text-center">
            <Wrench className="h-16 w-16 text-white/20 mx-auto mb-4" />
            <h3 className="text-lg font-semibold text-white mb-2">
              Пока нет заявок
            </h3>
            <p className="text-white/60">
              Здесь будут отображаться заявки от селлеров на поставку товаров
            </p>
          </div>
        </Card>
      ) : (
        <Card className="bg-white/10 backdrop-blur border-white/20 overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-white/20">
                  <th className="text-left p-4 text-white font-semibold">ID</th>
                  <th className="text-left p-4 text-white font-semibold">
                    Заказчик
                  </th>
                  <th className="text-left p-4 text-white font-semibold">
                    Дата поставки
                  </th>
                  <th className="text-left p-4 text-white font-semibold">
                    Дата заявки
                  </th>
                  <th className="text-left p-4 text-white font-semibold">
                    Количество
                  </th>
                  <th className="text-left p-4 text-white font-semibold">
                    Сумма
                  </th>
                  <th className="text-left p-4 text-white font-semibold">
                    Статус
                  </th>
                  <th className="text-left p-4 text-white font-semibold">
                    Действия
                  </th>
                </tr>
              </thead>
              <tbody>
                {incomingSupplyOrders.map((order) => {
                  const isOrderExpanded = expandedOrders.has(order.id);

                  return (
                    <React.Fragment key={order.id}>
                      {/* Основная строка заказа */}
                      <tr className="border-b border-white/10 hover:bg-white/5 transition-colors">
                        <td className="p-4">
                          <div className="flex items-center space-x-2">
                            <button
                              onClick={() => toggleOrderExpansion(order.id)}
                              className="text-white/60 hover:text-white"
                            >
                              {isOrderExpanded ? (
                                <ChevronDown className="h-4 w-4" />
                              ) : (
                                <ChevronRight className="h-4 w-4" />
                              )}
                            </button>
                            <span className="text-white font-medium">
                              {order.id.slice(-8)}
                            </span>
                          </div>
                        </td>
                        <td className="p-4">
                          <div className="space-y-1">
                            <div className="flex items-center space-x-2">
                              <User className="h-4 w-4 text-white/40" />
                              <span className="text-white font-medium">
                                {order.organization.name ||
                                  order.organization.fullName ||
                                  "Заказчик"}
                              </span>
                            </div>
                            <p className="text-white/60 text-sm">
                              Тип: {order.organization.type}
                            </p>
                          </div>
                        </td>
                        <td className="p-4">
                          <div className="flex items-center space-x-2">
                            <Calendar className="h-4 w-4 text-white/40" />
                            <span className="text-white font-semibold">
                              {formatDate(order.deliveryDate)}
                            </span>
                          </div>
                        </td>
                        <td className="p-4">
                          <span className="text-white/80">
                            {formatDateTime(order.createdAt)}
                          </span>
                        </td>
                        <td className="p-4">
                          <span className="text-white font-semibold">
                            {order.totalItems} шт
                          </span>
                        </td>
                        <td className="p-4">
                          <div className="flex items-center space-x-2">
                            <DollarSign className="h-4 w-4 text-white/40" />
                            <span className="text-green-400 font-bold">
                              {formatCurrency(order.totalAmount)}
                            </span>
                          </div>
                        </td>
                        <td className="p-4">{getStatusBadge(order.status)}</td>
                        <td className="p-4">
                          <div className="flex items-center space-x-2">
                            {order.status === "PENDING" && (
                              <>
                                <Button
                                  size="sm"
                                  onClick={() =>
                                    handleStatusUpdate(order.id, "CONFIRMED")
                                  }
                                  disabled={updating}
                                  className="bg-green-500/20 hover:bg-green-500/30 text-green-300 border border-green-500/30"
                                >
                                  <CheckCircle className="h-4 w-4 mr-1" />
                                  Одобрить
                                </Button>
                                <Button
                                  size="sm"
                                  onClick={() =>
                                    handleStatusUpdate(order.id, "CANCELLED")
                                  }
                                  disabled={updating}
                                  className="bg-red-500/20 hover:bg-red-500/30 text-red-300 border border-red-500/30"
                                >
                                  <XCircle className="h-4 w-4 mr-1" />
                                  Отказать
                                </Button>
                              </>
                            )}
                            {order.status === "CONFIRMED" && (
                              <Button
                                size="sm"
                                onClick={() =>
                                  handleStatusUpdate(order.id, "IN_TRANSIT")
                                }
                                disabled={updating}
                                className="bg-yellow-500/20 hover:bg-yellow-500/30 text-yellow-300 border border-yellow-500/30"
                              >
                                <Truck className="h-4 w-4 mr-1" />
                                Отправить
                              </Button>
                            )}
                            {order.status === "CANCELLED" && (
                              <span className="text-red-400 text-sm">
                                Отклонена
                              </span>
                            )}
                            {order.status === "IN_TRANSIT" && (
                              <span className="text-yellow-400 text-sm">
                                В пути
                              </span>
                            )}
                            {order.status === "DELIVERED" && (
                              <span className="text-green-400 text-sm">
                                Доставлена
                              </span>
                            )}
                          </div>
                        </td>
                      </tr>

                      {/* Развернутая информация о заказе */}
                      {isOrderExpanded && (
                        <tr>
                          <td colSpan={8} className="p-0">
                            <div className="bg-white/5 border-t border-white/10">
                              <div className="p-6">
                                <h4 className="text-white font-semibold mb-4">
                                  Состав заявки:
                                </h4>
                                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                                  {order.items.map((item) => (
                                    <Card
                                      key={item.id}
                                      className="bg-white/10 backdrop-blur border-white/20 p-4"
                                    >
                                      <div className="space-y-3">
                                        <div>
                                          <h5 className="text-white font-medium mb-1">
                                            {item.product.name}
                                          </h5>
                                          <p className="text-white/60 text-sm">
                                            Артикул: {item.product.article}
                                          </p>
                                          {item.product.category && (
                                            <Badge className="bg-purple-500/20 text-purple-300 border-purple-500/30 text-xs mt-2">
                                              {item.product.category.name}
                                            </Badge>
                                          )}
                                        </div>
                                        <div className="flex items-center justify-between">
                                          <div className="text-sm">
                                            <p className="text-white/60">
                                              Количество: {item.quantity} шт
                                            </p>
                                            <p className="text-white/60">
                                              Цена: {formatCurrency(item.price)}
                                            </p>
                                          </div>
                                          <div className="text-right">
                                            <p className="text-green-400 font-semibold">
                                              {formatCurrency(item.totalPrice)}
                                            </p>
                                          </div>
                                        </div>
                                      </div>
                                    </Card>
                                  ))}
                                </div>
                              </div>
                            </div>
                          </td>
                        </tr>
                      )}
                    </React.Fragment>
                  );
                })}
              </tbody>
            </table>
          </div>
        </Card>
      )}
    </div>
  );
}
