// Report — export data from General Information / Sales Performance
// by date range, to an Excel (.xlsx) download. Success = toast; failure = modal.

const REPORT_TYPES = [
  { id:'general',  label:'General Information',   file:'GeneralInformation_Report' },
  { id:'sales',    label:'Sales Performance',     file:'SalesPerformance_Report' },
];

// Shared date helper — formats any ISO 'YYYY-MM-DD' / Date string to 'DD/MM/YYYY'.
function fmtDMY(v){
  if (!v) return '';
  const s = String(v).slice(0,10);
  const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s);
  if (m) return `${m[3]}/${m[2]}/${m[1]}`;
  const d = new Date(v);
  if (isNaN(d)) return String(v);
  return `${String(d.getDate()).padStart(2,'0')}/${String(d.getMonth()+1).padStart(2,'0')}/${d.getFullYear()}`;
}
window.fmtDMY = fmtDMY;

// Build { head, rows, count, colStyles, widths } for the chosen report, filtered to
// [from..to] (inclusive, ISO) by Request Date and by Data Status. Zero-value rows dropped.
// `statuses` = array of raw statuses to keep, e.g. ['Submitted','Draft']; null/empty = all.
function buildReport(typeId, from, to, statuses){
  const inRange = (iso) => iso && iso >= from && iso <= to;
  const numRaw = (v) => Number(v)||0;
  const stStatus = (s) => { const v = String(s||'Submitted'); return v==='Submitted' ? 'Submit' : v; };
  const sel = (!statuses || statuses.length===0) ? null : statuses;
  const passStatus = (st) => !sel || sel.includes(String(st||'Submitted'));

  if (typeId === 'sales'){
    const db = (()=>{ try { return JSON.parse(localStorage.getItem('finx_sales_requests_v1')||'{}'); } catch(_){ return {}; } })();
    const data = Object.values(db).filter(r => inRange((r.reqDate||'').slice(0,10)) && passStatus(r.status));
    const head = ['Fiscal Year','Fiscal Month','Date','Sales Channel','Target','Actual','Variance','Achievement','Entry Date','Status'];
    const colStyles = { 0:7, 1:7, 3:7, 4:5, 5:5, 6:5, 7:6, 9:7 };
    const widths = { 4:16, 5:16, 6:16, 7:16 };
    const rows = [];
    data.forEach(r => {
      (r.rows || []).forEach(line => {
        const target = numRaw(line.estimate), actual = numRaw(line.amount);
        if (target === 0 && actual === 0) return;   // skip zero rows
        const variance = actual - target;
        const achievement = target !== 0 ? (actual / target) * 100 : 0;
        rows.push([
          r.fy||'', r.fm||'', fmtDMY(line.date), line.channel||r.channel||'',
          target, actual, variance, achievement,
          fmtDMY(line.entryDate), stStatus(r.status)
        ]);
      });
    });
    return { head, rows, count: rows.length, colStyles, widths };
  }

  if (typeId === 'general'){
    const db = (()=>{ try { return JSON.parse(localStorage.getItem('finx_expense_requests_v1')||'{}'); } catch(_){ return {}; } })();
    const data = Object.values(db).filter(r => inRange((r.reqDate||'').slice(0,10)) && passStatus(r.status));
    const head = ['Fiscal Year','Fiscal Month','Date','Company Name','Expense Type','Description','Estimate','Actual','Variance','Cost Variance',
      'Accounts Payable','Status','Entry Date'];
    const colStyles = { 0:7, 1:7, 6:5, 7:5, 8:5, 9:6, 11:7 };
    const widths = { 6:16, 7:16, 8:16, 9:16 };
    const rows = [];
    data.forEach(r => {
      (r.rows || []).forEach(line => {
        const est = numRaw(line.estimate), act = numRaw(line.amount);
        if (est === 0 && act === 0) return;   // skip zero rows
        const variance = est - act;
        const costVar = est !== 0 ? (variance / est) * 100 : 0;
        rows.push([
          r.fy||'', r.fm||'', fmtDMY(line.date), r.company||'', line.expenseGroup||'', line.accountName||'',
          est, act, variance, costVar,
          line.payable||'', stStatus(r.status), fmtDMY(line.entryDate)
        ]);
      });
    });
    return { head, rows, count: rows.length, colStyles, widths };
  }
}

// Segmented single-select for the Data Status filter — same .seg tabs as the Approve queue.
function StatusSegmented({ value, onChange, options, counts }){
  return (
    <div className="seg" style={{display:'grid',gridTemplateColumns:`repeat(${options.length},minmax(0,1fr))`,width:'max-content'}}>
      {options.map(o => {
        const active = value === o.key;
        const n = counts ? counts[o.key] : null;
        return (
          <button key={o.key} type="button" onClick={()=>onChange(o.key)}
            className={active?'on':''} style={{minWidth:78,textAlign:'center',...(active?{color:o.ink||'#1f2a8e'}:{})}}>
            {o.label}{n!=null && <span style={{opacity:.6}}> ({n})</span>}
          </button>
        );
      })}
    </div>
  );
}

function ReportView(){
  const clock = useSystemClock();
  const [type, setType] = useState('');
  const [from, setFrom] = useState('');
  const [to, setTo] = useState('');
  // Data Status filter — single select: all / Submitted / Draft.
  const STATUS_OPTS = [
    { key:'all',       label:'All Status', ink:'#a16207' },
    { key:'Submitted', label:'Submit', ink:'#15803d' },
    { key:'Draft',     label:'Draft',  ink:'#b91c1c' },
  ];
  const [statusMode, setStatusMode] = useState('all');
  const exportingRef = React.useRef(false);   // guard against double-click Export
  const rawStatuses = statusMode === 'all' ? ['Submitted','Draft'] : [statusMode];
  const statusLabel = statusMode === 'all' ? 'All status' : (statusMode === 'Submitted' ? 'Submit' : 'Draft');

  // Row counts per status for the Status tabs — only once a type + full date range is chosen.
  const statusCounts = React.useMemo(()=>{
    if (!type || !from || !to || from > to) return null;
    const n = (st)=>{ try { return buildReport(type, from, to, st).count; } catch(_){ return 0; } };
    return { all: n(['Submitted','Draft']), Submitted: n(['Submitted']), Draft: n(['Draft']) };
  }, [type, from, to]);

  const reportMeta = REPORT_TYPES.find(t => t.id === type);

  const successToast = (filename, count) => {
    window.toast(`${count} รายการ · ${filename}`, {tone:'success', title:'ดึงข้อมูล Report สำเร็จ', ttl:5000});
  };

  const failModal = (msg) => window.openModal({
    title:'ดึงข้อมูลไม่สำเร็จ', size:'xs',
    message: (
      <div style={{textAlign:'center',padding:'4px 0'}}>
        <div style={{width:52,height:52,margin:'0 auto 12px',borderRadius:'50%',background:'linear-gradient(135deg,#fb7185,#e11d48)',display:'flex',alignItems:'center',justifyContent:'center',boxShadow:'0 0 0 6px rgba(244,63,94,.12), 0 6px 18px rgba(244,63,94,.45)'}}>
          <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
        </div>
        <div style={{fontWeight:700,fontSize:15,color:'var(--ink)',marginBottom:8}}>ดึงข้อมูลไม่สำเร็จ</div>
        <div style={{padding:'10px 14px',background:'#fef2f2',borderRadius:10,border:'1px solid #fecaca',fontSize:12.5,color:'#991b1b',textAlign:'left',lineHeight:1.55}}>
          <div style={{display:'flex',gap:8,alignItems:'flex-start'}}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#dc2626" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{flexShrink:0,marginTop:1}}><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
            <span>{msg}</span>
          </div>
        </div>
      </div>
    ),
    actions:[ { label:'Close', kind:'primary' } ]
  });

  const onExport = () => {
    if (!type){ failModal('กรุณาเลือก Report Type ก่อนดึงข้อมูล'); return; }
    if (!from || !to){ failModal('กรุณาเลือกช่วงวันที่ Start Date และ End Date'); return; }
    if (from > to){ failModal('Start Date ต้องไม่มากกว่า End Date'); return; }
    let result;
    try {
      result = buildReport(type, from, to, rawStatuses);
    } catch(err){
      failModal('เกิดข้อผิดพลาด: ' + (err.message || String(err)));
      return;
    }
    if (!result.count){
      failModal(`ไม่พบข้อมูล "${reportMeta.label}" ในช่วงวันที่ที่เลือก`);
      return;
    }
    const filename = `${reportMeta.file}_${from}_to_${to}.xlsx`;
    if (exportingRef.current) return;   // guard against double-click
    exportingRef.current = true;
    window.showLoading('กำลังสร้างไฟล์ Excel…');
    setTimeout(()=>{ try {
      window.exportXlsx(filename, result.head, result.rows, { sheetName: reportMeta.label, colStyles: result.colStyles, widths: result.widths });
      // Show success only after the file has been saved, then clear all fields.
      successToast(filename, result.count);
      setType(''); setFrom(''); setTo(''); setStatusMode('all');
    } finally { window.hideLoading(); exportingRef.current = false; } }, 450);
  };

  const onReset = () => { setType(''); setFrom(''); setTo(''); setStatusMode('all'); window.toast('ล้างค่าการตั้งค่า Report แล้ว'); };

  // Selecting a new Report Type always clears the date range.
  const onTypeChange = (e) => { setType(e.target.value); setFrom(''); setTo(''); };

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Reported</div>
          <div className="page-sub">ดึงข้อมูลและส่งออกรายงานตามช่วงเวลา</div>
        </div>
      </div>

      <div className="card" style={{padding:'22px 24px',maxWidth:760}}>
        <div style={{fontWeight:700,fontSize:14,marginBottom:4}}>Export Report</div>
        <div style={{fontSize:12.5,color:'var(--muted)',marginBottom:20}}>เลือกประเภทข้อมูลและช่วงวันที่ที่ต้องการดึง · ระบบจะส่งออกเป็นไฟล์ Excel (.xlsx)</div>

        <div className="field" style={{marginBottom:16}}>
          <label>Report Type <span className="req">*</span></label>
          <select className="select" value={type} onChange={onTypeChange}>
            <option value="">— เลือกประเภทข้อมูล —</option>
            {REPORT_TYPES.map(t => <option key={t.id} value={t.id}>{t.label}</option>)}
          </select>
        </div>

        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:16}}>
          <div className="field">
            <label>Start Date <span className="req">*</span></label>
            <div className="dateinput">
              <I.Cal size={14} stroke="#7b87a8"/>
              <input type="date" value={from} max={to||undefined} onChange={e=>setFrom(e.target.value)}/>
            </div>
          </div>
          <div className="field">
            <label>End Date <span className="req">*</span></label>
            <div className="dateinput">
              <I.Cal size={14} stroke="#7b87a8"/>
              <input type="date" value={to} min={from||undefined} onChange={e=>setTo(e.target.value)}/>
            </div>
          </div>
        </div>

        <div className="field" style={{marginTop:16}}>
          <label>Status</label>
          <div style={{marginTop:2}}>
            <StatusSegmented value={statusMode} onChange={setStatusMode} options={STATUS_OPTS} counts={statusCounts}/>
          </div>
        </div>

        {type && from && to && (
          <div style={{marginTop:20,padding:'14px 18px',background:'linear-gradient(135deg,#f7f8fc,#fff)',border:'1px solid var(--line)',borderRadius:12,display:'flex',justifyContent:'space-between',alignItems:'center',gap:14}}>
            <div>
              <div style={{fontSize:11,letterSpacing:'.08em',textTransform:'uppercase',color:'var(--muted)'}}>พร้อมส่งออก</div>
              <div style={{fontWeight:700,fontSize:14,marginTop:2}}>{reportMeta.label}</div>
              <div className="mono" style={{fontSize:12,color:'var(--muted)',marginTop:2}}>{fmtDMY(from).replace(/\//g,'-')} → {fmtDMY(to).replace(/\//g,'-')} · {statusLabel}</div>
            </div>
            <div style={{textAlign:'right'}}>
              <div style={{fontSize:11,color:'var(--muted)'}}>รายการในช่วงนี้</div>
              <div className="mono" style={{fontSize:24,fontWeight:800,color:'#1f2a8e'}}>{buildReport(type, from, to, rawStatuses).count}</div>
            </div>
          </div>
        )}

        <div style={{marginTop:22,display:'flex',justifyContent:'flex-end',gap:10}}>
          <button className="btn" onClick={onReset}><I.Reset size={14}/> Reset</button>
          <button className="btn primary" onClick={onExport}><I.Download size={14}/> Export Report</button>
        </div>
      </div>

      <div style={{marginTop:18,display:'flex',justifyContent:'flex-start',color:'var(--muted)',fontSize:12,fontStyle:'italic'}}>
        <span>{clock}</span>
      </div>
    </div>
  );
}

window.ReportView = ReportView;
