// app/(admin)/owner-companies/_components/owner-company-form.tsx
"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { createOwnerCompany, updateOwnerCompany } from "./service";

const formSchema = z.object({
  name: z.string().min(1, "회사명을 입력해주세요"),
});

type FormValues = z.infer<typeof formSchema>;

interface OwnerCompanyFormProps {
  initialData?: {
    id: number;
    name: string;
  };
}

export function OwnerCompanyForm({ initialData }: OwnerCompanyFormProps) {
  const router = useRouter();
  const isEdit = !!initialData;

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: initialData?.name || "",
    },
  });

  async function onSubmit(values: FormValues) {
    try {
      const result = isEdit
        ? await updateOwnerCompany(initialData.id, values)
        : await createOwnerCompany(values);

      if (result.success) {
        toast.success(
          isEdit ? "회사 정보가 수정되었습니다" : "회사가 등록되었습니다"
        );
        router.push("/evcp/data-room/owner-companies");
        router.refresh();
      }
    } catch (error) {
      toast.error("오류가 발생했습니다");
    }
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
        <FormField
          control={form.control}
          name="name"
          render={({ field }) => (
            <FormItem>
              <FormLabel>회사명 *</FormLabel>
              <FormControl>
                <Input placeholder="삼성전자" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <div className="flex gap-2">
          <Button
            type="button"
            variant="outline"
            onClick={() => router.back()}
          >
            취소
          </Button>
          <Button type="submit" disabled={form.formState.isSubmitting}>
            {form.formState.isSubmitting
              ? "처리 중..."
              : isEdit
              ? "수정"
              : "등록"}
          </Button>
        </div>
      </form>
    </Form>
  );
}