"use client"

import * as React from "react"
import { OcrRow } from "@/db/schema"
import { zodResolver } from "@hookform/resolvers/zod"
import { Loader } from "lucide-react"
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,
  SheetClose,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"

import { modifyOcrRow } from "../service"
import { updateOcrRowSchema, type UpdateOcrRowSchema } from "../validation"

interface UpdateOcrRowSheetProps
  extends React.ComponentPropsWithRef<typeof Sheet> {
  ocrRow: OcrRow | null
}

export function UpdateOcrRowSheet({ ocrRow, ...props }: UpdateOcrRowSheetProps) {
  const [isUpdatePending, startUpdateTransition] = React.useTransition()

  const form = useForm<UpdateOcrRowSchema>({
    resolver: zodResolver(updateOcrRowSchema),
    defaultValues: {
      identificationNo: ocrRow?.identificationNo ?? "",
      tagNo: ocrRow?.tagNo ?? "",
      weldingDate: ocrRow?.weldingDate ?? "",
      jointType: ocrRow?.jointType ?? "",
    },
  })

  React.useEffect(() => {
    if (ocrRow) {
      form.reset({
        identificationNo: ocrRow.identificationNo ?? "",
        tagNo: ocrRow.tagNo ?? "",
        weldingDate: ocrRow.weldingDate ?? "",
        jointType: ocrRow.jointType ?? "",
      })
    }
  }, [ocrRow, form])

  function onSubmit(input: UpdateOcrRowSchema) {
    startUpdateTransition(async () => {
      if (!ocrRow) return

      const { error } = await modifyOcrRow({
        id: ocrRow.id,
        ...input,
      })

      if (error) {
        toast.error(error)
        return
      }

      form.reset()
      props.onOpenChange?.(false)
      toast.success("OCR 행이 업데이트되었습니다")
    })
  }



  return (
    <Sheet {...props}>
      <SheetContent className="flex flex-col gap-6 sm:max-w-md">
        <SheetHeader className="text-left">
          <SheetTitle>OCR 행 업데이트</SheetTitle>
          <SheetDescription>
            OCR 행의 세부 정보를 수정하고 변경 사항을 저장하세요
          </SheetDescription>
        </SheetHeader>
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="flex flex-col gap-4"
          >
            <FormField
              control={form.control}
              name="identificationNo"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Identification No</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="식별 번호를 입력하세요"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            
            <FormField
              control={form.control}
              name="tagNo"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Tag No</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="태그 번호를 입력하세요"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="weldingDate"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Welding Date</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="용접 날짜를 입력하세요 (예: 2024-12-01)"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="jointType"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Joint Type</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="조인트 타입을 입력하세요"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <SheetFooter className="gap-2 pt-2 sm:space-x-0">
              <SheetClose asChild>
                <Button type="button" variant="outline">
                  취소
                </Button>
              </SheetClose>
              <Button disabled={isUpdatePending}>
                {isUpdatePending && (
                  <Loader
                    className="mr-2 size-4 animate-spin"
                    aria-hidden="true"
                  />
                )}
                저장
              </Button>
            </SheetFooter>
          </form>
        </Form>
      </SheetContent>
    </Sheet>
  )
}