"use client"

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

import { Button } from "@/components/ui/button"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"
import { Checkbox } from "@/components/ui/checkbox"
import { Loader2 } from "lucide-react"

import type { TechVendorContact } from "@/db/schema/techVendors"
import { updateTechVendorContactSchema, type UpdateTechVendorContactSchema } from "../validations"
import { updateTechVendorContact } from "../service"

interface UpdateContactSheetProps
  extends React.ComponentPropsWithoutRef<typeof Sheet> {
  contact: TechVendorContact | null
  vendorId: number
}

export function UpdateContactSheet({ contact, vendorId, ...props }: UpdateContactSheetProps) {
  const [isPending, startTransition] = React.useTransition()

  const form = useForm<UpdateTechVendorContactSchema>({
    resolver: zodResolver(updateTechVendorContactSchema),
    defaultValues: {
      contactName: contact?.contactName ?? "",
      contactPosition: contact?.contactPosition ?? "",
      contactEmail: contact?.contactEmail ?? "",
      contactPhone: contact?.contactPhone ?? "",
      contactCountry: contact?.contactCountry ?? "",
      contactTitle: contact?.contactTitle ?? "",
      isPrimary: contact?.isPrimary ?? false,
    },
  })

  React.useEffect(() => {
    if (contact) {
      form.reset({
        contactName: contact.contactName,
        contactPosition: contact.contactPosition ?? "",
        contactEmail: contact.contactEmail,
        contactPhone: contact.contactPhone ?? "",
        contactCountry: contact.contactCountry ?? "",
        contactTitle: contact.contactTitle ?? "",
        isPrimary: contact.isPrimary,
      })
    }
  }, [contact, form])

  async function onSubmit(data: UpdateTechVendorContactSchema) {
    if (!contact) return
    
    startTransition(async () => {
      try {
        const { error } = await updateTechVendorContact({ 
          id: contact.id,
          vendorId: vendorId,
          ...data 
        })
        
        if (error) throw new Error(error)
        
        toast.success("연락처 정보가 업데이트되었습니다!")
        form.reset()
        props.onOpenChange?.(false)
      } catch (err: unknown) {
        toast.error(String(err))
      }
    })
  }

  return (
    <Sheet {...props}>
      <SheetContent className="space-y-4 w-[600px] sm:max-w-[600px]">
        <SheetHeader>
          <SheetTitle>연락처 수정</SheetTitle>
          <SheetDescription>
            연락처 정보를 수정하세요. 완료되면 저장 버튼을 클릭하세요.
          </SheetDescription>
        </SheetHeader>
        
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <div className="grid grid-cols-1 gap-4">
              <FormField
                control={form.control}
                name="contactName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>담당자명 *</FormLabel>
                    <FormControl>
                      <Input placeholder="담당자명을 입력하세요" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="contactPosition"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>직책</FormLabel>
                    <FormControl>
                      <Input placeholder="직책을 입력하세요" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="contactTitle"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>직책</FormLabel>
                    <FormControl>
                      <Input placeholder="직책을 입력하세요" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="contactEmail"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>이메일</FormLabel>
                    <FormControl>
                      <Input 
                        type="email" 
                        placeholder="이메일을 입력하세요" 
                        {...field} 
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="contactPhone"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>전화번호</FormLabel>
                    <FormControl>
                      <Input placeholder="전화번호를 입력하세요" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="contactCountry"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>국가</FormLabel>
                    <FormControl>
                      <Input placeholder="국가를 입력하세요" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="isPrimary"
                render={({ field }) => (
                  <FormItem className="flex flex-row items-start space-x-3 space-y-0">
                    <FormControl>
                      <Checkbox
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </FormControl>
                    <div className="space-y-1 leading-none">
                      <FormLabel>주 담당자</FormLabel>
                    </div>
                  </FormItem>
                )}
              />
            </div>

            <div className="flex justify-end space-x-2">
              <Button
                type="button"
                variant="outline"
                onClick={() => props.onOpenChange?.(false)}
              >
                취소
              </Button>
              <Button type="submit" disabled={isPending}>
                {isPending && (
                  <Loader2
                    className="mr-2 h-4 w-4 animate-spin"
                    aria-hidden="true"
                  />
                )}
                저장
              </Button>
            </div>
          </form>
        </Form>
      </SheetContent>
    </Sheet>
  )
} 