"use client";

import * as React from "react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
  Loader2,
  Eye,
  Globe,
  CheckCircle,
  Building2,
  Info
} from "lucide-react";
import { cn } from "@/lib/utils";
import { toast } from "sonner";
import { getAvlVendorsForRfq } from "../service";

interface AvlVendor {
  id: number;
  vendorId: number | null;
  vendorName: string | null;
  vendorCode: string | null;
  avlVendorName: string | null;
  tier: string | null;
  headquarterLocation: string | null;
  manufacturingLocation: string | null;
  materialGroupCode: string;
  materialGroupName: string | null;
  packageName: string | null;
  isAgent: boolean;
  hasAvl: boolean;
  isBlacklist: boolean;
  isBcc: boolean;
  remark: string | null;
}

// 더 이상 계약 인터페이스 필요 없음 - 참조용으로만 사용

interface AvlVendorDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  rfqId: number;
}

export function AvlVendorDialog({
  open,
  onOpenChange,
  rfqId,
}: AvlVendorDialogProps) {
  const [isLoadingAvl, setIsLoadingAvl] = React.useState(false);
  const [avlVendors, setAvlVendors] = React.useState<AvlVendor[]>([]);
  const [existingVendorIds, setExistingVendorIds] = React.useState<Set<number>>(new Set());

  // AVL 벤더 로드 (참조용)
  const loadAvlVendors = React.useCallback(async () => {
    setIsLoadingAvl(true);
    try {
      const result = await getAvlVendorsForRfq(rfqId);
      if (result.success && result.vendors) {
        setAvlVendors(result.vendors as AvlVendor[]);

        // 이미 RFQ에 추가된 벤더 ID 설정 (참조용)
        const existingIds = new Set(result.existingVendorIds || []);
        setExistingVendorIds(existingIds);

        if (result.vendors.length === 0) {
          toast.info("해당 프로젝트와 자재그룹에 대한 AVL 벤더가 없습니다.");
        }
      } else {
        toast.error(result.error || "AVL 데이터를 불러오는데 실패했습니다.");
      }
    } catch (error) {
      console.error("Failed to load AVL vendors:", error);
      toast.error("AVL 데이터를 불러오는데 실패했습니다.");
    } finally {
      setIsLoadingAvl(false);
    }
  }, [rfqId]);

  // 다이얼로그 열릴 때 데이터 로드
  React.useEffect(() => {
    if (open) {
      loadAvlVendors();
    }
  }, [open, loadAvlVendors]);

  // 초기화
  React.useEffect(() => {
    if (!open) {
      setAvlVendors([]);
      setExistingVendorIds(new Set());
    }
  }, [open]);

  // 더 이상 핸들러 함수나 필터링이 필요 없음 - 참조용으로만 사용

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh] p-0 flex flex-col">
        <DialogHeader className="p-6 pb-0">
          <DialogTitle className="flex items-center gap-2">
            <Eye className="h-5 w-5 text-primary" />
            AVL 벤더 목록 조회
          </DialogTitle>
          <DialogDescription>
            동일한 자재그룹코드를 다루는 AVL 등록 벤더들의 목록을 확인할 수 있습니다.
          </DialogDescription>
        </DialogHeader>

        {isLoadingAvl ? (
          <div className="flex-1 flex items-center justify-center p-8">
            <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
          </div>
        ) : (
          <div className="flex-1 flex flex-col px-6 py-4 overflow-hidden min-h-0">
            {avlVendors.length === 0 ? (
              <Alert>
                <Info className="h-4 w-4" />
                <AlertDescription>
                  해당 프로젝트와 자재그룹에 대한 AVL 벤더가 없습니다.
                </AlertDescription>
              </Alert>
            ) : (
              <Card className="flex flex-col flex-1 min-h-0">
                <CardHeader>
                  <CardTitle className="text-lg flex items-center justify-between">
                    <span>AVL 등록 벤더 목록</span>
                    <Badge variant="outline">
                      총 {avlVendors.length}개 업체
                    </Badge>
                  </CardTitle>
                  <CardDescription>
                    동일한 자재그룹코드를 다루는 AVL 등록 벤더들의 정보입니다.
                  </CardDescription>
                </CardHeader>
                <CardContent className="flex-1 min-h-0">
                  <ScrollArea className="h-[500px] pr-4">
                    <div className="space-y-3">
                      {avlVendors.map((vendor) => {
                        const isInCurrentRfq = vendor.vendorId && existingVendorIds.has(vendor.vendorId);
                        const isInternational = vendor.headquarterLocation &&
                          vendor.headquarterLocation !== "KR" &&
                          vendor.headquarterLocation !== "한국";

                        return (
                          <div
                            key={vendor.id}
                            className={cn(
                              "flex items-center justify-between p-4 rounded-lg border bg-card",
                              isInCurrentRfq && "bg-blue-50 border-blue-200"
                            )}
                          >
                            <div className="flex items-center gap-3 flex-1">
                              <Building2 className="h-5 w-5 text-muted-foreground flex-shrink-0" />
                              <div className="flex flex-col flex-1 min-w-0">
                                <div className="flex items-center gap-2 flex-wrap">
                                  <span className="font-medium">{vendor.vendorName}</span>
                                  {vendor.vendorCode && (
                                    <Badge variant="outline" className="text-xs">
                                      {vendor.vendorCode}
                                    </Badge>
                                  )}
                                  {isInCurrentRfq && (
                                    <Badge variant="default" className="text-xs bg-blue-600">
                                      <CheckCircle className="h-3 w-3 mr-1" />
                                      RFQ 참여중
                                    </Badge>
                                  )}
                                </div>
                                <div className="flex items-center gap-2 mt-1 flex-wrap">
                                  {vendor.tier && (
                                    <Badge variant="outline" className="text-xs">
                                      등급: {vendor.tier}
                                    </Badge>
                                  )}
                                  {isInternational ? (
                                    <Badge variant="secondary" className="text-xs">
                                      <Globe className="h-3 w-3 mr-1" />
                                      {vendor.headquarterLocation}
                                    </Badge>
                                  ) : (
                                    <Badge variant="default" className="text-xs">
                                      국내
                                    </Badge>
                                  )}
                                  {vendor.materialGroupName && (
                                    <span className="text-xs text-muted-foreground">
                                      {vendor.materialGroupName}
                                    </span>
                                  )}
                                  {vendor.isAgent && (
                                    <Badge variant="secondary" className="text-xs">
                                      Agent
                                    </Badge>
                                  )}
                                </div>
                                {vendor.remark && (
                                  <div className="text-xs text-muted-foreground mt-1">
                                    {vendor.remark}
                                  </div>
                                )}
                              </div>
                            </div>

                            <div className="flex items-center gap-1 flex-shrink-0">
                              {vendor.hasAvl && (
                                <Badge variant="default" className="text-xs bg-green-600">
                                  <CheckCircle className="h-3 w-3 mr-1" />
                                  AVL
                                </Badge>
                              )}
                              {vendor.isBcc && (
                                <Badge variant="outline" className="text-xs">
                                  BCC
                                </Badge>
                              )}
                              {vendor.isBlacklist && (
                                <Badge variant="destructive" className="text-xs">
                                  Blacklist
                                </Badge>
                              )}
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </ScrollArea>
                </CardContent>
              </Card>
            )}
          </div>
        )}

        <DialogFooter className="p-6 pt-0 border-t">
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
          >
            닫기
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}