"use client";
import * as React from "react";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from "@/components/ui/form";
import { Plus } from "lucide-react";
import { toast } from "sonner";
import { createGeneralEvaluation } from "@/lib/general-check-list/service";
import { useRouter } from "next/navigation";

const schema = z.object({
  category: z.string().min(1, "카테고리를 입력하세요"),
  inspectionItem: z.string().min(1, "점검 항목을 입력하세요"),
  remarks: z.string().optional(),
});

type FormValues = z.infer<typeof schema>;

export function CreateEvaluationDialog({ onSuccess }: { onSuccess?: () => void }) {
  const [open, setOpen] = React.useState(false);
  const [pending, setPending] = React.useState(false);
  const router = useRouter();          // ⬅️

  const form = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: { category: "", inspectionItem: "", remarks: "" },
  });

  async function onSubmit(values: FormValues) {
    setPending(true);
    const res = await createGeneralEvaluation(values);
    if (res.success) {
      toast.success(res.message);
      router.refresh();                // ❷ 새로고침

      onSuccess?.();
      setOpen(false);
      form.reset();
    } else {
      toast.error(res.message);
    }
    setPending(false);
  }

  return (
    <Dialog open={open} onOpenChange={(v) => !pending && setOpen(v)}>
      <DialogTrigger asChild>
        <Button variant="outline" size="sm" className="gap-2">
          <Plus className="size-4" /> 새 항목
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[480px]">
        <DialogHeader>
          <DialogTitle>새 정기평가 체크리스트</DialogTitle>
          <DialogDescription>점검 항목을 추가합니다.</DialogDescription>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="category"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>카테고리</FormLabel>
                  <FormControl>
                    <Input placeholder="예: 안전" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="inspectionItem"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>점검 항목</FormLabel>
                  <FormControl>
                    <Input placeholder="예: 안전모 착용 여부" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="remarks"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>비고 (선택)</FormLabel>
                  <FormControl>
                    <Input placeholder="메모" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <DialogFooter>
              <Button type="submit" disabled={pending}>
                {pending ? "저장중..." : "저장"}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}