import { useState } from 'react';
import { Download, FileSpreadsheet, Check } from 'lucide-react';

/*
 * SFR-02 공통컴포넌트: 엑셀 내보내기
 * CSV 형식으로 내보내기 (브라우저 네이티브)
 */

interface ExcelExportProps {
  /** 내보낼 데이터 배열 */
  data: Record<string, unknown>[];
  /** 컬럼 정의 { key, label } */
  columns: { key: string; label: string }[];
  /** 파일명 (확장자 제외) */
  filename?: string;
  /** 버튼 라벨 */
  label?: string;
  className?: string;
}

export function ExcelExport({
  data,
  columns,
  filename = 'export',
  label = '엑셀 내보내기',
  className = '',
}: ExcelExportProps) {
  const [exported, setExported] = useState(false);

  const handleExport = () => {
    if (!data.length) return;

    // BOM + CSV
    const BOM = '\uFEFF';
    const header = columns.map((c) => `"${c.label}"`).join(',');
    const rows = data.map((row) =>
      columns.map((c) => {
        const val = row[c.key];
        const str = val == null ? '' : String(val);
        return `"${str.replace(/"/g, '""')}"`;
      }).join(',')
    );
    const csv = BOM + [header, ...rows].join('\r\n');

    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `${filename}_${new Date().toISOString().slice(0, 10)}.csv`;
    link.click();
    URL.revokeObjectURL(url);

    setExported(true);
    setTimeout(() => setExported(false), 2000);
  };

  return (
    <button
      type="button"
      onClick={handleExport}
      disabled={!data.length}
      className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[10px] font-medium transition-colors disabled:opacity-30 ${
        exported
          ? 'bg-green-600/20 text-green-400 border border-green-500/30'
          : 'bg-surface-overlay border border-border text-muted-foreground hover:text-on-vivid hover:border-border'
      } ${className}`}
    >
      {exported ? <Check className="w-3 h-3" /> : <FileSpreadsheet className="w-3 h-3" />}
      {exported ? '다운로드 완료' : label}
    </button>
  );
}
