summaryrefslogtreecommitdiff
path: root/lib/owner-companies/owner-company-form.tsx
blob: a385eccc9180a949efbdabe2e5dd7f19001104ff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// 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>
  );
}