"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 {
  Sheet,
  SheetClose,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"

import { Input } from "@/components/ui/input"
import { UpdateVendorTypeSchema, updateVendorTypeSchema } from "../validations"
import { modifyVendorType } from "../service"
import { VendorTypes } from "@/db/schema"

interface UpdateTypeSheetProps
  extends React.ComponentPropsWithRef<typeof Sheet> {
  vendorType: VendorTypes | null
}

export function UpdateTypeSheet({ vendorType, ...props }: UpdateTypeSheetProps) {
  const [isUpdatePending, startUpdateTransition] = React.useTransition()

  const form = useForm<UpdateVendorTypeSchema>({
    resolver: zodResolver(updateVendorTypeSchema),
    defaultValues: {
      nameKo: vendorType?.nameKo ?? "",
      nameEn: vendorType?.nameEn ?? "",

    },
  })


  React.useEffect(() => {
    if (vendorType) {
      form.reset({
        nameKo: vendorType.nameKo ?? "",
        nameEn: vendorType.nameEn ?? "",
      });
    }
  }, [vendorType, form]);

  function onSubmit(input: UpdateVendorTypeSchema) {
    startUpdateTransition(async () => {
      if (!vendorType) return

      const { error } = await modifyVendorType({
        id: vendorType.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 vendorType</SheetTitle>
          <SheetDescription>
            Update the vendorType 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="nameKo"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>업체 유형 (한글)</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="e.g."
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="nameEn"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>업체 유형 (영문)</FormLabel>
                  <FormControl>
                  <Input
                      placeholder="e.g."
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <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>
  )
}
