'use client';

import { useState, useEffect } from 'react';
import { StandardDialog } from '@/components/molecules/StandardDialog';
import { FormField } from '@/components/molecules/FormField';
import { Button } from '@/components/ui/button';
import { toast } from 'sonner';
import { saveSupplierSettings } from './actions';
import type { SupplierSettings } from './types';

interface SupplierSettingModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  settings: SupplierSettings;
  onSaved: (settings: SupplierSettings) => void;
}

export function SupplierSettingModal({
  open,
  onOpenChange,
  settings,
  onSaved,
}: SupplierSettingModalProps) {
  const [formData, setFormData] = useState<SupplierSettings>(settings);
  const [isSaving, setIsSaving] = useState(false);

  useEffect(() => {
    if (open) {
      setFormData(settings);
    }
  }, [open, settings]);

  const handleChange = (field: keyof SupplierSettings, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  const handleSave = async () => {
    if (!formData.companyName.trim()) {
      toast.error('상호명을 입력하세요.');
      return;
    }
    if (!formData.representativeName.trim()) {
      toast.error('대표자명을 입력하세요.');
      return;
    }

    setIsSaving(true);
    try {
      const result = await saveSupplierSettings(formData);
      if (result.success) {
        toast.success('공급자 정보가 저장되었습니다.');
        onSaved(result.data ?? formData);
        onOpenChange(false);
      } else {
        toast.error(result.error || '저장에 실패했습니다.');
      }
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <StandardDialog
      open={open}
      onOpenChange={onOpenChange}
      title="공급자 기초정보 설정"
      description="세금계산서에 표시될 공급자 정보를 설정합니다."
      size="md"
      footer={
        <div className="flex justify-end gap-2 px-6 pb-4">
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSaving}>
            취소
          </Button>
          <Button onClick={handleSave} disabled={isSaving}>
            {isSaving ? '저장 중...' : '저장'}
          </Button>
        </div>
      }
    >
      <div className="space-y-4">
        <FormField
          label="사업자번호"
          type="businessNumber"
          value={formData.businessNumber}
          onChange={(v) => handleChange('businessNumber', v)}
          placeholder="000-00-00000"
        />
        <FormField
          label="상호명"
          required
          value={formData.companyName}
          onChange={(v) => handleChange('companyName', v)}
          placeholder="상호명을 입력하세요"
        />
        <FormField
          label="대표자명"
          required
          value={formData.representativeName}
          onChange={(v) => handleChange('representativeName', v)}
          placeholder="대표자명을 입력하세요"
        />
        <FormField
          label="주소"
          value={formData.address}
          onChange={(v) => handleChange('address', v)}
          placeholder="사업장 주소를 입력하세요"
        />
        <div className="grid grid-cols-2 gap-4">
          <FormField
            label="업태"
            value={formData.businessType}
            onChange={(v) => handleChange('businessType', v)}
            placeholder="업태"
          />
          <FormField
            label="종목"
            value={formData.businessItem}
            onChange={(v) => handleChange('businessItem', v)}
            placeholder="종목"
          />
        </div>
        <FormField
          label="담당자명"
          value={formData.contactName}
          onChange={(v) => handleChange('contactName', v)}
          placeholder="담당자명"
        />
        <FormField
          label="연락처"
          type="phone"
          value={formData.contactPhone}
          onChange={(v) => handleChange('contactPhone', v)}
          placeholder="010-0000-0000"
        />
        <FormField
          label="이메일"
          value={formData.contactEmail}
          onChange={(v) => handleChange('contactEmail', v)}
          placeholder="email@example.com"
        />
      </div>
    </StandardDialog>
  );
}
