"use client";

import * as React from "react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { DatePicker } from "@/components/ui/date-picker"

import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Plus, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { 
  saveVendorBusinessContacts, 
  saveVendorAdditionalInfo,
  fetchVendorRegistrationStatus 
} from "@/lib/vendor-regular-registrations/service";

// 업무담당자 정보 스키마
const businessContactSchema = z.object({
  contactType: z.enum(["sales", "design", "delivery", "quality", "tax_invoice"]),
  contactName: z.string().min(1, "담당자명은 필수입니다"),
  position: z.string().min(1, "직급은 필수입니다"),
  department: z.string().min(1, "부서는 필수입니다"),
  responsibility: z.string().min(1, "담당업무는 필수입니다"),
  email: z.string().email("올바른 이메일 형식이 아닙니다"),
});

// 추가정보 스키마
const additionalInfoSchema = z.object({
  businessType: z.string().min(1, "사업유형은 필수입니다"),
  industryType: z.string().min(1, "산업유형은 필수입니다"),
  companySize: z.string().min(1, "기업규모는 필수입니다"),
  revenue: z.string().min(1, "매출액은 필수입니다"),
  factoryEstablishedDate: z.string().min(1, "공장설립일은 필수입니다"),
  preferredContractTerms: z.string().min(1, "선호계약조건은 필수입니다"),
});

// 전체 폼 스키마
const formSchema = z.object({
  businessContacts: z.array(businessContactSchema).min(5, "모든 업무담당자 정보를 입력해주세요"),
  additionalInfo: additionalInfoSchema,
});

type FormData = z.infer<typeof formSchema>;

interface AdditionalInfoDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  vendorId: number;
  onSave?: () => void;
  readonly?: boolean;
}

const contactTypes = [
  { value: "sales", label: "영업", required: true },
  { value: "design", label: "설계", required: true },
  { value: "delivery", label: "납기", required: true },
  { value: "quality", label: "품질", required: true },
  { value: "tax_invoice", label: "세금계산서", required: true },
];

// 드롭다운 옵션들
const businessTypeOptions = [
  "건설업외",
  "기타숙박업외", 
  "산업기계외",
  "선박",
  "선박건조외",
  "선박산업기기",
  "임대",
  "철구조물외"
];

const industryTypeOptions = [
  "건설업외",
  "부동산",
  "산업",
  "숙박음식",
  "제조도매외",
  "제조업"
];

const companySizeOptions = [
  "소기업",
  "중소기업", 
  "중견기업",
  "대기업"
];



export function AdditionalInfoDialog({
  open,
  onOpenChange,
  vendorId,
  onSave,
  readonly = false,
}: AdditionalInfoDialogProps) {
  const [saving, setSaving] = useState(false);
  const [loading, setLoading] = useState(false);

  const form = useForm<FormData>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      businessContacts: contactTypes.map(type => ({
        contactType: type.value as any,
        contactName: "",
        position: "",
        department: "",
        responsibility: "",
        email: "",
      })),
      additionalInfo: {
        businessType: "",
        industryType: "",
        companySize: "",
        revenue: "",
        factoryEstablishedDate: "",
        preferredContractTerms: "",
      },
    },
  });

  // 기존 데이터 로드
  const loadExistingData = async () => {
    if (!vendorId || !open) return;
    
    setLoading(true);
    try {
      const result = await fetchVendorRegistrationStatus(vendorId);
      if (result.success && result.data) {
        const { businessContacts, additionalInfo } = result.data;
        
        // 업무담당자 데이터 설정
        const contactsData = contactTypes.map(type => {
          const existingContact = businessContacts.find(c => c.contactType === type.value);
          return existingContact ? {
            contactType: existingContact.contactType,
            contactName: existingContact.contactName,
            position: existingContact.position,
            department: existingContact.department,
            responsibility: existingContact.responsibility,
            email: existingContact.email,
          } : {
            contactType: type.value as any,
            contactName: "",
            position: "",
            department: "",
            responsibility: "",
            email: "",
          };
        });
        
        // 추가정보 데이터 설정  
        const additionalInfoData = additionalInfo as any;
        const additionalData = {
          businessType: additionalInfoData?.businessType || "",
          industryType: additionalInfoData?.industryType || "",
          companySize: additionalInfoData?.companySize || "",
          revenue: additionalInfoData?.revenue || "",
          factoryEstablishedDate: additionalInfoData?.factoryEstablishedDate 
            ? new Date(additionalInfoData.factoryEstablishedDate).toISOString().split('T')[0] 
            : "",
          preferredContractTerms: additionalInfoData?.preferredContractTerms || "",
        };
        
        // 폼 데이터 업데이트
        form.reset({
          businessContacts: contactsData,
          additionalInfo: additionalData,
        });
      }
    } catch (error) {
      console.error("Error loading existing data:", error);
      toast.error("기존 데이터를 불러오는 중 오류가 발생했습니다.");
    } finally {
      setLoading(false);
    }
  };

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

  const handleSave = async (data: FormData) => {
    setSaving(true);
    try {
      // 업무담당자 정보 저장
      const contactsResult = await saveVendorBusinessContacts(vendorId, data.businessContacts);
      if (!contactsResult.success) {
        throw new Error(contactsResult.error);
      }

      // 추가정보 저장
      const additionalResult = await saveVendorAdditionalInfo(vendorId, data.additionalInfo);
      if (!additionalResult.success) {
        throw new Error(additionalResult.error);
      }
      
      toast.success("추가정보가 저장되었습니다.");
      onSave?.();
      onOpenChange(false);
    } catch (error) {
      console.error("Error saving additional info:", error);
      toast.error(error instanceof Error ? error.message : "추가정보 저장 중 오류가 발생했습니다.");
    } finally {
      setSaving(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{readonly ? "추가정보 조회" : "추가정보 입력"}</DialogTitle>
          <p className="text-sm text-muted-foreground">
            {readonly 
              ? "정규업체 등록을 위한 추가 정보를 조회합니다."
              : "정규업체 등록을 위한 추가정보를 입력해주세요. * 표시는 필수 입력 항목입니다."
            }
          </p>
        </DialogHeader>

        {loading ? (
          <div className="p-8 text-center">
            <div className="text-sm text-muted-foreground">데이터를 불러오는 중...</div>
          </div>
        ) : (

        <Form {...form}>
          <form onSubmit={form.handleSubmit(handleSave)}>
            <Tabs defaultValue="contacts" className="w-full">
              <TabsList className="grid w-full grid-cols-2">
                <TabsTrigger value="contacts">업무담당자 정보</TabsTrigger>
                <TabsTrigger value="additional">추가정보</TabsTrigger>
              </TabsList>

              <TabsContent value="contacts" className="space-y-4">
                <div className="space-y-4">
                  {contactTypes.map((contactType, index) => (
                    <Card key={contactType.value}>
                      <CardHeader className="pb-3">
                        <CardTitle className="text-lg flex items-center gap-2">
                          {contactType.label} 담당자
                        </CardTitle>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        <div className="grid grid-cols-2 gap-4">
                          <FormField
                            control={form.control}
                            name={`businessContacts.${index}.contactName`}
                            render={({ field }) => (
                              <FormItem>
                                <FormLabel>담당자명 {!readonly && "*"}</FormLabel>
                                <FormControl>
                                  <Input 
                                    placeholder={readonly ? "" : "담당자명 입력"} 
                                    readOnly={readonly}
                                    {...field} 
                                  />
                                </FormControl>
                                <FormMessage />
                              </FormItem>
                            )}
                          />
                          <FormField
                            control={form.control}
                            name={`businessContacts.${index}.position`}
                            render={({ field }) => (
                              <FormItem>
                                <FormLabel>직급 {!readonly && "*"}</FormLabel>
                                <FormControl>
                                  <Input 
                                    placeholder={readonly ? "" : "직급 입력"} 
                                    readOnly={readonly}
                                    {...field} 
                                  />
                                </FormControl>
                                <FormMessage />
                              </FormItem>
                            )}
                          />
                        </div>
                        <div className="grid grid-cols-2 gap-4">
                          <FormField
                            control={form.control}
                            name={`businessContacts.${index}.department`}
                            render={({ field }) => (
                              <FormItem>
                                <FormLabel>부서 {!readonly && "*"}</FormLabel>
                                <FormControl>
                                  <Input 
                                    placeholder={readonly ? "" : "부서명 입력"} 
                                    readOnly={readonly}
                                    {...field} 
                                  />
                                </FormControl>
                                <FormMessage />
                              </FormItem>
                            )}
                          />
                          <FormField
                            control={form.control}
                            name={`businessContacts.${index}.email`}
                            render={({ field }) => (
                              <FormItem>
                                <FormLabel>Email {!readonly && "*"}</FormLabel>
                                <FormControl>
                                  <Input 
                                    placeholder={readonly ? "" : "이메일 입력"} 
                                    type="email" 
                                    readOnly={readonly}
                                    {...field} 
                                  />
                                </FormControl>
                                <FormMessage />
                              </FormItem>
                            )}
                          />
                        </div>
                        <FormField
                          control={form.control}
                          name={`businessContacts.${index}.responsibility`}
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>담당업무 {!readonly && "*"}</FormLabel>
                              <FormControl>
                                <Textarea 
                                  placeholder={readonly ? "" : "담당업무 상세 입력"} 
                                  className="h-20"
                                  readOnly={readonly}
                                  {...field} 
                                />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                      </CardContent>
                    </Card>
                  ))}
                </div>
              </TabsContent>

              <TabsContent value="additional" className="space-y-4">
                <Card>
                  <CardHeader>
                    <CardTitle>회사 추가정보</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      <FormField
                        control={form.control}
                        name="additionalInfo.businessType"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>사업유형 {!readonly && "*"}</FormLabel>
                            <Select 
                              onValueChange={field.onChange} 
                              defaultValue={field.value}
                              disabled={readonly}
                            >
                              <FormControl>
                                <SelectTrigger>
                                  <SelectValue placeholder={readonly ? "" : "사업유형을 선택하세요"} />
                                </SelectTrigger>
                              </FormControl>
                              <SelectContent>
                                {businessTypeOptions.map((option) => (
                                  <SelectItem key={option} value={option}>
                                    {option}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={form.control}
                        name="additionalInfo.industryType"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>산업유형 {!readonly && "*"}</FormLabel>
                            <Select 
                              onValueChange={field.onChange} 
                              defaultValue={field.value}
                              disabled={readonly}
                            >
                              <FormControl>
                                <SelectTrigger>
                                  <SelectValue placeholder={readonly ? "" : "산업유형을 선택하세요"} />
                                </SelectTrigger>
                              </FormControl>
                              <SelectContent>
                                {industryTypeOptions.map((option) => (
                                  <SelectItem key={option} value={option}>
                                    {option}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <FormField
                        control={form.control}
                        name="additionalInfo.companySize"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>기업규모 {!readonly && "*"}</FormLabel>
                            <Select 
                              onValueChange={field.onChange} 
                              defaultValue={field.value}
                              disabled={readonly}
                            >
                              <FormControl>
                                <SelectTrigger>
                                  <SelectValue placeholder={readonly ? "" : "기업규모를 선택하세요"} />
                                </SelectTrigger>
                              </FormControl>
                              <SelectContent>
                                {companySizeOptions.map((option) => (
                                  <SelectItem key={option} value={option}>
                                    {option}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={form.control}
                        name="additionalInfo.revenue"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>매출액 (억원) {!readonly && "*"}</FormLabel>
                            <FormControl>
                              <Input 
                                placeholder={readonly ? "" : "매출액 입력"} 
                                type="number"
                                readOnly={readonly}
                                {...field} 
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <FormField
                        control={form.control}
                        name="additionalInfo.factoryEstablishedDate"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>공장설립일 {!readonly && "*"}</FormLabel>
                            <FormControl>
                              {/* datepicker 라이브러리를 사용하는 방식으로 수정 (예: react-datepicker) */}
                              <DatePicker
                                date={field.value ? new Date(field.value) : undefined}
                                onSelect={(date) => {
                                  field.onChange(date ? date.toISOString().slice(0, 10) : "");
                                }}
                                placeholder={readonly ? "" : "YYYY-MM-DD"}
                                disabled={readonly}
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>
                    <FormField
                      control={form.control}
                      name="additionalInfo.preferredContractTerms"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>선호계약조건 {!readonly && "*"}</FormLabel>
                          <FormControl>
                            <Textarea 
                              placeholder={readonly ? "" : "선호하는 계약조건을 상세히 입력해주세요"} 
                              className="h-32"
                              readOnly={readonly}
                              {...field} 
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </CardContent>
                </Card>
              </TabsContent>
            </Tabs>

            <DialogFooter className="mt-6">
              {readonly ? (
                <Button
                  type="button"
                  onClick={() => onOpenChange(false)}
                >
                  닫기
                </Button>
              ) : (
                <>
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => onOpenChange(false)}
                    disabled={saving}
                  >
                    취소
                  </Button>
                  <Button type="submit" disabled={saving}>
                    {saving ? "저장 중..." : "저장"}
                  </Button>
                </>
              )}
            </DialogFooter>
          </form>
        </Form>
        )}
      </DialogContent>
    </Dialog>
  );
}
