import { useState } from 'react';
import { FileUpload, type FileUploadSelectEvent } from 'primereact/fileupload';
import { Calendar } from 'primereact/calendar';
import BaseFormDialog from '@/core/components/BaseFormDialog';

interface Props {
  visible: boolean;
  onHide: () => void;
  onUpload: (file: File, effectiveDate: string) => Promise<void>;
}

export default function TealUploadDialog({ visible, onHide, onUpload }: Props) {
  const [file, setFile] = useState<File | null>(null);
  const [effectiveDate, setEffectiveDate] = useState<Date | null>(null);
  const [loading, setLoading] = useState(false);

  function onSelect(e: FileUploadSelectEvent) {
    setFile(e.files[0] ?? null);
  }

  async function handleSubmit() {
    if (!file || !effectiveDate) return;
    setLoading(true);
    try {
      await onUpload(file, effectiveDate.toISOString().slice(0, 10));
    } finally {
      setLoading(false);
    }
  }

  return (
    <BaseFormDialog visible={visible} onHide={onHide} title="TEAL 업로드" loading={loading} onSubmit={handleSubmit} submitLabel="업로드">
      <div className="form-field">
        <label className="form-field__label form-field__label--required">TEAL 파일</label>
        <FileUpload mode="basic" accept=".xls,.xlsx,.csv" maxFileSize={10000000} onSelect={onSelect} chooseLabel="파일 선택" auto={false} />
      </div>
      <div className="form-field">
        <label className="form-field__label form-field__label--required">적용일</label>
        <Calendar value={effectiveDate} onChange={(e) => setEffectiveDate(e.value as Date)} dateFormat="yy-mm-dd" />
      </div>
    </BaseFormDialog>
  );
}
