import { useState, useEffect } from 'react';
import { InputText } from 'primereact/inputtext';
import { Dropdown } from 'primereact/dropdown';
import { MultiSelect } from 'primereact/multiselect';
import { InputSwitch } from 'primereact/inputswitch';
import BaseFormDialog from '@/core/components/BaseFormDialog';
import { ROLES } from '@/core/constants/app.constants';
import type { User } from '../user.types';

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

const DISCIPLINE_OPTIONS = [
  'Piping', 'Electrical', 'Instrument', 'Civil', 'Structural',
  'Mechanical', 'Process', 'HSE', 'QA/QC', 'Other',
].map((d) => ({ label: d, value: d }));

const ROLE_OPTIONS = Object.values(ROLES).map((r) => ({ label: r, value: r }));

export default function UserFormDialog({ visible, onHide, user, onSave }: Props) {
  const [fullName, setFullName] = useState('');
  const [email, setEmail] = useState('');
  const [employeeId, setEmployeeId] = useState('');
  const [department, setDepartment] = useState('');
  const [discipline, setDiscipline] = useState('');
  const [roles, setRoles] = useState<string[]>([]);
  const [isActive, setIsActive] = useState(true);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (user) {
      setFullName(user.fullName);
      setEmail(user.email);
      setEmployeeId(user.employeeId ?? '');
      setDepartment(user.department ?? '');
      setDiscipline(user.discipline ?? '');
      setRoles(user.roles);
      setIsActive(user.isActive);
    } else {
      setFullName(''); setEmail(''); setEmployeeId(''); setDepartment('');
      setDiscipline(''); setRoles([]); setIsActive(true);
    }
  }, [user, visible]);

  async function handleSubmit() {
    setLoading(true);
    try {
      await onSave({ fullName, email, employeeId, department, discipline, roles, isActive });
    } finally {
      setLoading(false);
    }
  }

  return (
    <BaseFormDialog visible={visible} onHide={onHide} title={user ? '사용자 수정' : '사용자 생성'} loading={loading} onSubmit={handleSubmit}>
      <div className="form-grid">
        <div className="col-6 form-field">
          <label className="form-field__label form-field__label--required">이름</label>
          <InputText value={fullName} onChange={(e) => setFullName(e.target.value)} />
        </div>
        <div className="col-6 form-field">
          <label className="form-field__label form-field__label--required">이메일</label>
          <InputText value={email} onChange={(e) => setEmail(e.target.value)} type="email" />
        </div>
        <div className="col-6 form-field">
          <label className="form-field__label">사번</label>
          <InputText value={employeeId} onChange={(e) => setEmployeeId(e.target.value)} />
        </div>
        <div className="col-6 form-field">
          <label className="form-field__label">부서</label>
          <InputText value={department} onChange={(e) => setDepartment(e.target.value)} />
        </div>
        <div className="col-6 form-field">
          <label className="form-field__label">Discipline</label>
          <Dropdown value={discipline} options={DISCIPLINE_OPTIONS} onChange={(e) => setDiscipline(e.value)} placeholder="선택" showClear />
        </div>
        <div className="col-6 form-field">
          <label className="form-field__label">역할</label>
          <MultiSelect value={roles} options={ROLE_OPTIONS} onChange={(e) => setRoles(e.value)} placeholder="선택" />
        </div>
        {user && (
          <div className="col-6 form-field">
            <label className="form-field__label">활성 상태</label>
            <InputSwitch checked={isActive} onChange={(e) => setIsActive(e.value ?? false)} />
          </div>
        )}
      </div>
    </BaseFormDialog>
  );
}
