'use client';

import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { Users, Wifi, DollarSign, AlertTriangle, Ticket, ClipboardList } from 'lucide-react';

interface DashboardSummary {
  subscribers: { total: number; active: number; pending: number; suspended: number };
  billing: { unpaidInvoices: number; overdueInvoices: number };
  support: { openTickets: number; inProgressTickets: number };
  tasks: { pending: number };
  revenue: { thisMonth: number; lastMonth: number; trend: number };
  leads: { total: number; new: number };
}

function KpiCard({
  label,
  value,
  sub,
  icon: Icon,
  color,
  isLoading,
}: {
  label: string;
  value: string;
  sub?: string;
  icon: React.ElementType;
  color: string;
  isLoading: boolean;
}) {
  return (
    <Card className="border shadow-sm">
      <CardHeader className="flex flex-row items-center justify-between pb-2">
        <CardTitle className="text-sm font-medium text-slate-500">{label}</CardTitle>
        <div
          className="w-9 h-9 rounded-lg flex items-center justify-center"
          style={{ backgroundColor: color + '1A' }}
        >
          <Icon size={18} style={{ color }} />
        </div>
      </CardHeader>
      <CardContent>
        {isLoading ? (
          <Skeleton className="h-8 w-24" />
        ) : (
          <>
            <p className="text-2xl font-bold text-slate-800">{value}</p>
            {sub && <p className="text-xs text-slate-500 mt-1">{sub}</p>}
          </>
        )}
      </CardContent>
    </Card>
  );
}

export default function DashboardPage() {
  const { data, isLoading, error } = useQuery<DashboardSummary>({
    queryKey: ['dashboard', 'summary'],
    queryFn: async () => {
      const res = await api.get('/api/v1/dashboard/summary');
      return res.data;
    },
  });

  const fmt = (n: number) => n?.toLocaleString() ?? '—';
  const peso = (n: number) =>
    '₱' + (n ?? 0).toLocaleString('en-PH', { minimumFractionDigits: 2 });

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-slate-800">Dashboard</h1>
        <p className="text-slate-500 text-sm mt-1">Overview of your ISP operations</p>
      </div>

      {error && (
        <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-red-600 text-sm">
          Failed to load dashboard data.
        </div>
      )}

      {/* KPI Row 1 */}
      <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4 mb-4">
        <KpiCard
          label="Active Subscribers"
          value={fmt(data?.subscribers?.active ?? 0)}
          sub={`${fmt(data?.subscribers?.total ?? 0)} total · ${fmt(data?.subscribers?.pending ?? 0)} pending`}
          icon={Wifi}
          color="#059669"
          isLoading={isLoading}
        />
        <KpiCard
          label="Revenue This Month"
          value={peso(data?.revenue?.thisMonth ?? 0)}
          sub={`Last month: ${peso(data?.revenue?.lastMonth ?? 0)}`}
          icon={DollarSign}
          color="#0891B2"
          isLoading={isLoading}
        />
        <KpiCard
          label="Overdue Invoices"
          value={fmt(data?.billing?.overdueInvoices ?? 0)}
          sub={`${fmt(data?.billing?.unpaidInvoices ?? 0)} unpaid total`}
          icon={AlertTriangle}
          color="#DC2626"
          isLoading={isLoading}
        />
      </div>

      {/* KPI Row 2 */}
      <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4 mb-8">
        <KpiCard
          label="Open Tickets"
          value={fmt(data?.support?.openTickets ?? 0)}
          sub={`${fmt(data?.support?.inProgressTickets ?? 0)} in progress`}
          icon={Ticket}
          color="#7C3AED"
          isLoading={isLoading}
        />
        <KpiCard
          label="Pending Tasks"
          value={fmt(data?.tasks?.pending ?? 0)}
          sub="Manual tasks awaiting action"
          icon={ClipboardList}
          color="#D97706"
          isLoading={isLoading}
        />
        <KpiCard
          label="Total Clients"
          value={fmt(data?.subscribers?.total ?? 0)}
          sub={`${fmt(data?.leads?.new ?? 0)} new leads`}
          icon={Users}
          color="#0F172A"
          isLoading={isLoading}
        />
      </div>

      {/* Quick stats */}
      <Card className="border shadow-sm">
        <CardHeader>
          <CardTitle className="text-base font-semibold text-slate-700">Subscriber Breakdown</CardTitle>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="space-y-2">
              <Skeleton className="h-4 w-full" />
              <Skeleton className="h-4 w-3/4" />
            </div>
          ) : (
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
              {[
                { label: 'Active', value: data?.subscribers?.active ?? 0, color: '#059669' },
                { label: 'Pending', value: data?.subscribers?.pending ?? 0, color: '#D97706' },
                { label: 'Suspended', value: data?.subscribers?.suspended ?? 0, color: '#DC2626' },
                { label: 'Total', value: data?.subscribers?.total ?? 0, color: '#0891B2' },
              ].map((item) => (
                <div key={item.label} className="text-center p-3 rounded-lg bg-slate-50">
                  <p className="text-2xl font-bold" style={{ color: item.color }}>
                    {item.value}
                  </p>
                  <p className="text-xs text-slate-500 mt-1">{item.label}</p>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
