// =============================================================
// AdminCsvExport.jsx — CSVエクスポート画面
// =============================================================

const { useState: useStateCsv, useMemo: useMemoC2 } = React;

const AdminCsvExport = ({ appData }) => {
  const { Download, CheckCircle: CheckCircleCSV } = window.LucideReact;

  // デフォルト期間（直近3ヶ月）
  const [startDate, setStartDate] = useStateCsv(() => {
    const d = new Date(); d.setMonth(d.getMonth() - 3);
    return d.toISOString().split('T')[0];
  });
  const [endDate,    setEndDate]    = useStateCsv(() => new Date().toISOString().split('T')[0]);
  const [centerId,   setCenterId]   = useStateCsv('all');
  const [dataType,   setDataType]   = useStateCsv('checks');
  const [downloading, setDownloading] = useStateCsv(false);
  const [done,        setDone]        = useStateCsv(false);

  // 対象件数プレビュー
  const filteredCount = useMemoC2(() => {
    const inRange = (dateStr) => dateStr >= startDate && dateStr <= endDate;
    const inCenter = (cid) => centerId === 'all' || cid === parseInt(centerId);

    if (dataType === 'checks') {
      return (appData.checkRecords || []).filter(r => {
        if (!inRange(r.check_date)) return false;
        const area = window.MASTER_AREAS.find(a => a.id === r.area_id);
        return inCenter(area?.center_id);
      }).length;
    } else {
      return (appData.correctionOrders || []).filter(o => {
        const d = o.created_at.split('T')[0];
        return inRange(d) && inCenter(o.center_id);
      }).length;
    }
  }, [appData, startDate, endDate, centerId, dataType]);

  const handleDownload = () => {
    setDownloading(true);
    const inRange  = (d) => d >= startDate && d <= endDate;
    const inCenter = (cid) => centerId === 'all' || cid === parseInt(centerId);
    let content = '', filename = '';

    if (dataType === 'checks') {
      const records = (appData.checkRecords || []).filter(r => {
        if (!inRange(r.check_date)) return false;
        const area = window.MASTER_AREAS.find(a => a.id === r.area_id);
        return inCenter(area?.center_id);
      });
      const headers = ['実施記録ID','実施日','開始時間','センター','エリア','実施者','OK件数','NG件数','作成日時'];
      const rows = records.map(r => {
        const area   = window.MASTER_AREAS.find(a => a.id === r.area_id);
        const center = window.MASTER_CENTERS.find(c => c.id === area?.center_id);
        const user   = window.MASTER_USERS.find(u => u.id === r.user_id);
        const res    = (appData.checkResults || []).filter(x => x.check_record_id === r.id);
        const ok = res.filter(x => x.result === 'OK').length;
        const ng = res.filter(x => x.result === 'NG').length;
        return [r.id, r.check_date, r.start_time, center?.name||'', area?.name||'', user?.name||'', ok, ng, r.created_at];
      });
      content  = [headers, ...rows].map(row => row.map(v => `"${String(v).replace(/"/g,'""')}"`).join(',')).join('\n');
      filename = `チェック記録_${startDate}_${endDate}.csv`;

    } else {
      const orders = (appData.correctionOrders || []).filter(o => {
        return inRange(o.created_at.split('T')[0]) && inCenter(o.center_id);
      });
      const headers = ['是正指示ID','作成日','センター','期限','ステータス','指示内容','報告件数'];
      const rows = orders.map(o => {
        const center    = window.MASTER_CENTERS.find(c => c.id === o.center_id);
        const repCnt    = (appData.correctionReports || []).filter(r => r.correction_order_id === o.id).length;
        const statusMap = { pending:'未対応', in_review:'承認待ち', resolved:'承認済', rejected:'差戻し' };
        return [o.id, o.created_at.split('T')[0], center?.name||'', o.deadline, statusMap[o.status]||o.status, o.content, repCnt];
      });
      content  = [headers, ...rows].map(row => row.map(v => `"${String(v).replace(/"/g,'""')}"`).join(',')).join('\n');
      filename = `是正指示_${startDate}_${endDate}.csv`;
    }

    const bom  = '\uFEFF';
    const blob = new Blob([bom + content], { type: 'text/csv;charset=utf-8;' });
    const url  = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href     = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);

    setDownloading(false);
    setDone(true);
    setTimeout(() => setDone(false), 3000);
  };

  const dataTypes = [
    { v: 'checks',      label: 'チェック記録' },
    { v: 'corrections', label: '是正指示'     },
  ];

  return (
    <div className="p-6 max-w-2xl">
      <h1 className="text-xl font-bold text-slate-800 mb-1">CSVエクスポート</h1>
      <p className="text-sm text-slate-500 mb-6">出力条件を指定してデータをダウンロードします</p>

      <div className="bg-white rounded-2xl border border-slate-200 p-6 space-y-5">

        {/* 出力データ種別 */}
        <div>
          <label className="block text-xs font-bold text-slate-500 mb-2">出力データ</label>
          <div className="flex gap-2">
            {dataTypes.map(({ v, label }) => (
              <button
                key={v}
                onClick={() => setDataType(v)}
                className={`px-4 py-2 rounded-xl text-sm font-semibold transition-all border ${
                  dataType === v
                    ? 'bg-indigo-600 text-white border-indigo-600'
                    : 'bg-white text-slate-600 border-slate-300 hover:border-indigo-300'
                }`}
              >
                {label}
              </button>
            ))}
          </div>
        </div>

        {/* 期間 */}
        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className="block text-xs font-bold text-slate-500 mb-1.5">開始日</label>
            <input type="date" value={startDate} onChange={e => setStartDate(e.target.value)}
              className="w-full text-sm border border-slate-300 rounded-xl px-3 py-2.5 outline-none focus:ring-2 focus:ring-indigo-300" />
          </div>
          <div>
            <label className="block text-xs font-bold text-slate-500 mb-1.5">終了日</label>
            <input type="date" value={endDate} onChange={e => setEndDate(e.target.value)}
              className="w-full text-sm border border-slate-300 rounded-xl px-3 py-2.5 outline-none focus:ring-2 focus:ring-indigo-300" />
          </div>
        </div>

        {/* センター */}
        <div>
          <label className="block text-xs font-bold text-slate-500 mb-1.5">センター</label>
          <select value={centerId} onChange={e => setCenterId(e.target.value)}
            className="w-full text-sm border border-slate-300 rounded-xl px-3 py-2.5 bg-white outline-none focus:ring-2 focus:ring-indigo-300">
            <option value="all">全センター</option>
            {window.MASTER_CENTERS.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
        </div>

        {/* 件数プレビュー + ダウンロードボタン */}
        <div className="pt-3 border-t border-slate-100">
          <div className="flex items-end justify-between gap-4">
            <div>
              <p className="text-xs text-slate-400 mb-1">出力対象件数</p>
              <p className="text-3xl font-bold text-slate-800 leading-none">
                {filteredCount.toLocaleString()}
                <span className="text-base font-normal text-slate-500 ml-1">件</span>
              </p>
              {filteredCount === 0 && (
                <p className="text-xs text-slate-400 mt-1">条件に該当するデータがありません</p>
              )}
            </div>
            <button
              onClick={handleDownload}
              disabled={filteredCount === 0 || downloading}
              className="flex items-center gap-2 px-5 py-3 rounded-xl text-sm font-bold transition-colors disabled:bg-slate-100 disabled:text-slate-400 text-white"
              style={{ backgroundColor: filteredCount > 0 && !downloading ? (done ? '#22c55e' : '#6366f1') : undefined }}
            >
              {done
                ? <><CheckCircleCSV size={16} />ダウンロード完了</>
                : <><Download size={16} />{downloading ? '処理中...' : 'CSVダウンロード'}</>
              }
            </button>
          </div>
        </div>
      </div>

      {/* CSVフォーマット説明 */}
      <div className="mt-4 bg-slate-50 rounded-2xl border border-slate-200 p-4">
        <p className="text-xs font-bold text-slate-500 mb-2">出力フォーマット</p>
        <p className="text-[11px] text-slate-400 leading-relaxed">
          {dataType === 'checks'
            ? '実施記録ID / 実施日 / 開始時間 / センター / エリア / 実施者 / OK件数 / NG件数 / 作成日時'
            : '是正指示ID / 作成日 / センター / 期限 / ステータス / 指示内容 / 報告件数'
          }
        </p>
        <p className="text-[11px] text-slate-400 mt-1">文字コード: UTF-8（BOM付き）</p>
      </div>
    </div>
  );
};

Object.assign(window, { AdminCsvExport });
