import { useState, useEffect } from 'react';
import { InputText } from 'primereact/inputtext';
import { InputSwitch } from 'primereact/inputswitch';
import BaseFormDialog from '@/core/components/BaseFormDialog';
import type { OverheadType } from '../settings.types';

interface Props {
  visible: boolean;
  onHide: () => void;
  overheadType: OverheadType | null;
  onSave: (data: Partial<OverheadType>) => Promise<void>;
}

export default function OverheadTypeDialog({ visible, onHide, overheadType, onSave }: Props) {
  const [code, setCode] = useState('');
  const [name, setName] = useState('');
  const [isActive, setIsActive] = useState(true);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (overheadType) {
      setCode(overheadType.code);
      setName(overheadType.name);
      setIsActive(overheadType.isActive);
    } else {
      setCode(''); setName(''); setIsActive(true);
    }
  }, [overheadType, visible]);

  async function handleSubmit() {
    setLoading(true);
    try {
      await onSave({ code, name, isActive });
    } finally {
      setLoading(false);
    }
  }

  return (
    <BaseFormDialog visible={visible} onHide={onHide} title={overheadType ? 'Overhead Type 수정' : 'Overhead Type 추가'} loading={loading} onSubmit={handleSubmit}>
      <div className="form-field">
        <label className="form-field__label form-field__label--required">코드</label>
        <InputText value={code} onChange={(e) => setCode(e.target.value)} disabled={!!overheadType} />
      </div>
      <div className="form-field">
        <label className="form-field__label form-field__label--required">이름</label>
        <InputText value={name} onChange={(e) => setName(e.target.value)} />
      </div>
      {overheadType && (
        <div className="form-field">
          <label className="form-field__label">활성 상태</label>
          <InputSwitch checked={isActive} onChange={(e) => setIsActive(e.value ?? false)} />
        </div>
      )}
    </BaseFormDialog>
  );
}
