"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 { Textarea } from "@/components/ui/textarea"

import { Item } from "@/db/schema/items"
import { updateItemSchema, UpdateItemSchema } from "../validations"
import { modifyItem } from "../service"
import { Input } from "@/components/ui/input"

interface UpdateItemSheetProps
  extends React.ComponentPropsWithRef<typeof Sheet> {
  item: Item | null
}

export function UpdateItemSheet({ item, ...props }: UpdateItemSheetProps) {
  const [isUpdatePending, startUpdateTransition] = React.useTransition()

  console.log(item)
  const form = useForm<UpdateItemSchema>({
    resolver: zodResolver(updateItemSchema),
    defaultValues: {
      itemCode: item?.itemCode ?? "",
      itemName: item?.itemName ?? "",
      description: item?.description ?? "",
      parentItemCode: item?.parentItemCode ?? "",
      itemLevel: item?.itemLevel ?? null,
      deleteFlag: item?.deleteFlag ?? "",
      unitOfMeasure: item?.unitOfMeasure ?? "",
      steelType: item?.steelType ?? "",
      gradeMaterial: item?.gradeMaterial ?? "",
      changeDate: item?.changeDate ?? "",
      baseUnitOfMeasure: item?.baseUnitOfMeasure ?? "",
    },
  })


  React.useEffect(() => {
    if (item) {
      form.reset({
        itemCode: item.itemCode ?? "",
        itemName: item.itemName ?? "",
        description: item.description ?? "",
        parentItemCode: item.parentItemCode ?? "",
        itemLevel: item.itemLevel ?? null,
        deleteFlag: item.deleteFlag ?? "",
        unitOfMeasure: item.unitOfMeasure ?? "",
        steelType: item.steelType ?? "",
        gradeMaterial: item.gradeMaterial ?? "",
        changeDate: item.changeDate ?? "",
        baseUnitOfMeasure: item.baseUnitOfMeasure ?? "",
      });
    }
  }, [item, form]);

  function onSubmit(input: UpdateItemSchema) {
    startUpdateTransition(async () => {
      if (!item) return

      const { error } = await modifyItem({
        id: item.id,
        ...input,
      })

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

      form.reset()
      props.onOpenChange?.(false)
      toast.success("Item updated")
    })
  }

  return (
    <Sheet {...props}>
      <SheetContent className="flex flex-col gap-6 sm:max-w-md">
        <SheetHeader className="text-left">
          <SheetTitle>Update item</SheetTitle>
          <SheetDescription>
            Update the item details and save the changes
          </SheetDescription>
        </SheetHeader>
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="flex flex-col gap-4"
          >
            <FormField
              control={form.control}
              name="itemCode"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>자재그룹코드</FormLabel>
                  <FormControl>
                    <Input placeholder="예: BOLT001" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="itemName"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>자재그룹명</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="예: 육각볼트 M8x20"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>상세</FormLabel>
                  <FormControl>
                    <Textarea
                      placeholder="예: 표준 육각 볼트 스테인리스 스틸"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* 2열 레이아웃 */}
            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="itemLevel"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>레벨</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        min="1"
                        max="5"
                        placeholder="1-5"
                        {...field}
                        value={field.value ?? ""}
                        onChange={(e) => field.onChange(e.target.value ? parseInt(e.target.value) : null)}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="deleteFlag"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>삭제 플래그</FormLabel>
                    <FormControl>
                      <Select onValueChange={field.onChange} value={field.value || ""}>
                        <SelectTrigger>
                          <SelectValue placeholder="선택" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="N">N (사용)</SelectItem>
                          <SelectItem value="Y">Y (삭제)</SelectItem>
                        </SelectContent>
                      </Select>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="parentItemCode"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>부모 아이템 코드</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="예: BOLT001"
                        {...field}
                        value={field.value || ""}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="steelType"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>강종</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="예: SS, CS, AL"
                        maxLength={2}
                        {...field}
                        value={field.value || ""}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="unitOfMeasure"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>단위</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="예: EA, SET, KG"
                        maxLength={3}
                        {...field}
                        value={field.value || ""}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="baseUnitOfMeasure"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>기본단위</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="예: EA, SET, KG"
                        maxLength={3}
                        {...field}
                        value={field.value || ""}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="gradeMaterial"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>등급 재질</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="예: Marine Grade A"
                        {...field}
                        value={field.value || ""}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="changeDate"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>변경일자</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="YYYYMMDD"
                        maxLength={8}
                        {...field}
                        value={field.value || ""}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

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