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

import { BiddingProjects } from "@/db/schema/projects"
import { updateBiddingProjectSchema, type UpdateBiddingProjectSchema } from "../validation"
import { updateBiddingProject } from "../actions"

interface UpdateProjectSheetProps
  extends React.ComponentPropsWithRef<typeof Sheet> {
  project: BiddingProjects | null
}

export function UpdateProjectSheet({ project, ...props }: UpdateProjectSheetProps) {
  const [isUpdatePending, startUpdateTransition] = React.useTransition()

  const form = useForm<UpdateBiddingProjectSchema>({
    resolver: zodResolver(updateBiddingProjectSchema),
  })

  React.useEffect(() => {
    if (project) {
      form.reset({
        id: project.id,
        projNm: project.projNm || "",
        kunnrNm: project.kunnrNm || "",
        cls1Nm: project.cls1Nm || "",
        ptypeNm: project.ptypeNm || "",
        pmodelNm: project.pmodelNm || "",
        pmodelSz: project.pmodelSz || "",
        txt30: project.txt30 || "",
        estmPm: project.estmPm || "",
      })
    }
  }, [project, form])

  function onSubmit(input: UpdateBiddingProjectSchema) {
    startUpdateTransition(async () => {
      const result = await updateBiddingProject(input)

      if (result.success) {
        toast.success(result.message)
        props.onOpenChange?.(false)
        form.reset()
      } else {
        toast.error(result.error)
      }
    })
  }

  return (
    <Sheet {...props}>
      <SheetContent className="flex flex-col gap-6 sm:max-w-md">
        <SheetHeader className="text-left">
          <SheetTitle>프로젝트 정보 수정</SheetTitle>
          <SheetDescription>
            해양 TOP 프로젝트의 정보를 수정할 수 있습니다.
            {project && (
              <div className="mt-2 text-sm font-mono bg-muted p-2 rounded">
                {project.pspid} | {project.pjtType}
              </div>
            )}
          </SheetDescription>
        </SheetHeader>

        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="flex flex-col gap-4"
          >
            {/* Hidden ID field */}
            <FormField
              control={form.control}
              name="id"
              render={({ field }) => (
                <input type="hidden" {...field} />
              )}
            />

            {/* 프로젝트명 */}
            <FormField
              control={form.control}
              name="projNm"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>프로젝트명</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="프로젝트명을 입력하세요"
                      {...field}
                      value={field.value || ""}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* 선주명 */}
            <FormField
              control={form.control}
              name="kunnrNm"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>선주명</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="선주명을 입력하세요"
                      {...field}
                      value={field.value || ""}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* 선급명 */}
            <FormField
              control={form.control}
              name="cls1Nm"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>선급명</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="선급명을 입력하세요"
                      {...field}
                      value={field.value || ""}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* 선종명 */}
            <FormField
              control={form.control}
              name="ptypeNm"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>선종명</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="선종명을 입력하세요"
                      {...field}
                      value={field.value || ""}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* 선형명 */}
            <FormField
              control={form.control}
              name="pmodelNm"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>선형명</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="선형명을 입력하세요"
                      {...field}
                      value={field.value || ""}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* 선형크기 */}
            <FormField
              control={form.control}
              name="pmodelSz"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>선형크기</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="선형크기를 입력하세요"
                      {...field}
                      value={field.value || ""}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* 견적상태명 */}
            <FormField
              control={form.control}
              name="txt30"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>견적상태명</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="견적상태명을 입력하세요"
                      {...field}
                      value={field.value || ""}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* 견적대표PM */}
            <FormField
              control={form.control}
              name="estmPm"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>견적대표PM</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="견적대표PM을 입력하세요"
                      {...field}
                      value={field.value || ""}
                    />
                  </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>
  )
} 