"use client";

import * as React from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Plus, Loader2 } from "lucide-react";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { createIncoterm } from "../service";
import { toast } from "sonner";

const createIncotermSchema = z.object({
  code: z.string().min(1, "코드는 필수입니다."),
  description: z.string().min(1, "설명은 필수입니다."),
  isActive: z.boolean().default(true),
});

type CreateIncotermFormValues = z.infer<typeof createIncotermSchema>;

interface IncotermsAddDialogProps {
  onSuccess?: () => void;
}

export function IncotermsAddDialog({ onSuccess }: IncotermsAddDialogProps) {
  const [open, setOpen] = React.useState(false);
  const [isLoading, setIsLoading] = React.useState(false);

  const form = useForm<CreateIncotermFormValues>({
    resolver: zodResolver(createIncotermSchema),
    defaultValues: {
      code: "",
      description: "",
      isActive: true,
    },
  });

  const handleOpenChange = (newOpen: boolean) => {
    setOpen(newOpen);
    if (!newOpen) {
      form.reset();
    }
  };

  const handleCancel = () => {
    form.reset();
    setOpen(false);
  };

  const onSubmit = async (data: CreateIncotermFormValues) => {
    setIsLoading(true);
    try {
      const result = await createIncoterm(data);
      if (result.data) {
        toast.success("인코텀즈가 추가되었습니다.");
        setOpen(false);
        if (onSuccess) {
          onSuccess();
        }
      } else {
        toast.error(result.error || "생성 중 오류가 발생했습니다.");
      }
    } catch (error) {
      console.error("인코텀즈 생성 오류:", error);
      toast.error("인코텀즈 생성에 실패했습니다.");
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogTrigger asChild>
        <Button size="sm" variant="outline">
          <Plus className="mr-2 h-4 w-4" />
          인코텀즈 추가
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>인코텀즈 추가</DialogTitle>
          <DialogDescription>
            새로운 인코텀즈를 추가합니다. 필수 정보를 입력해주세요.
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="code"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>
                    코드 <span className="text-red-500">*</span>
                  </FormLabel>
                  <FormControl>
                    <Input placeholder="인코텀즈 코드" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>
                    설명 <span className="text-red-500">*</span>
                  </FormLabel>
                  <FormControl>
                    <Input placeholder="인코텀즈 설명" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </form>
        </Form>

        <DialogFooter>
          <Button
            type="button"
            variant="outline"
            onClick={handleCancel}
            disabled={isLoading}
          >
            취소
          </Button>
          <Button
            type="submit"
            onClick={form.handleSubmit(onSubmit)}
            disabled={isLoading}
          >
            {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            {isLoading ? "생성 중..." : "인코텀즈 추가"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
} 