"use client";

import { useState } from "react";
import { useQuery, useMutation } from "@apollo/client";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
import { useAuth } from "@/hooks/useAuth";
import { GET_SUPPLY_ORDERS } from "@/graphql/queries";
import { 
  SUPPLIER_APPROVE_ORDER, 
  SUPPLIER_REJECT_ORDER,
  SUPPLIER_SHIP_ORDER 
} from "@/graphql/mutations";
import { toast } from "sonner";
import {
  Calendar,
  Package,
  Truck,
  User,
  CheckCircle,
  Clock,
  XCircle,
  MapPin,
  Phone,
  Mail,
  Building,
  Hash,
  AlertTriangle,
} from "lucide-react";

interface SupplyOrder {
  id: string;
  organizationId: string;
  partnerId: string;
  deliveryDate: string;
  status: "PENDING" | "SUPPLIER_APPROVED" | "LOGISTICS_CONFIRMED" | "SHIPPED" | "DELIVERED" | "CANCELLED";
  totalAmount: number;
  totalItems: number;
  createdAt: string;
  organization: {
    id: string;
    name?: string;
    fullName?: string;
    type: string;
  };
  fulfillmentCenter?: {
    id: string;
    name?: string;
    fullName?: string;
    type: string;
  };
  logisticsPartner?: {
    id: string;
    name?: string;
    fullName?: string;
    type: string;
  };
  items: Array<{
    id: string;
    quantity: number;
    price: number;
    totalPrice: number;
    product: {
      id: string;
      name: string;
      article: string;
      description?: string;
      category?: {
        id: string;
        name: string;
      };
    };
  }>;
}

export function SupplierOrdersContent() {
  const { user } = useAuth();
  const [expandedOrders, setExpandedOrders] = useState<Set<string>>(new Set());
  const [rejectReason, setRejectReason] = useState<string>("");
  const [showRejectModal, setShowRejectModal] = useState<string | null>(null);

  // Загружаем заказы поставок
  const { data, loading, error, refetch } = useQuery(GET_SUPPLY_ORDERS, {
    fetchPolicy: "cache-and-network",
  });

  // Мутации для действий поставщика
  const [supplierApproveOrder] = useMutation(SUPPLIER_APPROVE_ORDER, {
    refetchQueries: [{ query: GET_SUPPLY_ORDERS }],
    awaitRefetchQueries: true,
    onCompleted: (data) => {
      if (data.supplierApproveOrder.success) {
        toast.success(data.supplierApproveOrder.message);
      } else {
        toast.error(data.supplierApproveOrder.message);
      }
    },
    onError: (error) => {
      console.error("Error approving order:", error);
      toast.error("Ошибка при одобрении заказа");
    },
  });

  const [supplierRejectOrder] = useMutation(SUPPLIER_REJECT_ORDER, {
    refetchQueries: [{ query: GET_SUPPLY_ORDERS }],
    onCompleted: (data) => {
      if (data.supplierRejectOrder.success) {
        toast.success(data.supplierRejectOrder.message);
      } else {
        toast.error(data.supplierRejectOrder.message);
      }
      setShowRejectModal(null);
      setRejectReason("");
    },
    onError: (error) => {
      console.error("Error rejecting order:", error);
      toast.error("Ошибка при отклонении заказа");
    },
  });

  const [supplierShipOrder] = useMutation(SUPPLIER_SHIP_ORDER, {
    refetchQueries: [{ query: GET_SUPPLY_ORDERS }],
    onCompleted: (data) => {
      if (data.supplierShipOrder.success) {
        toast.success(data.supplierShipOrder.message);
      } else {
        toast.error(data.supplierShipOrder.message);
      }
    },
    onError: (error) => {
      console.error("Error shipping order:", error);
      toast.error("Ошибка при отправке заказа");
    },
  });

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

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

  const getStatusBadge = (status: SupplyOrder["status"]) => {
    const statusMap = {
      PENDING: {
        label: "Ожидает одобрения",
        color: "bg-yellow-500/20 text-yellow-300 border-yellow-500/30",
        icon: Clock,
      },
      SUPPLIER_APPROVED: {
        label: "Ожидает подтверждения логистики",
        color: "bg-blue-500/20 text-blue-300 border-blue-500/30",
        icon: Clock,
      },
      LOGISTICS_CONFIRMED: {
        label: "Готов к отправке",
        color: "bg-cyan-500/20 text-cyan-300 border-cyan-500/30",
        icon: CheckCircle,
      },
      SHIPPED: {
        label: "Отправлено",
        color: "bg-orange-500/20 text-orange-300 border-orange-500/30",
        icon: Truck,
      },
      DELIVERED: {
        label: "Доставлено",
        color: "bg-green-500/20 text-green-300 border-green-500/30",
        icon: Package,
      },
      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 text-xs`}>
        <Icon className="h-3 w-3" />
        {label}
      </Badge>
    );
  };

  const handleApproveOrder = async (orderId: string) => {
    await supplierApproveOrder({ variables: { id: orderId } });
  };

  const handleRejectOrder = async (orderId: string) => {
    await supplierRejectOrder({
      variables: { id: orderId, reason: rejectReason || undefined },
    });
  };

  const handleShipOrder = async (orderId: string) => {
    await supplierShipOrder({ variables: { id: orderId } });
  };

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

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

  const getInitials = (name: string): string => {
    return name
      .split(" ")
      .map((word) => word.charAt(0))
      .join("")
      .toUpperCase()
      .slice(0, 2);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-white">Загрузка заказов...</div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-red-300">Ошибка загрузки заказов: {error.message}</div>
      </div>
    );
  }

  return (
    <div className="space-y-6 p-4">
      {/* Заголовок */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white mb-2">
            Заказы поставок
          </h1>
          <p className="text-white/60">
            Управление входящими заказами от фулфилмент-центров
          </p>
        </div>
      </div>

      {/* Статистика */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <Card className="bg-white/10 backdrop-blur border-white/20 p-4">
          <div className="flex items-center space-x-3">
            <div className="p-2 bg-yellow-500/20 rounded">
              <Clock className="h-5 w-5 text-yellow-400" />
            </div>
            <div>
              <p className="text-white/60 text-sm">Ожидают одобрения</p>
              <p className="text-xl font-bold text-white">
                {supplierOrders.filter(order => order.status === "PENDING").length}
              </p>
            </div>
          </div>
        </Card>

        <Card className="bg-white/10 backdrop-blur border-white/20 p-4">
          <div className="flex items-center space-x-3">
            <div className="p-2 bg-cyan-500/20 rounded">
              <CheckCircle className="h-5 w-5 text-cyan-400" />
            </div>
            <div>
              <p className="text-white/60 text-sm">Готово к отправке</p>
              <p className="text-xl font-bold text-white">
                {supplierOrders.filter(order => order.status === "LOGISTICS_CONFIRMED").length}
              </p>
            </div>
          </div>
        </Card>

        <Card className="bg-white/10 backdrop-blur border-white/20 p-4">
          <div className="flex items-center space-x-3">
            <div className="p-2 bg-orange-500/20 rounded">
              <Truck className="h-5 w-5 text-orange-400" />
            </div>
            <div>
              <p className="text-white/60 text-sm">В пути</p>
              <p className="text-xl font-bold text-white">
                {supplierOrders.filter(order => order.status === "SHIPPED").length}
              </p>
            </div>
          </div>
        </Card>

        <Card className="bg-white/10 backdrop-blur border-white/20 p-4">
          <div className="flex items-center space-x-3">
            <div className="p-2 bg-green-500/20 rounded">
              <Package className="h-5 w-5 text-green-400" />
            </div>
            <div>
              <p className="text-white/60 text-sm">Доставлено</p>
              <p className="text-xl font-bold text-white">
                {supplierOrders.filter(order => order.status === "DELIVERED").length}
              </p>
            </div>
          </div>
        </Card>
      </div>

      {/* Список заказов */}
      <div className="space-y-4">
        {supplierOrders.length === 0 ? (
          <Card className="bg-white/10 backdrop-blur border-white/20 p-8">
            <div className="text-center">
              <Package className="h-12 w-12 text-white/40 mx-auto mb-4" />
              <h3 className="text-lg font-semibold text-white mb-2">
                Нет заказов поставок
              </h3>
              <p className="text-white/60">
                Входящие заказы от фулфилмент-центров будут отображаться здесь
              </p>
            </div>
          </Card>
        ) : (
          supplierOrders.map((order) => (
            <Card
              key={order.id}
              className="bg-white/10 backdrop-blur border-white/20 overflow-hidden hover:bg-white/15 transition-colors cursor-pointer"
              onClick={() => toggleOrderExpansion(order.id)}
            >
              {/* Основная информация о заказе */}
              <div className="p-4">
                <div className="flex items-center justify-between">
                  {/* Левая часть */}
                  <div className="flex items-center space-x-4 flex-1 min-w-0">
                    {/* Номер заказа */}
                    <div className="flex items-center space-x-2">
                      <Hash className="h-4 w-4 text-white/60" />
                      <span className="text-white font-semibold">
                        {order.id.slice(-8)}
                      </span>
                    </div>

                    {/* Заказчик */}
                    <div className="flex items-center space-x-3 min-w-0">
                      <Avatar className="w-8 h-8">
                        <AvatarFallback className="bg-blue-500 text-white text-sm">
                          {getInitials(order.organization.name || order.organization.fullName || "ФФ")}
                        </AvatarFallback>
                      </Avatar>
                      <div className="min-w-0">
                        <h3 className="text-white font-medium text-sm truncate">
                          {order.organization.name || order.organization.fullName}
                        </h3>
                        <p className="text-white/60 text-xs">
                          {order.organization.type === "FULFILLMENT" ? "Фулфилмент" : "Организация"}
                        </p>
                      </div>
                    </div>

                    {/* Краткая информация */}
                    <div className="hidden lg:flex items-center space-x-4">
                      <div className="flex items-center space-x-1">
                        <Calendar className="h-4 w-4 text-blue-400" />
                        <span className="text-white text-sm">
                          {formatDate(order.deliveryDate)}
                        </span>
                      </div>
                      <div className="flex items-center space-x-1">
                        <Package className="h-4 w-4 text-green-400" />
                        <span className="text-white text-sm">
                          {order.totalItems} шт.
                        </span>
                      </div>
                    </div>
                  </div>

                  {/* Правая часть - статус и действия */}
                  <div className="flex items-center space-x-3 flex-shrink-0">
                    {getStatusBadge(order.status)}

                    {/* Кнопки действий для поставщика */}
                    {order.status === "PENDING" && (
                      <div className="flex items-center space-x-2">
                        <Button
                          size="sm"
                          onClick={(e) => {
                            e.stopPropagation();
                            handleApproveOrder(order.id);
                          }}
                          className="bg-green-500/20 hover:bg-green-500/30 text-green-300 border border-green-500/30 text-xs px-3 py-1 h-7"
                        >
                          <CheckCircle className="h-3 w-3 mr-1" />
                          Одобрить
                        </Button>
                        <Button
                          size="sm"
                          onClick={(e) => {
                            e.stopPropagation();
                            setShowRejectModal(order.id);
                          }}
                          className="bg-red-500/20 hover:bg-red-500/30 text-red-300 border border-red-500/30 text-xs px-3 py-1 h-7"
                        >
                          <XCircle className="h-3 w-3 mr-1" />
                          Отклонить
                        </Button>
                      </div>
                    )}

                    {order.status === "LOGISTICS_CONFIRMED" && (
                      <Button
                        size="sm"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleShipOrder(order.id);
                        }}
                        className="bg-orange-500/20 hover:bg-orange-500/30 text-orange-300 border border-orange-500/30 text-xs px-3 py-1 h-7"
                      >
                        <Truck className="h-3 w-3 mr-1" />
                        Отправить
                      </Button>
                    )}
                  </div>
                </div>

                {/* Развернутые детали */}
                {expandedOrders.has(order.id) && (
                  <>
                    <Separator className="my-4 bg-white/10" />
                    
                    {/* Сумма заказа */}
                    <div className="mb-4 p-3 bg-white/5 rounded">
                      <div className="flex items-center justify-between">
                        <span className="text-white/60">Общая сумма:</span>
                        <span className="text-white font-semibold text-lg">
                          {formatCurrency(order.totalAmount)}
                        </span>
                      </div>
                    </div>

                    {/* Информация о логистике */}
                    {order.logisticsPartner && (
                      <div className="mb-4">
                        <h4 className="text-white font-semibold mb-2 flex items-center text-sm">
                          <Truck className="h-4 w-4 mr-2 text-purple-400" />
                          Логистическая компания
                        </h4>
                        <div className="bg-white/5 rounded p-3">
                          <p className="text-white">
                            {order.logisticsPartner.name || order.logisticsPartner.fullName}
                          </p>
                        </div>
                      </div>
                    )}

                    {/* Список товаров */}
                    <div>
                      <h4 className="text-white font-semibold mb-3 flex items-center text-sm">
                        <Package className="h-4 w-4 mr-2 text-green-400" />
                        Товары ({order.items.length})
                      </h4>
                      <div className="space-y-2">
                        {order.items.map((item) => (
                          <div
                            key={item.id}
                            className="bg-white/5 rounded p-3 flex items-center justify-between"
                          >
                            <div className="flex-1 min-w-0">
                              <h5 className="text-white font-medium text-sm">
                                {item.product.name}
                              </h5>
                              <p className="text-white/60 text-xs">
                                Артикул: {item.product.article}
                              </p>
                              {item.product.category && (
                                <Badge
                                  variant="secondary"
                                  className="bg-blue-500/20 text-blue-300 text-xs mt-1"
                                >
                                  {item.product.category.name}
                                </Badge>
                              )}
                            </div>
                            <div className="text-right flex-shrink-0 ml-4">
                              <p className="text-white font-semibold">
                                {item.quantity} шт.
                              </p>
                              <p className="text-white/60 text-xs">
                                {formatCurrency(item.price)}
                              </p>
                              <p className="text-green-400 font-semibold text-sm">
                                {formatCurrency(item.totalPrice)}
                              </p>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  </>
                )}
              </div>
            </Card>
          ))
        )}
      </div>

      {/* Модальное окно для отклонения заказа */}
      {showRejectModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <Card className="bg-gray-900 border-white/20 p-6 max-w-md w-full mx-4">
            <h3 className="text-white font-semibold text-lg mb-4">
              Отклонить заказ
            </h3>
            <p className="text-white/60 text-sm mb-4">
              Укажите причину отклонения заказа (необязательно):
            </p>
            <textarea
              value={rejectReason}
              onChange={(e) => setRejectReason(e.target.value)}
              placeholder="Причина отклонения..."
              className="w-full bg-white/10 border border-white/20 rounded-md px-3 py-2 text-white text-sm focus:outline-none focus:ring-1 focus:ring-red-500 focus:border-transparent mb-4"
              rows={3}
            />
            <div className="flex items-center space-x-3">
              <Button
                onClick={() => handleRejectOrder(showRejectModal)}
                className="bg-red-500/20 hover:bg-red-500/30 text-red-300 border border-red-500/30"
              >
                Отклонить заказ
              </Button>
              <Button
                onClick={() => {
                  setShowRejectModal(null);
                  setRejectReason("");
                }}
                variant="outline"
                className="border-white/20 text-white hover:bg-white/10"
              >
                Отмена
              </Button>
            </div>
          </Card>
        </div>
      )}
    </div>
  );
}