"use client"

import * as React from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"

import { Button } from "@/components/ui/button"
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"

import { toast } from "sonner"
import { Upload, X, FileText } from "lucide-react"

// 협력업체 정보 입력 스키마
const vendorInfoSchema = z.object({
  // 공장 정보
  factoryName: z.string().min(1, "공장명을 입력해주세요."),
  factoryLocation: z.string().min(1, "공장위치를 입력해주세요."),
  factoryAddress: z.string().min(1, "공장주소를 입력해주세요."),
  
  // 공장 PIC 정보
  factoryPicName: z.string().min(1, "공장 담당자 이름을 입력해주세요."),
  factoryPicPhone: z.string().min(1, "공장 담당자 전화번호를 입력해주세요."),
  factoryPicEmail: z.string().email("올바른 이메일 주소를 입력해주세요."),
  
  // 공장 가는 법
  factoryDirections: z.string().min(1, "공장 가는 법을 입력해주세요."),
  
  // 공장 출입절차
  accessProcedure: z.string().min(1, "공장 출입절차를 입력해주세요."),
  
  // 첨부파일
  hasAttachments: z.boolean().default(false),
  
  // 기타 정보
  otherInfo: z.string().optional(),
})

export type VendorInfoFormValues = z.infer<typeof vendorInfoSchema>

interface VendorInfoSheetProps {
  isOpen: boolean
  onClose: () => void
  onSubmit: (data: VendorInfoFormValues & { attachments?: File[] }) => Promise<void>
  siteVisitRequestId: number
  initialData?: VendorInfoFormValues | null
}

export function VendorInfoSheet({
  isOpen,
  onClose,
  onSubmit,
  siteVisitRequestId,
  initialData,
}: VendorInfoSheetProps) {
  const [isPending, setIsPending] = React.useState(false)
  const [selectedFiles, setSelectedFiles] = React.useState<File[]>([])
  const fileInputRef = React.useRef<HTMLInputElement>(null)

  const form = useForm<VendorInfoFormValues>({
    resolver: zodResolver(vendorInfoSchema),
    defaultValues: {
      factoryName: "",
      factoryLocation: "",
      factoryAddress: "",
      factoryPicName: "",
      factoryPicPhone: "",
      factoryPicEmail: "",
      factoryDirections: "",
      accessProcedure: "",

      hasAttachments: false,
      otherInfo: "",
    },
  })

  // Sheet가 열릴 때마다 폼 재설정
  React.useEffect(() => {
    if (isOpen) {
      if (initialData) {
        form.reset(initialData)
      } else {
        form.reset({
          factoryName: "",
          factoryLocation: "",
          factoryAddress: "",
          factoryPicName: "",
          factoryPicPhone: "",
          factoryPicEmail: "",
          factoryDirections: "",
          accessProcedure: "",

          hasAttachments: false,
          otherInfo: "",
        })
      }
    }
  }, [isOpen, form, initialData])

  // 파일 업로드 핸들러
  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files
    if (!files || files.length === 0) return

    const newFiles = Array.from(files)
    
    // 파일 크기 체크 (10MB)
    const validFiles = newFiles.filter(file => {
      if (file.size > 10 * 1024 * 1024) {
        toast.error(`${file.name}: 파일 크기가 10MB를 초과합니다.`)
        return false
      }
      return true
    })

    if (validFiles.length > 0) {
      setSelectedFiles(prev => [...prev, ...validFiles])
      form.setValue("hasAttachments", true)
      toast.success(`${validFiles.length}개 파일이 추가되었습니다.`)
    }
  }

  // 파일 삭제 핸들러
  const handleRemoveFile = (index: number) => {
    setSelectedFiles(prev => prev.filter((_, i) => i !== index))
    const newFileCount = selectedFiles.length - 1
    form.setValue("hasAttachments", newFileCount > 0)
  }

  async function handleSubmit(data: VendorInfoFormValues) {
    setIsPending(true)
    try {
      // 첨부파일 정보를 포함하여 제출
      const submitData = {
        ...data,
        siteVisitRequestId,
        attachments: selectedFiles
      }
      await onSubmit(submitData)
      toast.success("협력업체 정보가 성공적으로 제출되었습니다.")
      onClose()
    } catch (error) {
      toast.error("협력업체 정보 제출 중 오류가 발생했습니다.")
      console.error("협력업체 정보 제출 오류:", error)
    } finally {
      setIsPending(false)
    }
  }

  return (
    <Sheet open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <SheetContent className="w-[800px] sm:max-w-xl max-w-[95vw] overflow-y-auto space-y-2">
        <SheetHeader>
          <SheetTitle>협력업체 정보 입력</SheetTitle>
          <SheetDescription>
            방문실사 관련 협력업체 정보를 입력해주세요.
          </SheetDescription>
        </SheetHeader>
        
        <Form {...form}>
          <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-6">
            {/* 공장 정보 */}
            <div className="space-y-4">
              <h3 className="text-lg font-semibold border-b pb-2">공장 정보</h3>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="factoryName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>공장명 *</FormLabel>
                      <FormControl>
                        <Input placeholder="공장명을 입력하세요" {...field} disabled={isPending} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormField
                  control={form.control}
                  name="factoryLocation"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>공장위치 *</FormLabel>
                      <FormControl>
                        <Input placeholder="국가 또는 지역 (예: Finland, 부산)" {...field} disabled={isPending} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <div className="md:col-span-2">
                  <FormField
                    control={form.control}
                    name="factoryAddress"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>공장주소 *</FormLabel>
                        <FormControl>
                          <Textarea 
                            placeholder="상세 주소를 입력하세요" 
                            {...field} 
                            disabled={isPending}
                            className="min-h-[80px]"
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              </div>
            </div>

            {/* 공장 PIC 정보 */}
            <div className="space-y-4">
              <h3 className="text-lg font-semibold border-b pb-2">공장 담당자 정보</h3>
              
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <FormField
                  control={form.control}
                  name="factoryPicName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>이름 *</FormLabel>
                      <FormControl>
                        <Input placeholder="PIC 이름" {...field} disabled={isPending} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormField
                  control={form.control}
                  name="factoryPicPhone"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>전화번호 *</FormLabel>
                      <FormControl>
                        <Input placeholder="전화번호" {...field} disabled={isPending} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormField
                  control={form.control}
                  name="factoryPicEmail"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>이메일 *</FormLabel>
                      <FormControl>
                        <Input placeholder="이메일 주소" {...field} disabled={isPending} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </div>

            {/* 공장 정보 상세 */}
            <div className="space-y-4">
              <h3 className="text-lg font-semibold border-b pb-2">공장 정보 상세</h3>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <FormField
                  control={form.control}
                  name="factoryDirections"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>공장 가는 법 *</FormLabel>
                      <FormControl>
                        <Textarea 
                          placeholder="공항에서 공장까지 가는 방법, 대중교통 정보 등을 상세히 입력하세요" 
                          {...field} 
                          disabled={isPending}
                          className="min-h-[120px]"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                
                <FormField
                  control={form.control}
                  name="accessProcedure"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>공장 출입절차 *</FormLabel>
                      <FormControl>
                        <Textarea 
                          placeholder="신분증 제출, 출입증 교환, 준비물 등 출입 절차를 상세히 입력하세요" 
                          {...field} 
                          disabled={isPending}
                          className="min-h-[120px]"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </div>



            {/* 첨부파일 */}
            <div className="space-y-4">
              <h3 className="text-lg font-semibold border-b pb-2">첨부파일</h3>
              
              {/* 파일 업로드 */}
              <div className="space-y-2">
                <FormLabel>파일 업로드</FormLabel>
                <div className="border-2 border-dashed border-gray-300 rounded-lg p-4 text-center">
                  <input
                    ref={fileInputRef}
                    type="file"
                    multiple
                    accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png"
                    onChange={handleFileUpload}
                    className="hidden"
                    disabled={isPending}
                  />
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => fileInputRef.current?.click()}
                    disabled={isPending}
                    className="w-full"
                  >
                    <Upload className="h-4 w-4 mr-2" />
                    파일 선택
                  </Button>
                  <p className="text-xs text-muted-foreground mt-2">
                    PDF, Word, Excel, 이미지 파일 (최대 10MB)
                  </p>
                </div>
              </div>

              {/* 첨부된 파일 목록 */}
              <div>
                <FormLabel>첨부된 파일</FormLabel>
                <div className="space-y-2">
                  {selectedFiles.length > 0 ? (
                    selectedFiles.map((file, index) => (
                      <div key={index} className="flex items-center justify-between p-2 border rounded-md">
                        <div className="flex items-center space-x-2 flex-1 min-w-0">
                          <FileText className="h-4 w-4 text-muted-foreground" />
                          <span className="text-sm truncate">{file.name}</span>
                          <span className="text-xs text-muted-foreground">
                            ({Math.round(file.size / 1024)}KB)
                          </span>
                        </div>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={() => handleRemoveFile(index)}
                          disabled={isPending}
                          className="text-destructive hover:text-destructive"
                        >
                          <X className="h-4 w-4" />
                        </Button>
                      </div>
                    ))
                  ) : (
                    <div className="text-sm text-muted-foreground text-center py-4">
                      첨부된 파일이 없습니다.
                    </div>
                  )}
                </div>
              </div>
            </div>

            {/* 기타 정보 */}
            <div className="space-y-4">
              <h3 className="text-lg font-semibold border-b pb-2">기타 정보</h3>
              
              <FormField
                control={form.control}
                name="otherInfo"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>기타 정보 (선택사항)</FormLabel>
                    <FormControl>
                      <Textarea 
                        placeholder="추가로 전달하고 싶은 정보가 있다면 입력하세요" 
                        {...field} 
                        disabled={isPending}
                        className="min-h-[100px]"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <SheetFooter>
              <Button
                type="button"
                variant="outline"
                onClick={onClose}
                disabled={isPending}
              >
                취소
              </Button>
              <Button type="submit" disabled={isPending}>
                {isPending ? "처리 중..." : "정보입력"}
              </Button>
            </SheetFooter>
          </form>
        </Form>
      </SheetContent>
    </Sheet>
  )
} 