summaryrefslogtreecommitdiff
path: root/components/signup/tech-vendor-join-form.tsx
blob: e93a11028bd924c6789827e41276d764049ca445 (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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
"use client"

import * as React from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm, useFieldArray } from "react-hook-form"
import { useRouter, useSearchParams, useParams } from "next/navigation"

import i18nIsoCountries from "i18n-iso-countries"
import enLocale from "i18n-iso-countries/langs/en.json"
import koLocale from "i18n-iso-countries/langs/ko.json"

import { Button } from "@/components/ui/button"
import { Separator } from "@/components/ui/separator"
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { toast } from "@/hooks/use-toast"
import {
  Popover,
  PopoverTrigger,
  PopoverContent,
} from "@/components/ui/popover"
import {
  Command,
  CommandInput,
  CommandEmpty,
  CommandGroup,
  CommandItem,
} from "@/components/ui/command"
import { Check, ChevronsUpDown, Loader2, Plus, X } from "lucide-react"
import { cn } from "@/lib/utils"

import { createTechVendorFromSignup } from "@/lib/tech-vendors/service"
import { TechVendorItemSelectorDialog } from "./tech-vendor-item-selector-dialog"
import { createTechVendorSchema, CreateTechVendorSchema } from "@/lib/tech-vendors/validations"
import { VENDOR_TYPES } from "@/db/schema/techVendors"
import { verifyTechVendorInvitationToken } from "@/lib/tech-vendor-invitation-token"
import { countryDialCodes } from "@/components/common/country-dial-codes"


import {
  Dropzone,
  DropzoneZone,
  DropzoneInput,
  DropzoneUploadIcon,
  DropzoneTitle,
  DropzoneDescription,
} from "@/components/ui/dropzone"
import {
  FileList,
  FileListItem,
  FileListHeader,
  FileListIcon,
  FileListInfo,
  FileListName,
  FileListDescription,
  FileListAction,
} from "@/components/ui/file-list"
import { Badge } from "@/components/ui/badge"
import { ScrollArea } from "@/components/ui/scroll-area"
import prettyBytes from "pretty-bytes"

i18nIsoCountries.registerLocale(enLocale)
i18nIsoCountries.registerLocale(koLocale)

const locale = "ko"
const countryMap = i18nIsoCountries.getNames(locale, { select: "official" })
const countryArray = Object.entries(countryMap).map(([code, label]) => ({
  code,
  label,
}))

// Sort countries to put Korea first, then alphabetically
const sortedCountryArray = [...countryArray].sort((a, b) => {
  if (a.code === "KR") return -1;
  if (b.code === "KR") return 1;
  return a.label.localeCompare(b.label);
});

// Add English names for Korean locale
const enhancedCountryArray = sortedCountryArray.map(country => ({
  ...country,
  label: locale === "ko" && country.code === "KR" 
    ? "대한민국 (South Korea)" 
    : country.label
}));

const MAX_FILE_SIZE = 3e9

export function TechVendorJoinForm() {
  const params = useParams() || {}; 
  const lng = params.lng ? String(params.lng) : "ko"; 

  const router = useRouter()
  const searchParams = useSearchParams() || new URLSearchParams(); 
  const defaultTaxId = searchParams.get("taxID") ?? ""
  const invitationToken = searchParams.get("token") ?? ""

  // States
  const [selectedFiles, setSelectedFiles] = React.useState<File[]>([])
  const [isSubmitting, setIsSubmitting] = React.useState(false)
  const [isLoading, setIsLoading] = React.useState(false)
  const [hasValidToken, setHasValidToken] = React.useState<boolean | null>(null)
  const [isItemSelectorOpen, setIsItemSelectorOpen] = React.useState(false)
  const [selectedItemCodes, setSelectedItemCodes] = React.useState<string[]>([])

  // React Hook Form (항상 최상위에서 호출)
  const form = useForm<CreateTechVendorSchema>({
    resolver: zodResolver(createTechVendorSchema),
    defaultValues: {
      vendorName: "",
      vendorCode: "",
      items: "",
      taxId: defaultTaxId,
      address: "",
      email: "",
      phone: "",
      country: "",
      website: "",
      techVendorType: [],
      representativeName: "",
      representativeBirth: "",
      representativeEmail: "",
      representativePhone: "",
      files: undefined,
      contacts: [
        {
          contactName: "",
          contactPosition: "",
          contactTitle: "",
          contactCountry: "",
          contactEmail: "",
          contactPhone: "",
        },
      ],
    },
    mode: "onChange",
  })

  // Field array for contacts (항상 최상위에서 호출)
  const { fields: contactFields, append: addContact, remove: removeContact } =
    useFieldArray({
      control: form.control,
      name: "contacts",
    })

  // 토큰 검증 로직
  React.useEffect(() => {
    // 토큰이 없으면 유효하지 않음
    if (!invitationToken) {
      setHasValidToken(false);
      return;
    }

    // 토큰이 있으면 검증 수행
    const validateToken = async () => {
      setIsLoading(true);
      
      try {
        const tokenPayload = await verifyTechVendorInvitationToken(invitationToken);
        
        if (tokenPayload) {
          setHasValidToken(true);
          console.log("tokenPayload", tokenPayload);
          // 토큰에서 가져온 정보로 폼 미리 채우기
          form.setValue("vendorName", tokenPayload.vendorName);
          form.setValue("email", tokenPayload.email);
          form.setValue("techVendorType", tokenPayload.vendorType as "조선" | "해양TOP" | "해양HULL" | ("조선" | "해양TOP" | "해양HULL")[]);
          
          // // 연락처 정보도 미리 채우기
          // form.setValue("contacts.0.contactName", tokenPayload.vendorName);
          // form.setValue("contacts.0.contactEmail", tokenPayload.email);
          
          toast({
            title: "초대 정보 로드 완료",
            description: "기존 정보가 자동으로 입력되었습니다. 추가 정보를 입력해주세요.",
          });
        } else {
          setHasValidToken(false);
          toast({
            variant: "destructive",
            title: "유효하지 않은 초대 링크",
            description: "초대 링크가 만료되었거나 유효하지 않습니다.",
          });
        }
      } catch (error) {
        console.error("Token verification error:", error);
        setHasValidToken(false);
        toast({
          variant: "destructive",
          title: "오류 발생",
          description: "초대 정보를 불러오는 중 오류가 발생했습니다.",
        });
      } finally {
        setIsLoading(false);
      }
    };
    
    validateToken();
  }, [invitationToken, form, router]);

  // 토큰이 유효하지 않으면 에러 페이지 표시
  if (hasValidToken === false) {
    return (
      <div className="container py-6">
        <section className="overflow-hidden rounded-md border bg-background shadow-sm">
          <div className="p-6 md:p-10 space-y-6">
            <div className="flex flex-col items-center justify-center py-12 text-center">
              <div className="rounded-lg border border-dashed border-destructive p-10 shadow-sm">
                <h3 className="mb-2 text-xl font-semibold text-destructive">유효하지 않은 접근</h3>
                <p className="mb-6 text-muted-foreground">
                  기술영업 협력업체 등록은 초대를 통해서만 가능합니다.<br />
                  올바른 초대 링크를 통해 접근해주세요.
                </p>
                <Button 
                  variant="destructive" 
                  onClick={() => router.push("/ko/partners")}
                >
                  돌아가기
                </Button>
              </div>
            </div>
          </div>
        </section>
      </div>
    );
  }

  const isFormValid = form.formState.isValid
  console.log("Form errors:", form.formState.errors);
  console.log("Form values:", form.getValues());
  console.log("Form valid:", form.formState.isValid);

  // Dropzone handlers
  const handleDropAccepted = (acceptedFiles: File[]) => {
    const newFiles = [...selectedFiles, ...acceptedFiles]
    setSelectedFiles(newFiles)
    form.setValue("files", newFiles, { shouldValidate: true })
  }

  const handleDropRejected = (fileRejections: any[]) => {
    fileRejections.forEach((rej) => {
      toast({
        variant: "destructive",
        title: "File Error",
        description: `${rej.file.name}: ${rej.errors[0]?.message || "Upload failed"}`,
      })
    })
  }

  const removeFile = (index: number) => {
    const updated = [...selectedFiles]
    updated.splice(index, 1)
    setSelectedFiles(updated)
    form.setValue("files", updated, { shouldValidate: true })
  }

  type SelectedItem = { type: "SHIP" | "TOP" | "HULL", id: number, code: string, name: string };

  const handleItemsSelected = (items: SelectedItem[]) => {
    setSelectedItemCodes(items.map(item => item.code));
    form.setValue("items", JSON.stringify(items));
  }

  // Submit
  async function onSubmit(values: CreateTechVendorSchema) {
    setIsSubmitting(true)
    try {
      const mainFiles = values.files
        ? Array.from(values.files as FileList)
        : []

      const techVendorData = {
        vendorName: values.vendorName,
        vendorCode: values.vendorCode,
        items: values.items,
        website: values.website,
        taxId: values.taxId,
        address: values.address,
        email: values.email,
        phone: values.phone,
        country: values.country,
        techVendorType: values.techVendorType as "조선" | "해양TOP" | "해양HULL" | ("조선" | "해양TOP" | "해양HULL")[],
        representativeName: values.representativeName || "",
        representativeBirth: values.representativeBirth || "",
        representativeEmail: values.representativeEmail || "",
        representativePhone: values.representativePhone || "",
        contacts: values.contacts,
        files: mainFiles,
      }

      const result = await createTechVendorFromSignup({
        vendorData: techVendorData,
        files: mainFiles,
        contacts: values.contacts,
        selectedItemCodes: selectedItemCodes,
        invitationToken: invitationToken || undefined,
      })

      if (!result.error) {
        toast({
          title: "등록 완료",
          description: invitationToken 
            ? "기술영업 업체 정보가 성공적으로 업데이트되었습니다."
            : "기술영업 업체 등록이 완료되었습니다.",
        })
        router.push("/ko/partners")
      } else {
        toast({
          variant: "destructive",
          title: "오류",
          description: result.error || "등록에 실패했습니다.",
        })
      }
    } catch (error: any) {
      console.error(error)
      toast({
        variant: "destructive",
        title: "서버 에러",
        description: error.message || "에러가 발생했습니다.",
      })
    } finally {
      setIsSubmitting(false)
    }
  }

  // Get country code for phone number placeholder
  const getPhonePlaceholder = (countryCode: string) => {
    if (!countryCode || !countryDialCodes[countryCode]) return "전화번호";
    return `${countryDialCodes[countryCode]} 전화번호`;
  };

  if (isLoading) {
    return (
      <div className="container py-6">
        <div className="flex items-center justify-center">
          <Loader2 className="h-8 w-8 animate-spin" />
          <span className="ml-2">기존 정보를 불러오는 중...</span>
        </div>
      </div>
    );
  }

  return (
    <div className="container py-6">
      <section className="overflow-hidden rounded-md border bg-background shadow-sm">
        <div className="p-6 md:p-10 space-y-6">
          <div className="space-y-2">
            <h3 className="text-xl font-semibold">
              {invitationToken ? "기술영업 업체 정보 업데이트" : "기술영업 업체 등록"}
            </h3>
            <p className="text-sm text-muted-foreground">
              {invitationToken 
                ? "기술영업 업체 정보를 업데이트하고 필요한 서류를 첨부해주세요."
                : "기술영업 업체 기본 정보를 입력하고 필요한 서류를 첨부해주세요. 검토 후 빠른 시일 내에 승인처리 해드리겠습니다."
              }
            </p>
          </div>

          <Separator />

          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
              {/* ─────────────────────────────────────────
                  기본 정보
              ───────────────────────────────────────── */}
              <div className="rounded-md border p-4 space-y-4">
                <h4 className="text-md font-semibold">기본 정보</h4>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {/* 업체 유형 */}
                  <FormField
                    control={form.control}
                    name="techVendorType"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel className="after:content-['*'] after:ml-0.5 after:text-red-500">
                          업체 유형
                        </FormLabel>
                        <div className="space-y-2">
                          {VENDOR_TYPES.map((type) => (
                            <div key={type} className="flex items-center space-x-2">
                              <input
                                type="checkbox" 
                                id={`techVendorType-${type}`}
                                checked={field.value?.includes(type) || false}
                                onChange={(e) => {
                                  const currentValues = Array.isArray(field.value) ? field.value : [];
                                  if (e.target.checked) {
                                    field.onChange([...currentValues, type]);
                                  } else {
                                    field.onChange(currentValues.filter((v: string) => v !== type));
                                  }
                                }}
                                className="rounded border-input"
                              />
                              <label htmlFor={`techVendorType-${type}`} className="text-sm">
                                {type}
                              </label>
                            </div>
                          ))}
                        </div>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  {/* 업체명 */}
                  <FormField
                    control={form.control}
                    name="vendorName"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel className="after:content-['*'] after:ml-0.5 after:text-red-500">
                          업체명
                        </FormLabel>
                        <FormControl>
                          <Input placeholder="업체명을 입력하세요" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  {/* 업체 코드 */}
                  <FormField
                    control={form.control}
                    name="vendorCode"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>업체 코드</FormLabel>
                        <FormControl>
                          <Input placeholder="업체 코드를 입력하세요" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  {/* 사업자등록번호 */}
                  <FormField
                    control={form.control}
                    name="taxId"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel className="after:content-['*'] after:ml-0.5 after:text-red-500">
                          사업자등록번호
                        </FormLabel>
                        <FormControl>
                          <Input placeholder="000-00-00000" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  {/* 국가 */}
                  <FormField
                    control={form.control}
                    name="country"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel className="after:content-['*'] after:ml-0.5 after:text-red-500">
                          국가
                        </FormLabel>
                        <Popover>
                          <PopoverTrigger asChild>
                            <FormControl>
                              <Button
                                variant="outline"
                                role="combobox"
                                className={cn(
                                  "w-full justify-between",
                                  !field.value && "text-muted-foreground"
                                )}
                              >
                                {field.value
                                  ? i18nIsoCountries.getName(field.value, "ko")
                                  : "국가를 선택하세요"}
                                <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                              </Button>
                            </FormControl>
                          </PopoverTrigger>
                          <PopoverContent className="w-full p-0">
                            <Command>
                              <CommandInput placeholder="국가를 검색하세요..." />
                              <CommandEmpty>국가를 찾을 수 없습니다.</CommandEmpty>
                              <CommandGroup>
                                <ScrollArea className="h-72">
                                  {Object.entries(i18nIsoCountries.getNames("ko")).map(([code, name]) => (
                                    <CommandItem
                                      key={code}
                                      value={`${code} ${name}`}
                                      onSelect={() => {
                                        form.setValue("country", code);
                                      }}
                                    >
                                      <Check
                                        className={cn(
                                          "mr-2 h-4 w-4",
                                          code === field.value ? "opacity-100" : "opacity-0"
                                        )}
                                      />
                                      {name}
                                    </CommandItem>
                                  ))}
                                </ScrollArea>
                              </CommandGroup>
                            </Command>
                          </PopoverContent>
                        </Popover>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  {/* 주소 */}
                  <FormField
                    control={form.control}
                    name="address"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>주소</FormLabel>
                        <FormControl>
                          <Input placeholder="주소를 입력하세요" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  {/* 이메일 (수정 불가, 뷰 전용) */}
                  <FormField
                    control={form.control}
                    name="email"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel className="after:content-['*'] after:ml-0.5 after:text-red-500">
                          이메일
                        </FormLabel>
                        <FormControl>
                          <Input
                            placeholder="example@company.com"
                            {...field}
                            readOnly
                            tabIndex={-1}
                            className="bg-muted cursor-not-allowed pointer-events-none"
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  {/* 전화번호 */}
                  <FormField
                    control={form.control}
                    name="phone"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>전화번호</FormLabel>
                        <FormControl>
                          <Input 
                            placeholder={getPhonePlaceholder(form.watch("country"))} 
                            {...field} 
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  {/* 웹사이트 */}
                  <FormField
                    control={form.control}
                    name="website"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>웹사이트</FormLabel>
                        <FormControl>
                          <Input placeholder="https://www.example.com" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  {/* 주요 품목 */}
                  <FormField
                    control={form.control}
                    name="items"
                    render={({ field }) => (
                      <FormItem className="md:col-span-2">
                        <FormLabel className="after:content-['*'] after:ml-0.5 after:text-red-500">
                          주요 품목
                        </FormLabel>
                        <div className="space-y-2">
                          <FormControl>
                            <Input placeholder="주요 품목을 입력하세요" {...field} />
                          </FormControl>
                          <div className="flex items-center space-x-2">
                            <Button
                              type="button"
                              variant="outline"
                              size="sm"
                              onClick={() => setIsItemSelectorOpen(true)}
                              disabled={!form.watch("techVendorType") || (Array.isArray(form.watch("techVendorType")) && form.watch("techVendorType").length === 0)}
                            >
                              공급가능품목 선택
                            </Button>
                            {selectedItemCodes.length > 0 && (
                              <span className="text-sm text-muted-foreground">
                                {selectedItemCodes.length}개 아이템 선택됨
                              </span>
                            )}
                          </div>
                        </div>
                        <FormDescription>
                          공급가능품목 선택 버튼을 클릭하여 아이템을 선택하세요. 원하는 아이템이 없다면 텍스트로 입력하세요.
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              </div>

              {/* ─────────────────────────────────────────
                  대표자 정보
              ───────────────────────────────────────── */}
              <div className="rounded-md border p-4 space-y-4">
                <h4 className="text-md font-semibold">대표자 정보</h4>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {/* 대표자명 */}
                  <FormField
                    control={form.control}
                    name="representativeName"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>대표자명</FormLabel>
                        <FormControl>
                          <Input placeholder="대표자명을 입력하세요" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  {/* 대표자 생년월일 */}
                  <FormField
                    control={form.control}
                    name="representativeBirth"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>대표자 생년월일</FormLabel>
                        <FormControl>
                          <Input placeholder="YYYY-MM-DD" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  {/* 대표자 이메일 */}
                  <FormField
                    control={form.control}
                    name="representativeEmail"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>대표자 이메일</FormLabel>
                        <FormControl>
                          <Input placeholder="representative@company.com" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  {/* 대표자 전화번호 */}
                  <FormField
                    control={form.control}
                    name="representativePhone"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>대표자 전화번호</FormLabel>
                        <FormControl>
                          <Input placeholder="대표자 전화번호를 입력하세요" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              </div>

              {/* ─────────────────────────────────────────
                  연락처 정보
              ───────────────────────────────────────── */}
              <div className="rounded-md border p-4 space-y-4">
                <div className="flex items-center justify-between">
                  <h4 className="text-md font-semibold">연락처 정보</h4>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() =>
                      addContact({
                        contactName: "",
                        contactPosition: "",
                        contactEmail: "",
                        contactPhone: "",
                      })
                    }
                  >
                    <Plus className="mr-2 h-4 w-4" />
                    연락처 추가
                  </Button>
                </div>

                {contactFields.map((field, index) => (
                  <div key={field.id} className="space-y-4 p-4 border rounded-lg">
                    <div className="flex items-center justify-between">
                      <h5 className="text-sm font-medium">연락처 {index + 1}</h5>
                      {contactFields.length > 1 && (
                        <Button
                          type="button"
                          variant="outline"
                          size="sm"
                          onClick={() => removeContact(index)}
                        >
                          <X className="mr-2 h-4 w-4" />
                          삭제
                        </Button>
                      )}
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <FormField
                        control={form.control}
                        name={`contacts.${index}.contactName`}
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel className="after:content-['*'] after:ml-0.5 after:text-red-500">
                              연락처명
                            </FormLabel>
                            <FormControl>
                              <Input placeholder="연락처명을 입력하세요" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />

                      <FormField
                        control={form.control}
                        name={`contacts.${index}.contactPosition`}
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>직책</FormLabel>
                            <FormControl>
                              <Input placeholder="직책을 입력하세요" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={form.control}
                        name={`contacts.${index}.contactTitle`}
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>직위</FormLabel>
                            <FormControl>
                              <Input placeholder="직위를 입력하세요" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />

                      <FormField
                        control={form.control}
                        name={`contacts.${index}.contactCountry`}
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>국가</FormLabel>
                            <FormControl>
                              <Input placeholder="국가를 입력하세요" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />

                      <FormField
                        control={form.control}
                        name={`contacts.${index}.contactEmail`}
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel className="after:content-['*'] after:ml-0.5 after:text-red-500">
                              이메일
                            </FormLabel>
                            <FormControl>
                              <Input placeholder="contact@company.com" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />

                      <FormField
                        control={form.control}
                        name={`contacts.${index}.contactPhone`}
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>전화번호</FormLabel>
                            <FormControl>
                              <Input placeholder="전화번호를 입력하세요" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>
                  </div>
                ))}
              </div>

              {/* ─────────────────────────────────────────
                  첨부파일
              ───────────────────────────────────────── */}
              <div className="rounded-md border p-4 space-y-4">
                <h4 className="text-md font-semibold">첨부파일</h4>
                <FormField
                  control={form.control}
                  name="files"
                  render={({ field }) => (
                    <FormItem>
                      <FormControl>
                        <Dropzone
                          onDropAccepted={handleDropAccepted}
                          onDropRejected={handleDropRejected}
                          maxSize={MAX_FILE_SIZE}
                          accept={{
                            "application/pdf": [".pdf"],
                            "application/msword": [".doc"],
                            "application/vnd.openxmlformats-officedocument.wordprocessingml.document": [
                              ".docx",
                            ],
                            "application/vnd.ms-excel": [".xls"],
                            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": [
                              ".xlsx",
                            ],
                            "image/*": [".png", ".jpg", ".jpeg"],
                          }}
                        >
                          <DropzoneZone>
                            <DropzoneUploadIcon className="mx-auto h-12 w-12 text-muted-foreground" />
                            <DropzoneTitle className="text-lg font-medium">
                              파일을 드래그하거나 클릭하여 업로드
                            </DropzoneTitle>
                            <DropzoneDescription className="text-sm text-muted-foreground">
                              PDF, Word, Excel, 이미지 파일 (최대 3GB)
                            </DropzoneDescription>
                          </DropzoneZone>
                          <DropzoneInput />
                        </Dropzone>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {selectedFiles.length > 0 && (
                  <div className="space-y-2">
                    <FileListHeader>
                      <FileListIcon />
                      <FileListInfo>
                        <FileListName>업로드된 파일</FileListName>
                        <FileListDescription>
                          {selectedFiles.length}개 파일
                        </FileListDescription>
                      </FileListInfo>
                    </FileListHeader>
                    <ScrollArea className="h-32">
                      {selectedFiles.map((file, index) => (
                        <FileListItem key={index}>
                          <FileListIcon />
                          <FileListInfo>
                            <FileListName>{file.name}</FileListName>
                            <FileListDescription>
                              {prettyBytes(file.size)}
                            </FileListDescription>
                          </FileListInfo>
                          <FileListAction>
                            <Button
                              type="button"
                              variant="outline"
                              size="sm"
                              onClick={() => removeFile(index)}
                            >
                              <X className="h-4 w-4" />
                            </Button>
                          </FileListAction>
                        </FileListItem>
                      ))}
                    </ScrollArea>
                  </div>
                )}
              </div>

              <div className="flex justify-end">
                <Button type="submit" disabled={!isFormValid || isSubmitting}>
                  {isSubmitting ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      {invitationToken ? "업데이트 중..." : "등록 중..."}
                    </>
                  ) : (
                    invitationToken ? "업데이트하기" : "등록하기"
                  )}
                </Button>
              </div>
            </form>
          </Form>
        </div>
      </section>

      {/* 공급가능품목 선택 다이얼로그 */}
      <TechVendorItemSelectorDialog
        open={isItemSelectorOpen}
        onOpenChange={setIsItemSelectorOpen}
        vendorType={form.watch("techVendorType")}
        onItemsSelected={handleItemsSelected}
      />
    </div>
  )
}