'use client';

import { useEffect, useState } from 'react';
import { DashboardLayout } from '@/components/layout/DashboardLayout';
import { Card, CardContent } from '@/components/ui/card';
import { api } from '@/lib/api';
import {
  AdminError,
  AdminLoading,
  AdminTable,
  AdminTd,
  AdminTh,
  PaginationBar,
  PaginationMeta,
  formatDate,
} from '@/components/admin/admin-ui';

interface DashboardStats {
  totalUsers: number;
  totalWorkers: number;
  totalCustomers: number;
  totalJobs: number;
  openJobs: number;
  completedJobs: number;
  pendingVerifications: number;
  totalReviews: number;
}

interface QRScan {
  id: string;
  slug: string;
  source: string;
  createdAt: string;
  category: { name: string; slug: string } | null;
}

export default function AdminReportsPage() {
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [scans, setScans] = useState<QRScan[]>([]);
  const [bySource, setBySource] = useState<{ source: string; _count: number }[]>([]);
  const [meta, setMeta] = useState<PaginationMeta>({ page: 1, limit: 20, total: 0, totalPages: 0 });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  async function loadQR(page = 1) {
    const res = await api<{
      data: { scans: QRScan[]; bySource: { source: string; _count: number }[] };
      meta: PaginationMeta;
    }>(`/analytics/qr?page=${page}&limit=20`);
    setScans(res.data.scans);
    setBySource(res.data.bySource);
    setMeta(res.meta!);
  }

  useEffect(() => {
    setLoading(true);
    setError('');
    Promise.all([
      api<{ data: { stats: DashboardStats } }>('/analytics/dashboard'),
      loadQR(1),
    ])
      .then(([dash]) => setStats(dash.data.stats))
      .catch((e) => setError(e instanceof Error ? e.message : 'Failed to load reports'))
      .finally(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <DashboardLayout role="admin" title="Reports">
        <AdminLoading />
      </DashboardLayout>
    );
  }

  if (error) {
    return (
      <DashboardLayout role="admin" title="Reports">
        <AdminError message={error} />
      </DashboardLayout>
    );
  }

  return (
    <DashboardLayout role="admin" title="Reports">
      <h2 className="text-lg font-bold mb-4">Platform Overview</h2>
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        {[
          { label: 'Total Users', value: stats?.totalUsers },
          { label: 'Customers', value: stats?.totalCustomers },
          { label: 'Workers', value: stats?.totalWorkers },
          { label: 'Total Jobs', value: stats?.totalJobs },
          { label: 'Open Jobs', value: stats?.openJobs },
          { label: 'Completed Jobs', value: stats?.completedJobs },
          { label: 'Pending Verifications', value: stats?.pendingVerifications },
          { label: 'Total Reviews', value: stats?.totalReviews },
        ].map((s) => (
          <Card key={s.label}>
            <CardContent className="p-4">
              <p className="text-2xl font-bold text-slate-900">{s.value ?? 0}</p>
              <p className="text-xs text-muted">{s.label}</p>
            </CardContent>
          </Card>
        ))}
      </div>

      <h2 className="text-lg font-bold mb-4">QR Code Scans by Source</h2>
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-8">
        {bySource.map((row) => (
          <Card key={row.source}>
            <CardContent className="p-4 text-center">
              <p className="text-xl font-bold">{row._count}</p>
              <p className="text-xs text-muted capitalize">{row.source || 'direct'}</p>
            </CardContent>
          </Card>
        ))}
        {bySource.length === 0 && (
          <Card className="col-span-full">
            <CardContent className="p-6 text-center text-muted">No QR scans recorded yet.</CardContent>
          </Card>
        )}
      </div>

      <h2 className="text-lg font-bold mb-4">Recent QR Scans</h2>
      {scans.length === 0 ? (
        <Card>
          <CardContent className="p-6 text-center text-muted">No scan history.</CardContent>
        </Card>
      ) : (
        <>
          <AdminTable>
            <thead>
              <tr>
                <AdminTh>Slug</AdminTh>
                <AdminTh>Category</AdminTh>
                <AdminTh>Source</AdminTh>
                <AdminTh>Date</AdminTh>
              </tr>
            </thead>
            <tbody>
              {scans.map((scan) => (
                <tr key={scan.id}>
                  <AdminTd>
                    <code className="text-xs">{scan.slug}</code>
                  </AdminTd>
                  <AdminTd>{scan.category?.name || '—'}</AdminTd>
                  <AdminTd className="capitalize">{scan.source || 'direct'}</AdminTd>
                  <AdminTd>{formatDate(scan.createdAt)}</AdminTd>
                </tr>
              ))}
            </tbody>
          </AdminTable>
          <PaginationBar meta={meta} onPageChange={loadQR} />
        </>
      )}
    </DashboardLayout>
  );
}
