"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 { Loader2, Users } from "lucide-react";
import { toast } from "sonner";
import { assignPicToRfqs } from "../service";
import { Badge } from "@/components/ui/badge";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { 
  PurchaseGroupCodeSingleSelector,
  PurchaseGroupCodeWithUser 
} from "@/components/common/selectors/purchase-group-code";

interface RfqAssignPicDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  selectedRfqIds: number[];
  selectedRfqCodes: string[];
  onSuccess?: () => void;
}

export function RfqAssignPicDialog({
  open,
  onOpenChange,
  selectedRfqIds,
  selectedRfqCodes,
  onSuccess,
}: RfqAssignPicDialogProps) {
  const [isAssigning, setIsAssigning] = React.useState(false);
  const [selectedCode, setSelectedCode] = React.useState<PurchaseGroupCodeWithUser | undefined>(undefined);
  const [selectorOpen, setSelectorOpen] = React.useState(false);

  // 다이얼로그 열릴 때 초기화
  React.useEffect(() => {
    if (open) {
      setSelectedCode(undefined);
    }
  }, [open]);

  const handleCodeSelect = (code: PurchaseGroupCodeWithUser) => {
    setSelectedCode(code);
    
    // 유저 정보가 없는 경우 toast로 알림
    if (!code.user) {
      toast.warning(
        `해당 구매그룹코드(${code.PURCHASE_GROUP_CODE})의 사번 정보의 유저가 없습니다`,
        {
          description: `사번: ${code.EMPLOYEE_NUMBER}`,
          duration: 5000,
        }
      );
    }
  };

  const handleAssign = async () => {
    if (!selectedCode) {
      toast.error("구매그룹코드를 선택해주세요");
      return;
    }

    if (!selectedCode.user) {
      toast.error("선택한 구매그룹코드에 연결된 사용자가 없습니다");
      return;
    }

    if (selectedRfqIds.length === 0) {
      toast.error("담당자 지정이 가능한 ITB가 없습니다");
      return;
    }

    setIsAssigning(true);
    try {
      const result = await assignPicToRfqs({
        rfqIds: selectedRfqIds,
        picUserId: selectedCode.user.id,
      });

      if (result.success) {
        toast.success(result.message);
        onSuccess?.();
        onOpenChange(false);
      } else {
        toast.error(result.message);
      }
    } catch (error) {
      console.error("담당자 지정 오류:", error);
      toast.error("담당자 지정 중 오류가 발생했습니다");
    } finally {
      setIsAssigning(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Users className="h-5 w-5" />
            담당자 지정
          </DialogTitle>
          <DialogDescription>
            선택한 ITB에 구매 담당자를 지정합니다
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          {/* 선택된 ITB 정보 */}
          <div className="space-y-2">
            <label className="text-sm font-medium">선택된 ITB</label>
            <div className="p-3 bg-muted rounded-md">
              <div className="flex items-center gap-2 mb-2">
                <Badge variant="secondary">{selectedRfqCodes.length}건</Badge>
              </div>
              <div className="max-h-[100px] overflow-y-auto">
                <div className="flex flex-wrap gap-1">
                  {selectedRfqCodes.slice(0, 10).map((code, index) => (
                    <Badge key={index} variant="outline" className="text-xs">
                      {code}
                    </Badge>
                  ))}
                  {selectedRfqCodes.length > 10 && (
                    <Badge variant="outline" className="text-xs">
                      +{selectedRfqCodes.length - 10}개
                    </Badge>
                  )}
                </div>
              </div>
            </div>
            {selectedRfqCodes.length === 0 && (
              <Alert className="border-orange-200 bg-orange-50">
                <AlertDescription className="text-orange-800">
                  담당자 지정이 가능한 ITB가 없습니다. (상태가 "RFQ 생성" 또는 "구매담당지정"인 ITB만 가능)
                </AlertDescription>
              </Alert>
            )}
          </div>

          {/* 구매 담당자 선택 (구매그룹코드) */}
          <div className="space-y-2">
            <label className="text-sm font-medium">구매 담당자 (구매그룹코드)</label>
            <Button
              type="button"
              variant="outline"
              className="w-full justify-start h-auto min-h-[40px]"
              disabled={selectedRfqCodes.length === 0}
              onClick={() => setSelectorOpen(true)}
            >
              {selectedCode ? (
                <div className="flex flex-col items-start gap-1 w-full">
                  <div className="flex items-center gap-2">
                    <Badge variant="secondary" className="font-mono">
                      {selectedCode.PURCHASE_GROUP_CODE}
                    </Badge>
                    <span>{selectedCode.DISPLAY_NAME}</span>
                  </div>
                  {selectedCode.user && (
                    <div className="text-xs text-muted-foreground">
                      사용자: {selectedCode.user.name} ({selectedCode.user.email})
                    </div>
                  )}
                  {!selectedCode.user && (
                    <div className="text-xs text-orange-600">
                      ⚠️ 연결된 사용자가 없습니다
                    </div>
                  )}
                </div>
              ) : (
                <span className="text-muted-foreground">
                  구매그룹코드를 선택하세요
                </span>
              )}
            </Button>
            
            {selectedCode && !selectedCode.user && (
              <Alert className="border-orange-200 bg-orange-50">
                <AlertDescription className="text-orange-800 text-xs">
                  선택한 구매그룹코드에 연결된 사용자가 없습니다. 다른 구매그룹코드를 선택해주세요.
                </AlertDescription>
              </Alert>
            )}
          </div>
        </div>

        {/* 구매그룹코드 선택 다이얼로그 */}
        <PurchaseGroupCodeSingleSelector
          open={selectorOpen}
          onOpenChange={setSelectorOpen}
          selectedCode={selectedCode}
          onCodeSelect={handleCodeSelect}
          title="구매 담당자 선택"
          description="ITB에 지정할 구매 담당자의 구매그룹코드를 선택하세요"
          showConfirmButtons={false}
        />

        <DialogFooter>
          <Button
            type="button"
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={isAssigning}
          >
            취소
          </Button>
          <Button
            type="submit"
            onClick={handleAssign}
            disabled={!selectedCode || !selectedCode.user || selectedRfqCodes.length === 0 || isAssigning}
          >
            {isAssigning ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                지정 중...
              </>
            ) : (
              "담당자 지정"
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
