import { useEffect, useState } from 'react';
import * as XLSX from 'xlsx';
import { fileDownloadUrl, fileViewUrl } from '../../lib/apiClient';

interface ExcelPreviewProps {
  fileId: string;
  fileName: string;
}

export function ExcelPreview({ fileId, fileName }: ExcelPreviewProps) {
  const [workbook, setWorkbook] = useState<XLSX.WorkBook | null>(null);
  const [html, setHtml] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [activeSheet, setActiveSheet] = useState(0);

  useEffect(() => {
    let cancelled = false;
    setWorkbook(null);
    setHtml(null);
    setError(null);
    setActiveSheet(0);

    (async () => {
      try {
        const res = await fetch(fileViewUrl(fileId));
        if (!res.ok) throw new Error('파일을 불러올 수 없습니다.');
        const buffer = await res.arrayBuffer();
        const wb = XLSX.read(buffer, { type: 'array' });
        if (cancelled) return;
        setWorkbook(wb);
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : '미리보기 실패');
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [fileId]);

  useEffect(() => {
    if (!workbook || workbook.SheetNames.length === 0) return;
    const sheet = workbook.Sheets[workbook.SheetNames[activeSheet]];
    setHtml(XLSX.utils.sheet_to_html(sheet, { id: 'excel-preview-table' }));
  }, [workbook, activeSheet]);

  if (error) {
    return (
      <div className="flex h-full w-full flex-col items-center justify-center gap-3 p-6 text-center">
        <p className="text-lg text-white/60">{error}</p>
        <p className="text-sm text-white/40">
          서버 재배포 등으로 파일이 삭제되었을 수 있습니다. 단계 수정에서 다시 첨부해 주세요.
        </p>
        <a
          href={fileDownloadUrl(fileId)}
          className="rounded bg-white/10 px-4 py-2 text-sm font-bold text-white hover:bg-white/20"
        >
          {fileName} 다운로드
        </a>
      </div>
    );
  }

  if (!html) {
    return <p className="text-lg text-white/50">엑셀 미리보기 로딩 중…</p>;
  }

  const sheetNames = workbook?.SheetNames ?? [];

  return (
    <div className="flex h-full w-full min-h-0 flex-col bg-white">
      {sheetNames.length > 1 && (
        <div className="flex shrink-0 gap-1 overflow-x-auto border-b border-slate-200 bg-slate-50 px-3 py-2">
          {sheetNames.map((name, i) => (
            <button
              key={name}
              type="button"
              onClick={() => setActiveSheet(i)}
              className={`shrink-0 rounded px-3 py-1 text-sm font-bold ${
                i === activeSheet ? 'bg-emerald-600 text-white' : 'bg-white text-slate-600 hover:bg-slate-100'
              }`}
            >
              {name}
            </button>
          ))}
        </div>
      )}
      <div
        className="min-h-0 flex-1 overflow-auto p-2 [&_table]:w-full [&_table]:border-collapse [&_td]:border [&_td]:border-slate-200 [&_td]:px-2 [&_td]:py-1 [&_td]:text-sm [&_th]:border [&_th]:border-slate-300 [&_th]:bg-slate-100 [&_th]:px-2 [&_th]:py-1 [&_th]:text-left [&_th]:text-sm [&_th]:font-bold"
        dangerouslySetInnerHTML={{ __html: html }}
      />
    </div>
  );
}
