const { useState, useEffect } = React;

function OverallReportView() {
  const [loading, setLoading] = useState(false);
  const [errorMsg, setErrorMsg] = useState('');
  const [reportData, setReportData] = useState(null);
  
  // Date Presets
  const getPreset = (days) => {
    const end = new Date();
    const start = new Date();
    start.setDate(end.getDate() - days);
    return { start: start.toISOString().split('T')[0], end: end.toISOString().split('T')[0] };
  };

  const presets = {
    today: getPreset(0),
    yesterday: {
      start: new Date(Date.now() - 86400000).toISOString().split('T')[0],
      end: new Date(Date.now() - 86400000).toISOString().split('T')[0]
    },
    last7: getPreset(6),
    last30: getPreset(29),
    thisMonth: {
      start: new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().split('T')[0],
      end: new Date().toISOString().split('T')[0]
    }
  };

  const [startDate, setStartDate] = useState(presets.last7.start);
  const [endDate, setEndDate] = useState(presets.last7.end);
  const [statusFilter, setStatusFilter] = useState('ALL'); // ALL, ACTIVE, INACTIVE

  const [activeTab, setActiveTab] = useState('campaigns');

  const handleFetch = async () => {
    setLoading(true);
    setErrorMsg('');
    setReportData(null);
    try {
      if (typeof fetchOverallReport !== 'function') throw new Error('Data fetcher not ready');
      let data = await fetchOverallReport(startDate, endDate, statusFilter);
      
      // If data is array (raw items), or has rawData, or has data.data, we should transform it
      if (Array.isArray(data) || data.rawData || data.data || data.status === 'success') {
        if (typeof transformMetaRawData === 'function') {
           data = transformMetaRawData(data, startDate, endDate);
        }
      }
      
      setReportData(data);
    } catch (err) {
      setErrorMsg(err.message);
    }
    setLoading(false);
  };

  const formatCurrency = (val) => '฿' + Number(val).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  const formatNumber = (val) => Number(val).toLocaleString();
  const formatPercent = (val) => Number(val).toFixed(2) + '%';

  const renderTable = (headers, rows, style = {}) => (
    <div className="card" style={{ overflowX: 'auto', marginBottom: 20, ...style }}>
      <table className="tbl" style={{ minWidth: 800 }}>
        <thead>
          <tr>
            {headers.map((h, i) => <th key={i}>{h}</th>)}
          </tr>
        </thead>
        <tbody>
          {rows.length === 0 ? (
            <tr><td colSpan={headers.length} style={{textAlign:'center', padding: '30px', color: 'var(--ink-3)'}}>ไม่พบข้อมูลในช่วงเวลานี้</td></tr>
          ) : rows.map((row, i) => (
            <tr key={i}>
              {row.map((cell, j) => <td key={j}>{cell !== undefined && cell !== null ? cell : '-'}</td>)}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );

  const getCampaignRows = () => {
    return (reportData?.campaigns || []).map(c => [
      c.name,
      formatCurrency(c.spend),
      formatNumber(c.impressions),
      formatNumber(c.clicks),
      formatPercent(c.ctr),
      formatNumber(c.purchases),
      formatCurrency(c.sales),
      formatCurrency(c.cpa),
      Number(c.roas).toFixed(2)
    ]);
  };

  const getAdSetRows = () => {
    return (reportData?.adSets || []).map(a => [
      a.name,
      a.campaign_name,
      formatCurrency(a.spend),
      formatNumber(a.impressions),
      formatNumber(a.clicks),
      formatPercent(a.ctr),
      formatNumber(a.purchases),
      formatCurrency(a.sales),
      formatCurrency(a.cpa),
      Number(a.roas).toFixed(2)
    ]);
  };

  const getAdRows = () => {
    return (reportData?.ads || []).map(a => [
      a.name,
      a.adset_name,
      a.campaign_name,
      formatCurrency(a.spend),
      formatNumber(a.impressions),
      formatNumber(a.clicks),
      formatPercent(a.ctr),
      formatNumber(a.purchases),
      formatCurrency(a.sales),
      formatCurrency(a.cpa),
      Number(a.roas).toFixed(2)
    ]);
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--section-gap)' }} className="fade-up">
      <ViewHeader
        title="Meta Ads Analysis"
        en="Granular Dashboard"
        sub="ดูข้อมูล Report ระดับ Campaign, Ad Set, Ad พร้อมเครื่องมือกรองข้อมูล"
      />

      <div className="card" style={{ padding: 'var(--pad-card)' }}>
        <div style={{ display: 'flex', gap: 16, alignItems: 'flex-end', flexWrap: 'wrap' }}>
          <div>
            <label className="eyebrow" style={{ display: 'block', marginBottom: 4 }}>Date Preset</label>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              <button className="btn btn-ghost" onClick={() => { setStartDate(presets.today.start); setEndDate(presets.today.end); }}>Today</button>
              <button className="btn btn-ghost" onClick={() => { setStartDate(presets.yesterday.start); setEndDate(presets.yesterday.end); }}>Yesterday</button>
              <button className="btn btn-ghost" onClick={() => { setStartDate(presets.last7.start); setEndDate(presets.last7.end); }}>Last 7</button>
              <button className="btn btn-ghost" onClick={() => { setStartDate(presets.last30.start); setEndDate(presets.last30.end); }}>Last 30</button>
              <button className="btn btn-ghost" onClick={() => { setStartDate(presets.thisMonth.start); setEndDate(presets.thisMonth.end); }}>This Month</button>
            </div>
          </div>
        </div>

        <div style={{ display: 'flex', gap: 16, alignItems: 'flex-end', flexWrap: 'wrap', marginTop: 16 }}>
          <div>
            <label className="eyebrow" style={{ display: 'block', marginBottom: 4 }}>Start Date</label>
            <input type="date" className="field" value={startDate} onChange={e => setStartDate(e.target.value)} />
          </div>
          <div>
            <label className="eyebrow" style={{ display: 'block', marginBottom: 4 }}>End Date</label>
            <input type="date" className="field" value={endDate} onChange={e => setEndDate(e.target.value)} />
          </div>
          <div>
            <label className="eyebrow" style={{ display: 'block', marginBottom: 4 }}>Status Filter</label>
            <select className="field" value={statusFilter} onChange={e => setStatusFilter(e.target.value)}>
              <option value="ALL">All (Active & Inactive)</option>
              <option value="ACTIVE">Active Only</option>
              <option value="INACTIVE">Inactive Only</option>
            </select>
          </div>
          <div>
            <button className="btn btn-primary" onClick={handleFetch} disabled={loading}>
              {loading ? 'กำลังดึงและคำนวณข้อมูล...' : 'ดึงข้อมูล (Fetch via API)'}
            </button>
          </div>
        </div>

        {errorMsg && (
          <div style={{ padding: 12, background: 'var(--danger-soft)', color: 'var(--danger)', borderRadius: 6, marginTop: 16, fontSize: 13, border: '1px solid var(--danger-ring)' }}>
            <IconWarn size={16} style={{ marginBottom: -3, marginRight: 6 }} />
            {errorMsg}
          </div>
        )}
      </div>

      {!reportData && !loading && !errorMsg && (
        <div style={{ textAlign: 'center', padding: '60px 20px', color: 'var(--ink-3)' }}>
          <IconLayers size={48} style={{ opacity: 0.2, marginBottom: 16 }} />
          <p>เลือกช่วงวันที่ และตั้งค่า Status Filter จากนั้นกดปุ่ม "ดึงข้อมูล"</p>
        </div>
      )}

      {loading && (
        <div style={{ textAlign: 'center', padding: '60px 20px', color: 'var(--ink-2)' }}>
          <div className="spinner" style={{ margin: '0 auto 16px', width: 30, height: 30, border: '3px solid var(--border)', borderTopColor: 'var(--accent)', borderRadius: '50%', animation: 'spin 1s linear infinite' }} />
          <p>กำลังโหลดและประมวลผลข้อมูลจาก Meta API...</p>
        </div>
      )}

      {reportData && !loading && (
        <div className="fade-up" style={{ background: 'var(--surface)', padding: '24px', borderRadius: '12px', border: '1px solid var(--border)' }}>
          
          <div style={{ display: 'flex', gap: 16, borderBottom: '1px solid var(--border)', marginBottom: 24, paddingBottom: 12 }}>
            <button 
              className={`btn ${activeTab === 'campaigns' ? 'btn-primary' : 'btn-ghost'}`} 
              onClick={() => setActiveTab('campaigns')}
            >
              Campaigns ({reportData.campaigns?.length || 0})
            </button>
            <button 
              className={`btn ${activeTab === 'adsets' ? 'btn-primary' : 'btn-ghost'}`} 
              onClick={() => setActiveTab('adsets')}
            >
              Ad Sets ({reportData.adSets?.length || 0})
            </button>
            <button 
              className={`btn ${activeTab === 'ads' ? 'btn-primary' : 'btn-ghost'}`} 
              onClick={() => setActiveTab('ads')}
            >
              Ads ({reportData.ads?.length || 0})
            </button>
          </div>

          {activeTab === 'campaigns' && (
            <div>
              <h3 style={{ marginBottom: 16, color: 'var(--ink)' }}>Performance by Campaign</h3>
              {renderTable(
                ['Campaign Name', 'Spend', 'Impressions', 'Clicks', 'CTR', 'Purchases', 'Sales Value', 'CPA', 'ROAS'],
                getCampaignRows()
              )}
            </div>
          )}

          {activeTab === 'adsets' && (
            <div>
              <h3 style={{ marginBottom: 16, color: 'var(--ink)' }}>Performance by Ad Set</h3>
              {renderTable(
                ['Ad Set Name', 'Campaign Name', 'Spend', 'Impressions', 'Clicks', 'CTR', 'Purchases', 'Sales Value', 'CPA', 'ROAS'],
                getAdSetRows()
              )}
            </div>
          )}

          {activeTab === 'ads' && (
            <div>
              <h3 style={{ marginBottom: 16, color: 'var(--ink)' }}>Performance by Ad</h3>
              {renderTable(
                ['Ad Name', 'Ad Set Name', 'Campaign Name', 'Spend', 'Impressions', 'Clicks', 'CTR', 'Purchases', 'Sales Value', 'CPA', 'ROAS'],
                getAdRows()
              )}
            </div>
          )}

        </div>
      )}
      <style>{`
        .spinner { animation: spin 1s linear infinite; }
        @keyframes spin { 100% { transform: rotate(360deg); } }
      `}</style>
    </div>
  );
}

Object.assign(window, { OverallReportView });
