'use client';
import { useEffect, useState, useCallback } from 'react';
import { adminService } from '@/services/admin.service';
import type { ReportInfo, PaginationMeta } from '@/types/admin.types';

export default function AdminReportsPage() {
  const [reports, setReports] = useState<ReportInfo[]>([]);
  const [meta, setMeta] = useState<PaginationMeta | null>(null);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [typeFilter, setTypeFilter] = useState('');
  const [showGenerate, setShowGenerate] = useState(false);
  const [form, setForm] = useState({ type: 'DAILY', format: 'CSV', dateFrom: '', dateTo: '' });
  const [actionMsg, setActionMsg] = useState('');

  const fetchReports = useCallback(async () => {
    setLoading(true);
    try {
      const params: any = { page, limit: 20 };
      if (typeFilter) params.type = typeFilter;
      const res = await adminService.listReports(params);
      setReports(res.data); setMeta(res.meta);
    } catch (e) { console.error(e); }
    finally { setLoading(false); }
  }, [page, typeFilter]);

  useEffect(() => { fetchReports(); }, [fetchReports]);

  const handleGenerate = async () => {
    try {
      await adminService.generateReport(form);
      setActionMsg('Report generated'); setShowGenerate(false); fetchReports();
    } catch (e: any) { setActionMsg(e?.response?.data?.message || 'Error'); }
  };

  const handleExport = async (reportId: string) => {
    try {
      const csv = await adminService.exportReport(reportId);
      const blob = new Blob([csv], { type: 'text/csv' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a'); a.href = url; a.download = `report-${reportId}.csv`; a.click();
      URL.revokeObjectURL(url);
    } catch (e) { console.error(e); }
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Reports</h1>
          <p className="mt-1 text-sm text-white/50">Generate and export platform reports</p>
        </div>
        <button onClick={() => setShowGenerate(!showGenerate)} className="rounded-lg bg-indigo-500/20 px-4 py-2 text-xs font-medium text-indigo-400 hover:bg-indigo-500/30">
          {showGenerate ? 'Cancel' : '+ Generate Report'}
        </button>
      </div>

      {actionMsg && <div className="rounded-lg bg-blue-500/10 p-3 text-sm text-blue-400">{actionMsg}</div>}

      {showGenerate && (
        <div className="rounded-xl border border-white/10 bg-white/[0.02] p-4 space-y-3">
          <div className="flex flex-wrap gap-3">
            <select value={form.type} onChange={(e) => setForm({ ...form, type: e.target.value })} className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-xs text-white">
              <option value="DAILY">Daily</option><option value="WEEKLY">Weekly</option><option value="MONTHLY">Monthly</option>
              <option value="TRADE">Trade</option><option value="REVENUE">Revenue</option><option value="COMMISSION">Commission</option>
              <option value="WALLET">Wallet</option><option value="USER">User</option>
            </select>
            <select value={form.format} onChange={(e) => setForm({ ...form, format: e.target.value })} className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-xs text-white">
              <option value="CSV">CSV</option><option value="EXCEL">Excel</option><option value="JSON">JSON</option>
            </select>
            <input type="date" value={form.dateFrom} onChange={(e) => setForm({ ...form, dateFrom: e.target.value })} className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-xs text-white" />
            <input type="date" value={form.dateTo} onChange={(e) => setForm({ ...form, dateTo: e.target.value })} className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-xs text-white" />
            <button onClick={handleGenerate} className="rounded-lg bg-indigo-500/20 px-4 py-2 text-xs font-medium text-indigo-400 hover:bg-indigo-500/30">Generate</button>
          </div>
        </div>
      )}

      <div className="flex flex-wrap gap-3">
        <select value={typeFilter} onChange={(e) => { setTypeFilter(e.target.value); setPage(1); }} className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-xs text-white">
          <option value="">All Types</option>
          <option value="DAILY">Daily</option><option value="WEEKLY">Weekly</option><option value="MONTHLY">Monthly</option>
          <option value="TRADE">Trade</option><option value="REVENUE">Revenue</option><option value="COMMISSION">Commission</option>
          <option value="WALLET">Wallet</option><option value="USER">User</option>
        </select>
      </div>

      <div className="overflow-x-auto rounded-xl border border-white/5">
        <table className="w-full text-left text-sm">
          <thead className="border-b border-white/5 bg-white/[0.02]">
            <tr>
              <th className="px-4 py-3 text-slate-400">Type</th>
              <th className="px-4 py-3 text-slate-400">Format</th>
              <th className="px-4 py-3 text-slate-400">Date Range</th>
              <th className="px-4 py-3 text-slate-400">Generated</th>
              <th className="px-4 py-3 text-slate-400">Actions</th>
            </tr>
          </thead>
          <tbody>
            {loading ? <tr><td colSpan={5} className="px-4 py-8 text-center text-slate-500">Loading...</td></tr>
            : reports.length === 0 ? <tr><td colSpan={5} className="px-4 py-8 text-center text-slate-500">No reports</td></tr>
            : reports.map((r) => (
              <tr key={r.id} className="border-b border-white/5 hover:bg-white/[0.02]">
                <td className="px-4 py-3 font-medium text-white">{r.type}</td>
                <td className="px-4 py-3 text-slate-300">{r.format}</td>
                <td className="px-4 py-3 text-slate-400">
                  {r.dateFrom ? new Date(r.dateFrom).toLocaleDateString() : '-'} to {r.dateTo ? new Date(r.dateTo).toLocaleDateString() : '-'}
                </td>
                <td className="px-4 py-3 text-slate-400">{new Date(r.createdAt).toLocaleString()}</td>
                <td className="px-4 py-3">
                  <button onClick={() => handleExport(r.id)} className="rounded-lg bg-emerald-500/10 px-3 py-1.5 text-xs text-emerald-400 hover:bg-emerald-500/20">Export CSV</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {meta && (
        <div className="flex items-center justify-between">
          <p className="text-xs text-slate-500">Page {meta.page} of {meta.totalPages}</p>
          <div className="flex gap-2">
            <button disabled={page <= 1} onClick={() => setPage(page - 1)} className="rounded-lg bg-white/5 px-3 py-1.5 text-xs text-white disabled:opacity-30 hover:bg-white/10">Previous</button>
            <button disabled={page >= meta.totalPages} onClick={() => setPage(page + 1)} className="rounded-lg bg-white/5 px-3 py-1.5 text-xs text-white disabled:opacity-30 hover:bg-white/10">Next</button>
          </div>
        </div>
      )}
    </div>
  );
}
