'use client';
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { DataTable } from '@/components/data-table';
import { useDialog } from '@/components/dialog';

const FORMATS = [
  { v: 'xlsx', label: 'Excel' },
  { v: 'csv', label: 'CSV' },
  { v: 'pdf', label: 'PDF' },
];

function ExportCard({ title, count, base, path }: { title: string; count: any; base: string; path: string }) {
  const [busy, setBusy] = useState('');
  const { notify } = useDialog();
  const go = async (fmt: string) => {
    setBusy(fmt);
    try { await api.download(`${path}?format=${fmt}`, `${base}.${fmt}`); }
    catch (e: any) { notify(e.message, { tone: 'error' }); }
    finally { setBusy(''); }
  };
  return (
    <div className="card space-y-2">
      <h2 className="font-medium">{title}</h2>
      <p className="text-sm text-slate-500">Matching records: {count ?? '—'} (respects your role/filters)</p>
      <div className="flex gap-2">
        {FORMATS.map(f => (
          <button key={f.v} className="btn-ghost text-sm" disabled={!!busy} onClick={() => go(f.v)}>
            {busy === f.v ? '…' : f.label}
          </button>
        ))}
      </div>
    </div>
  );
}

export default function ReportsPage() {
  const a = useQuery({ queryKey: ['rep-a'], queryFn: () => api.get('/api/v1/actions?limit=1') });
  const s = useQuery({ queryKey: ['rep-s'], queryFn: () => api.get('/api/v1/samples?limit=1') });
  const t = useQuery({ queryKey: ['rep-t'], queryFn: () => api.get('/api/v1/schedules?limit=1') });
  return (
    <div className="space-y-3">
      <h1 className="page-title">Reports</h1>
      <p className="text-sm text-slate-500">Server-generated exports with your current permissions applied (employees only see assigned work).</p>
      <div className="grid md:grid-cols-2 gap-3">
        <ExportCard title="Deviation Report" count={a.data?.total} base="deviations" path="/api/v1/reports/actions" />
        <ExportCard title="QC Sample Report" count={s.data?.total} base="samples" path="/api/v1/reports/samples" />
        <ExportCard title="Lab Schedule Report" count={t.data?.total} base="testing-schedules" path="/api/v1/reports/schedules" />
      </div>
      <SLACard />
    </div>
  );
}

function SLACard() {
  const { notify } = useDialog();
  const [level, setLevel] = useState('1');
  const sum = useQuery({ queryKey: ['sla-sum', level], queryFn: () => api.get(`/api/v1/reports/sla/summary?level=${level}`) });
  const [busy, setBusy] = useState('');
  const go = async (fmt: string) => {
    setBusy(fmt);
    try { await api.download(`/api/v1/reports/sla?level=${level}&format=${fmt}`, `sla-breaches-L${level}+.${fmt}`); }
    catch (e: any) { notify(e.message, { tone: 'error' }); }
    finally { setBusy(''); }
  };
  return (
    <div className="card space-y-2">
      <div className="flex flex-wrap gap-2 items-center">
        <h2 className="font-medium mr-auto">SLA Breach Report (escalation levels)</h2>
        <select className="input max-w-44 text-sm" value={level} onChange={(e) => setLevel(e.target.value)}>
          <option value="1">Level 1+ (all breaches)</option>
          <option value="2">Level 2+ (management)</option>
          <option value="3">Level 3 (critical)</option>
        </select>
      </div>
      <div className="grid grid-cols-3 gap-2">
        {(sum.data?.byLevel ?? []).map((b: any) => (
          <div key={b.level} className="border rounded-lg p-2 text-center">
            <p className="text-xs text-slate-500">Escalation L{b.level}</p>
            <p className="text-xl font-semibold">{b.deviations + b.capas}</p>
            <p className="text-[11px] text-slate-500">{b.deviations} deviations · {b.capas} capas · avg {b.avg_days_open}d open</p>
          </div>
        ))}
      </div>
      <DataTable
        caption="SLA breaches by priority"
        rows={sum.data?.byPriority ?? []}
        keyOf={(b: any) => b.priority}
        empty={sum.isLoading ? 'Loading…' : 'No breaches — all within SLA.'}
        columns={[
          { header: 'Priority', render: (b: any) => <span className="font-medium">{b.priority}</span> },
          { header: 'SLA', render: (b: any) => <span className="whitespace-nowrap">{b.sla_days}d</span> },
          { header: 'Breached', render: (b: any) => <span className={b.breached ? 'text-red-700 font-semibold' : ''}>{b.breached}</span> },
          { header: 'Deviations', render: (b: any) => b.deviations },
          { header: 'CAPAs', render: (b: any) => b.capas },
          { header: 'Avg open', render: (b: any) => <span className="whitespace-nowrap">{b.avg_days_open}d</span> },
        ]}
      />
      <div className="flex gap-2">
        {['xlsx', 'csv', 'pdf'].map((f) => (
          <button key={f} className="btn-ghost text-sm" disabled={!!busy} onClick={() => go(f)}>
            {busy === f ? '…' : f.toUpperCase()}
          </button>
        ))}
      </div>
    </div>
  );
}
