"use client"

import * as React from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import { Check, ChevronsUpDown, Loader } from "lucide-react"
import { useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod"

import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
} from "@/components/ui/command"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Sheet,
  SheetClose,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"
import { Checkbox } from "@/components/ui/checkbox"
import { ScrollArea } from "@/components/ui/scroll-area"

import { RfqDetailView } from "./rfq-detail-column"
import { updateRfqDetail } from "@/lib/procurement-rfqs/services"

// 폼 유효성 검증 스키마
const updateRfqDetailSchema = z.object({
  vendorId: z.string().min(1, "벤더를 선택해주세요"),
  currency: z.string().min(1, "통화를 선택해주세요"),
  paymentTermsCode: z.string().min(1, "지불 조건을 선택해주세요"),
  incotermsCode: z.string().min(1, "인코텀즈를 선택해주세요"),
  incotermsDetail: z.string().optional(),
  deliveryDate: z.string().optional(),
  taxCode: z.string().optional(),
  placeOfShipping: z.string().optional(),
  placeOfDestination: z.string().optional(),
  materialPriceRelatedYn: z.boolean().default(false),
})

type UpdateRfqDetailFormValues = z.infer<typeof updateRfqDetailSchema>

// 데이터 타입 정의
interface Vendor {
  id: number;
  vendorName: string;
  vendorCode: string;
}

interface Currency {
  code: string;
  name: string;
}

interface PaymentTerm {
  code: string;
  description: string;
}

interface Incoterm {
  code: string;
  description: string;
}

interface UpdateRfqDetailSheetProps
  extends React.ComponentPropsWithRef<typeof Sheet> {
  detail: RfqDetailView | null;
  vendors: Vendor[];
  currencies: Currency[];
  paymentTerms: PaymentTerm[];
  incoterms: Incoterm[];
  onSuccess?: () => void;
}

export function UpdateRfqDetailSheet({ 
  detail, 
  vendors, 
  currencies, 
  paymentTerms, 
  incoterms,
  onSuccess,
  ...props 
}: UpdateRfqDetailSheetProps) {
  const [isUpdatePending, startUpdateTransition] = React.useTransition()
  const [vendorOpen, setVendorOpen] = React.useState(false)

  const form = useForm<UpdateRfqDetailFormValues>({
    resolver: zodResolver(updateRfqDetailSchema),
    defaultValues: {
      vendorId: detail?.vendorName ? String(vendors.find(v => v.vendorName === detail.vendorName)?.id || "") : "",
      currency: detail?.currency || "",
      paymentTermsCode: detail?.paymentTermsCode || "",
      incotermsCode: detail?.incotermsCode || "",
      incotermsDetail: detail?.incotermsDetail || "",
      deliveryDate: detail?.deliveryDate ? new Date(detail.deliveryDate).toISOString().split('T')[0] : "",
      taxCode: detail?.taxCode || "",
      placeOfShipping: detail?.placeOfShipping || "",
      placeOfDestination: detail?.placeOfDestination || "",
      materialPriceRelatedYn: detail?.materialPriceRelatedYn || false,
    },
  })

  // detail이 변경될 때 form 값 업데이트
  React.useEffect(() => {
    if (detail) {
      const vendorId = vendors.find(v => v.vendorName === detail.vendorName)?.id
      
      form.reset({
        vendorId: vendorId ? String(vendorId) : "",
        currency: detail.currency || "",
        paymentTermsCode: detail.paymentTermsCode || "",
        incotermsCode: detail.incotermsCode || "",
        incotermsDetail: detail.incotermsDetail || "",
        deliveryDate: detail.deliveryDate ? new Date(detail.deliveryDate).toISOString().split('T')[0] : "",
        taxCode: detail.taxCode || "",
        placeOfShipping: detail.placeOfShipping || "",
        placeOfDestination: detail.placeOfDestination || "",
        materialPriceRelatedYn: detail.materialPriceRelatedYn || false,
      })
    }
  }, [detail, form, vendors])

  function onSubmit(values: UpdateRfqDetailFormValues) {
    if (!detail) return

    startUpdateTransition(async () => {
      try {
        const result = await updateRfqDetail(detail.detailId, values)

        if (!result.success) {
          toast.error(result.message || "수정 중 오류가 발생했습니다")
          return
        }

        props.onOpenChange?.(false)
        toast.success("RFQ 벤더 정보가 수정되었습니다")
        onSuccess?.()
      } catch (error) {
        console.error("RFQ 벤더 수정 오류:", error)
        toast.error("수정 중 오류가 발생했습니다")
      }
    })
  }

  return (
    <Sheet {...props}>
      <SheetContent className="flex w-full flex-col gap-6 sm:max-w-xl">
        <SheetHeader className="text-left">
          <SheetTitle>RFQ 벤더 정보 수정</SheetTitle>
          <SheetDescription>
            벤더 정보를 수정하고 저장하세요
          </SheetDescription>
        </SheetHeader>
        <ScrollArea className="flex-1 pr-4">
          <Form {...form}>
            <form
              id="update-rfq-detail-form"
              onSubmit={form.handleSubmit(onSubmit)}
              className="flex flex-col gap-4"
            >
              {/* 검색 가능한 벤더 선택 필드 */}
              <FormField
                control={form.control}
                name="vendorId"
                render={({ field }) => (
                  <FormItem className="flex flex-col">
                    <FormLabel>벤더 <span className="text-red-500">*</span></FormLabel>
                    <Popover open={vendorOpen} onOpenChange={setVendorOpen}>
                      <PopoverTrigger asChild>
                        <FormControl>
                          <Button
                            variant="outline"
                            role="combobox"
                            aria-expanded={vendorOpen}
                            className={cn(
                              "w-full justify-between",
                              !field.value && "text-muted-foreground"
                            )}
                          >
                            {field.value
                              ? vendors.find((vendor) => String(vendor.id) === field.value)
                                ? `${vendors.find((vendor) => String(vendor.id) === field.value)?.vendorName} (${vendors.find((vendor) => String(vendor.id) === field.value)?.vendorCode})`
                                : "벤더를 선택하세요"
                              : "벤더를 선택하세요"}
                            <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                          </Button>
                        </FormControl>
                      </PopoverTrigger>
                      <PopoverContent className="w-[400px] p-0">
                        <Command>
                          <CommandInput placeholder="벤더 검색..." />
                          <CommandEmpty>검색 결과가 없습니다</CommandEmpty>
                          <ScrollArea className="h-60">
                            <CommandGroup>
                              {vendors.map((vendor) => (
                                <CommandItem
                                  key={vendor.id}
                                  value={`${vendor.vendorName} ${vendor.vendorCode}`}
                                  onSelect={() => {
                                    form.setValue("vendorId", String(vendor.id), {
                                      shouldValidate: true,
                                    })
                                    setVendorOpen(false)
                                  }}
                                >
                                  <Check
                                    className={cn(
                                      "mr-2 h-4 w-4",
                                      String(vendor.id) === field.value
                                        ? "opacity-100"
                                        : "opacity-0"
                                    )}
                                  />
                                  {vendor.vendorName} ({vendor.vendorCode})
                                </CommandItem>
                              ))}
                            </CommandGroup>
                          </ScrollArea>
                        </Command>
                      </PopoverContent>
                    </Popover>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="currency"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>통화 <span className="text-red-500">*</span></FormLabel>
                    <Select onValueChange={field.onChange} value={field.value}>
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="통화를 선택하세요" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {currencies.map((currency) => (
                          <SelectItem key={currency.code} value={currency.code}>
                            {currency.name} ({currency.code})
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="paymentTermsCode"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>지불 조건 <span className="text-red-500">*</span></FormLabel>
                      <Select onValueChange={field.onChange} value={field.value}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="지불 조건 선택" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {paymentTerms.map((term) => (
                            <SelectItem key={term.code} value={term.code}>
                              {term.description}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="incotermsCode"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>인코텀즈 <span className="text-red-500">*</span></FormLabel>
                      <Select onValueChange={field.onChange} value={field.value}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="인코텀즈 선택" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {incoterms.map((incoterm) => (
                            <SelectItem key={incoterm.code} value={incoterm.code}>
                              {incoterm.description}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <FormField
                control={form.control}
                name="incotermsDetail"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>인코텀즈 세부사항</FormLabel>
                    <FormControl>
                      <Input {...field} placeholder="인코텀즈 세부사항" />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="deliveryDate"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>납품 예정일</FormLabel>
                      <FormControl>
                        <Input {...field} type="date" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="taxCode"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>세금 코드</FormLabel>
                      <FormControl>
                        <Input {...field} placeholder="세금 코드" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="placeOfShipping"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>선적지</FormLabel>
                      <FormControl>
                        <Input {...field} placeholder="선적지" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="placeOfDestination"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>도착지</FormLabel>
                      <FormControl>
                        <Input {...field} placeholder="도착지" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <FormField
                control={form.control}
                name="materialPriceRelatedYn"
                render={({ field }) => (
                  <FormItem className="flex flex-row items-start space-x-3 space-y-0 rounded-md border p-4">
                    <FormControl>
                      <Checkbox
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </FormControl>
                    <div className="space-y-1 leading-none">
                      <FormLabel>자재 가격 관련 여부</FormLabel>
                    </div>
                  </FormItem>
                )}
              />
            </form>
          </Form>
        </ScrollArea>
        <SheetFooter className="gap-2 pt-2 sm:space-x-0">
          <SheetClose asChild>
            <Button type="button" variant="outline">
              취소
            </Button>
          </SheetClose>
          <Button
            type="submit"
            form="update-rfq-detail-form"
            disabled={isUpdatePending}
          >
            {isUpdatePending && (
              <Loader
                className="mr-2 size-4 animate-spin"
                aria-hidden="true"
              />
            )}
            저장
          </Button>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  )
}