import { useState, useEffect } from 'react';
import { Dropdown } from 'primereact/dropdown';
import { Button } from 'primereact/button';
import { Column } from 'primereact/column';
import { Tag } from 'primereact/tag';
import BaseCrudTable from '@/core/components/BaseCrudTable';
import BasePageHeader from '@/core/components/BasePageHeader';
import TealUploadDialog from '../components/TealUploadDialog';
import { tealService } from '../teal.service';
import { projectService } from '@/modules/project/project.service';
import type { TealEntry, TealVersion } from '../teal.types';
import { toArray } from '@/core/api/utils';

export default function TealListView() {
  const [projects, setProjects] = useState<{ id: number; name: string; code: string }[]>([]);
  const [selectedProjectId, setSelectedProjectId] = useState<number | null>(null);
  const [versions, setVersions] = useState<TealVersion[]>([]);
  const [selectedVersionId, setSelectedVersionId] = useState<number | null>(null);
  const [entries, setEntries] = useState<TealEntry[]>([]);
  const [loading, setLoading] = useState(false);
  const [uploadVisible, setUploadVisible] = useState(false);

  useEffect(() => {
    projectService.getAll()
      .then(({ data }) => setProjects(toArray<{ id: number; name: string; code: string }>(data)))
      .catch(() => setProjects([]));
  }, []);

  useEffect(() => {
    if (!selectedProjectId) { setVersions([]); setEntries([]); return; }
    tealService.getVersions(selectedProjectId)
      .then(({ data }) => setVersions(toArray<TealVersion>(data)))
      .catch(() => setVersions([]));
  }, [selectedProjectId]);

  useEffect(() => {
    if (!selectedProjectId || !selectedVersionId) { setEntries([]); return; }
    setLoading(true);
    tealService.getActive(selectedProjectId)
      .then(({ data }) => setEntries(toArray<TealEntry>(data)))
      .catch(() => setEntries([]))
      .finally(() => setLoading(false));
  }, [selectedProjectId, selectedVersionId]);

  async function handleUpload(file: File, effectiveDate: string) {
    if (!selectedProjectId) return;
    await tealService.upload(selectedProjectId, file, effectiveDate);
    setUploadVisible(false);
    const { data } = await tealService.getVersions(selectedProjectId);
    setVersions(toArray<TealVersion>(data));
  }

  return (
    <div>
      <BasePageHeader title="TEAL 관리" actions={<Button label="TEAL 업로드" icon="pi pi-upload" size="small" disabled={!selectedProjectId} onClick={() => setUploadVisible(true)} />} />

      <div style={{ display: 'flex', gap: '0.5rem', marginBottom: '1rem', flexWrap: 'wrap' }}>
        <Dropdown value={selectedProjectId} options={projects.map((p) => ({ label: `${p.code} - ${p.name}`, value: p.id }))} onChange={(e) => { setSelectedProjectId(e.value); setSelectedVersionId(null); }} placeholder="프로젝트 선택" style={{ minWidth: '250px' }} />
        <Dropdown value={selectedVersionId} options={versions.map((v) => ({ label: `v${v.versionNumber} (${v.effectiveDate})`, value: v.id }))} onChange={(e) => setSelectedVersionId(e.value)} placeholder="버전 선택" disabled={!selectedProjectId} />
        {versions.find((v) => v.id === selectedVersionId) && (
          <Tag value={versions.find((v) => v.id === selectedVersionId)?.status ?? ''} severity={versions.find((v) => v.id === selectedVersionId)?.status === 'ACTIVE' ? 'success' : 'secondary'} />
        )}
      </div>

      <BaseCrudTable value={entries} loading={loading} globalFilterFields={['activityCode', 'activityName', 'discipline']}>
        <Column field="activityCode" header="Activity Code" sortable />
        <Column field="activityName" header="Activity Name" sortable />
        <Column field="discipline" header="Discipline" sortable />
      </BaseCrudTable>

      <TealUploadDialog visible={uploadVisible} onHide={() => setUploadVisible(false)} onUpload={handleUpload} />
    </div>
  );
}
