"use client"

import * as React from "react"
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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Sheet,
  SheetClose,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"

import { ProcurementItem } from "@/db/schema/items"
import { updateProcurementItemSchema, UpdateProcurementItemSchema } from "../validations"
import { modifyProcurementItem } from "../service"
import { Input } from "@/components/ui/input"

interface UpdateProcurementItemSheetProps
  extends React.ComponentPropsWithRef<typeof Sheet> {
  procurementItem: ProcurementItem | null
}

export function UpdateProcurementItemSheet({
  procurementItem,
  ...props
}: UpdateProcurementItemSheetProps) {
  const [isUpdatePending, startUpdateTransition] = React.useTransition()

  console.log(procurementItem)
  const form = useForm<UpdateProcurementItemSchema>({
    resolver: zodResolver(updateProcurementItemSchema),
    defaultValues: {
      itemCode: procurementItem?.itemCode ?? "",
      itemName: procurementItem?.itemName ?? "",
      material: procurementItem?.material ?? "",
      specification: procurementItem?.specification ?? "",
      unit: procurementItem?.unit ?? "",
      isActive: procurementItem?.isActive ?? "Y",
    },
  })

  React.useEffect(() => {
    if (procurementItem) {
      form.reset({
        itemCode: procurementItem.itemCode ?? "",
        itemName: procurementItem.itemName ?? "",
        material: procurementItem.material ?? "",
        specification: procurementItem.specification ?? "",
        unit: procurementItem.unit ?? "",
        isActive: procurementItem.isActive ?? "Y",
      })
    }
  }, [procurementItem, form])

  function onSubmit(input: UpdateProcurementItemSchema) {
    startUpdateTransition(async () => {
      if (!procurementItem) return

      const { error } = await modifyProcurementItem({
        id: procurementItem.id,
        ...input,
      })

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

      form.reset()
      toast.success("품목이 성공적으로 수정되었습니다.")
      props.onOpenChange?.(false)
    })
  }

  return (
    <Sheet {...props}>
      <SheetContent className="w-[400px] sm:w-[540px]">
        <SheetHeader>
          <SheetTitle>품목 수정</SheetTitle>
          <SheetDescription>
            품목 정보를 수정하고 <b>저장</b> 버튼을 누르세요.
          </SheetDescription>
        </SheetHeader>

        <div className="mt-6">
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
              <FormField
                control={form.control}
                name="itemCode"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>품목코드</FormLabel>
                    <FormControl>
                      <Input {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="itemName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>품목명</FormLabel>
                    <FormControl>
                      <Input {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="material"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>재질</FormLabel>
                    <FormControl>
                      <Input {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="specification"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>규격</FormLabel>
                    <FormControl>
                      <Input {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="unit"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>단위</FormLabel>
                    <FormControl>
                      <Input {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="isActive"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>활성화여부</FormLabel>
                    <Select onValueChange={field.onChange} value={field.value}>
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="Y">활성</SelectItem>
                        <SelectItem value="N">비활성</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <SheetFooter>
                <SheetClose asChild>
                  <Button type="button" variant="outline">
                    취소
                  </Button>
                </SheetClose>
                <Button disabled={isUpdatePending}>
                  {isUpdatePending && (
                    <Loader className="mr-2 size-4 animate-spin" />
                  )}
                  저장
                </Button>
              </SheetFooter>
            </form>
          </Form>
        </div>
      </SheetContent>
    </Sheet>
  )
}
