'use client';

import { useState } from 'react';
import { FileBarChart } from 'lucide-react';
import { useAuth } from '@/lib/auth-context';
import { useToast } from '@/lib/toast';

async function downloadCsv(path: string, accessToken: string, appSecretProof: string, fallbackName: string) {
  const API_BASE = process.env.NEXT_PUBLIC_API_BASE_URL;
  const res = await fetch(`${API_BASE}${path}`, {
    headers: { Authorization: `Bearer ${accessToken}`, 'X-App-Secret-Proof': appSecretProof },
  });
  if (!res.ok) throw new Error('EXPORT_FAILED');
  const blob = await res.blob();
  const disposition = res.headers.get('Content-Disposition') || '';
  const match = disposition.match(/filename="([^"]+)"/);
  const filename = match?.[1] || fallbackName;
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url; a.download = filename;
  document.body.appendChild(a); a.click(); a.remove();
  URL.revokeObjectURL(url);
}

export default function ReportsPage() {
  const { accessToken, appSecretProof } = useAuth();
  const { show } = useToast();
  const [from, setFrom] = useState('');
  const [to, setTo] = useState('');
  const [downloading, setDownloading] = useState<string | null>(null);

  async function run(key: string, path: string, fallbackName: string) {
    if (!accessToken || !appSecretProof) return;
    setDownloading(key);
    try {
      const qs = key === 'inventory' ? '' : `?${from ? `from=${from}&` : ''}${to ? `to=${to}` : ''}`;
      await downloadCsv(`${path}${qs}`, accessToken, appSecretProof, fallbackName);
      show('success', 'Download started.');
    } catch { show('error', 'Could not generate that export.'); }
    finally { setDownloading(null); }
  }

  const reports = [
    { key: 'sales', title: 'Sales Report', description: 'Every invoice raised in the period — client, subtotal, VAT, total, status, payment method.', path: '/admin/reports/sales.csv', filename: 'sales-report.csv', dated: true },
    { key: 'vat', title: 'VAT / Tax Summary', description: 'Paid invoices only, shaped for TRA filing — one row per invoice plus a totals row.', path: '/admin/reports/vat-summary.csv', filename: 'vat-summary.csv', dated: true },
    { key: 'inventory', title: 'Inventory Valuation', description: 'Current stock quantity × unit price for every product — a point-in-time snapshot, not a date range.', path: '/admin/reports/inventory-valuation.csv', filename: 'inventory-valuation.csv', dated: false },
  ];

  return (
    <div className="space-y-4">
      <h1 className="text-xl font-bold">Reports &amp; Exports Center &bull; admin.lussavara.co.tz</h1>
      <p className="text-xs text-gray-500">CSV opens directly in Excel — no screenshotting individual pages for your accountant or TRA filing.</p>

      <div className="bg-white border border-brand-border rounded-xl p-4 flex items-end gap-3 text-xs">
        <div><label className="text-[10px] text-gray-400 uppercase">From</label><input type="date" value={from} onChange={(e) => setFrom(e.target.value)} className="border border-brand-border rounded-lg px-2 py-1.5" /></div>
        <div><label className="text-[10px] text-gray-400 uppercase">To</label><input type="date" value={to} onChange={(e) => setTo(e.target.value)} className="border border-brand-border rounded-lg px-2 py-1.5" /></div>
        <p className="text-gray-400 pb-1.5">Applies to Sales Report and VAT Summary (defaults to the last 30 days if left blank).</p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        {reports.map((r) => (
          <div key={r.key} className="bg-white border border-brand-border rounded-xl p-4 flex flex-col">
            <FileBarChart size={20} className="text-brand-red mb-2" />
            <p className="text-sm font-semibold">{r.title}</p>
            <p className="text-xs text-gray-500 flex-1 mt-1">{r.description}</p>
            <button
              onClick={() => run(r.key, r.path, r.filename)}
              disabled={downloading === r.key}
              className="mt-3 bg-brand-charcoal text-white text-xs py-2 rounded-lg disabled:opacity-60"
            >
              {downloading === r.key ? 'Preparing…' : 'Download CSV'}
            </button>
          </div>
        ))}
      </div>
    </div>
  );
}
