"use client"

import * as React from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import { Loader, Save } from "lucide-react"
import { useForm } from "react-hook-form"
import { toast } from "sonner"
import { z } from "zod"
import { useRouter } from "next/navigation"

import { Button } from "@/components/ui/button"
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Sheet,
  SheetClose,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { modifyDocument } from "../service"

// Document 수정을 위한 Zod 스키마 정의
const updateDocumentSchema = z.object({
  docNumber: z.string().min(1, "Document number is required"),
  title: z.string().min(1, "Title is required"),
  status: z.string().min(1, "Status is required"),
  description: z.string().optional(),
  remarks: z.string().optional()
});

type UpdateDocumentSchema = z.infer<typeof updateDocumentSchema>;

// 상태 옵션 정의
const statusOptions = [
  "pending",
  "in-progress",
  "completed",
  "rejected"
];

interface UpdateDocumentSheetProps
  extends React.ComponentPropsWithRef<typeof Sheet> {
  document: {
    id: number;
    contractId: number;
    docNumber: string;
    title: string;
    status: string;
    description?: string | null;
    remarks?: string | null;
  } | null
}

export function UpdateDocumentSheet({ document, ...props }: UpdateDocumentSheetProps) {
  const [isUpdatePending, startUpdateTransition] = React.useTransition()
  const router = useRouter()

  const form = useForm<UpdateDocumentSchema>({
    resolver: zodResolver(updateDocumentSchema),
    defaultValues: {
      docNumber: "",
      title: "",
      status: "",
      description: "",
      remarks: "",
    },
  })

  // 폼 초기화 (document가 변경될 때)
  React.useEffect(() => {
    if (document) {
      form.reset({
        docNumber: document.docNumber,
        title: document.title,
        status: document.status,
        description: document.description ?? "",
        remarks: document.remarks ?? "",
      });
    }
  }, [document, form]);

  function onSubmit(input: UpdateDocumentSchema) {
    startUpdateTransition(async () => {
      if (!document) return
      
      const result = await modifyDocument({
        id: document.id,
        contractId: document.contractId,
        ...input,
      })
      
      if (!result.success) {
        if ('error' in result) {
          toast.error(result.error)
        } else {
          toast.error("Failed to update document")
        }
        return
      }
      
      form.reset()
      props.onOpenChange?.(false)
      toast.success("Document updated successfully")
      router.refresh()
    })
  }

  return (
    <Sheet {...props}>
      <SheetContent className="flex flex-col gap-6 sm:max-w-md">
        <SheetHeader className="text-left">
          <SheetTitle>Update Document</SheetTitle>
          <SheetDescription>
            Update the document 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="docNumber"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Document Number</FormLabel>
                  <FormControl>
                    <Input placeholder="Enter document number" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            
            {/* 문서 제목 필드 */}
            <FormField
              control={form.control}
              name="title"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Title</FormLabel>
                  <FormControl>
                    <Input placeholder="Enter document title" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            
            {/* 상태 필드 */}
            <FormField
              control={form.control}
              name="status"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Status</FormLabel>
                  <Select 
                    onValueChange={field.onChange} 
                    defaultValue={field.value}
                    value={field.value}
                  >
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="Select status" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectGroup>
                        {statusOptions.map((status) => (
                          <SelectItem key={status} value={status}>
                            {status.charAt(0).toUpperCase() + status.slice(1)}
                          </SelectItem>
                        ))}
                      </SelectGroup>
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />
            
            {/* 설명 필드 */}
            <FormField
              control={form.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Description</FormLabel>
                  <FormControl>
                    <Textarea
                      placeholder="Enter document description"
                      className="min-h-[80px]"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            
            {/* 비고 필드 */}
            <FormField
              control={form.control}
              name="remarks"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Remarks</FormLabel>
                  <FormControl>
                    <Textarea
                      placeholder="Enter additional remarks"
                      className="min-h-[80px]"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            
            <SheetFooter className="gap-2 pt-2 sm:space-x-0">
              <SheetClose asChild>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => form.reset()}
                >
                  Cancel
                </Button>
              </SheetClose>
              <Button disabled={isUpdatePending}>
                {isUpdatePending && (
                  <Loader
                    className="mr-2 size-4 animate-spin"
                    aria-hidden="true"
                  />
                )}
                <Save className="mr-2 size-4" /> Save
              </Button>
            </SheetFooter>
          </form>
        </Form>
      </SheetContent>
    </Sheet>
  )
}