"use client";
export const dynamic = "force-dynamic";



import { useQuery, useMutation } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { Users, Wifi, FileText, DollarSign, Ticket, TrendingUp, Database, RefreshCw, AlertCircle } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
import { Button } from "@/components/ui/Button";
import { Badge } from "@/components/ui/Badge";
import { formatCurrency, formatDateTime } from "@/lib/utils";
import { useAuthStore } from "@/lib/auth-store";
import { toast } from "sonner";
import api from "@/lib/api";
import type { DashboardSummary, PaginatedResponse, Ticket as TicketType } from "@/types";
import {
  LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend,
} from "recharts";

interface KpiCardProps {
  title: string;
  value: string | number;
  icon: React.ComponentType<{ className?: string }>;
  color: string;
  subtitle?: string;
  href?: string;
}

function KpiCard({ title, value, icon: Icon, color, subtitle, href }: KpiCardProps) {
  const router = useRouter();
  return (
    <Card
      className={href ? "cursor-pointer hover:shadow-md transition-shadow" : ""}
      onClick={href ? () => router.push(href) : undefined}
    >
      <CardContent className="flex items-center gap-4 py-5">
        <div className={`flex h-12 w-12 items-center justify-center rounded-xl ${color} shrink-0`}>
          <Icon className="h-6 w-6 text-white" />
        </div>
        <div className="min-w-0">
          <p className="text-sm font-medium text-gray-500 truncate">{title}</p>
          <p className="text-2xl font-bold text-gray-900">{value}</p>
          {subtitle && <p className="text-xs text-gray-400 mt-0.5">{subtitle}</p>}
        </div>
        {href && <div className="ml-auto text-gray-300 text-xs">→</div>}
      </CardContent>
    </Card>
  );
}

function KpiSkeleton() {
  return (
    <Card>
      <CardContent className="flex items-center gap-4 py-5">
        <div className="h-12 w-12 rounded-xl skeleton shrink-0" />
        <div className="flex-1 space-y-2">
          <div className="h-3 skeleton rounded w-24" />
          <div className="h-7 skeleton rounded w-16" />
          <div className="h-2 skeleton rounded w-20" />
        </div>
      </CardContent>
    </Card>
  );
}

function ErrorState({ message, onRetry }: { message: string; onRetry: () => void }) {
  return (
    <div className="flex flex-col items-center justify-center py-12 text-gray-400 gap-3">
      <AlertCircle className="h-10 w-10 text-red-300" />
      <p className="text-sm text-gray-500">{message}</p>
      <Button size="sm" variant="outline" onClick={onRetry}>Retry</Button>
    </div>
  );
}

const priorityVariant: Record<string, "danger" | "warning" | "default" | "muted"> = {
  URGENT: "danger", urgent: "danger",
  HIGH: "warning", high: "warning",
  NORMAL: "default", normal: "default",
  MEDIUM: "default", medium: "default",
  LOW: "muted", low: "muted",
};

function buildChartData(stats: DashboardSummary | undefined) {
  if (!stats) return [];
  const now = new Date();
  const thisMonth = now.toLocaleString("default", { month: "short" });
  const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1).toLocaleString("default", { month: "short" });
  return [
    { month: lastMonth, revenue: stats.revenue.lastMonth },
    { month: thisMonth, revenue: stats.revenue.thisMonth },
  ];
}

export default function DashboardPage() {
  const router = useRouter();
  const user = useAuthStore((s) => s.user);
  const isAdmin = user?.roles?.some(r => r.toLowerCase() === "admin" || r.toLowerCase() === "super_admin");

  const {
    data: stats,
    isLoading: statsLoading,
    isError: statsError,
    refetch: refetchStats,
  } = useQuery<DashboardSummary>({
    queryKey: ["dashboard-summary"],
    queryFn: async () => {
      const res = await api.get<DashboardSummary>("/api/v1/dashboard/summary");
      return res.data;
    },
  });

  const {
    data: ticketsData,
    isLoading: ticketsLoading,
    refetch: refetchTickets,
  } = useQuery<PaginatedResponse<TicketType>>({
    queryKey: ["recent-tickets"],
    queryFn: async () => {
      const res = await api.get<PaginatedResponse<TicketType>>("/api/v1/tickets?page=1&limit=5");
      return res.data;
    },
  });

  const seedMutation = useMutation({
    mutationFn: () => api.post<{ message: string }>("/api/v1/_seed", {}),
    onSuccess: (res) => {
      toast.success(res.data?.message || "Demo data seeded!");
      refetchStats();
      refetchTickets();
    },
    onError: (err: any) => {
      toast.error(err?.response?.data?.message || "Seed failed");
    },
  });

  const recentTickets = ticketsData?.data ?? [];
  const chartData = buildChartData(stats);
  const hasChartData = chartData.some((d) => d.revenue > 0);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Dashboard</h1>
          <p className="text-sm text-gray-500 mt-0.5">Overview of your ISP operations</p>
        </div>
        <div className="flex gap-2 flex-wrap">
          <Button size="sm" variant="outline" onClick={() => { refetchStats(); refetchTickets(); }}>
            <RefreshCw className="h-4 w-4" /> Refresh
          </Button>
          {isAdmin && (
            <Button size="sm" variant="secondary"
              onClick={() => seedMutation.mutate()}
              isLoading={seedMutation.isPending}>
              <Database className="h-4 w-4" /> Seed Demo Data
            </Button>
          )}
          <Button size="sm" data-testid="new-client-btn" onClick={() => router.push("/clients")}>+ New Client</Button>
          <Button size="sm" variant="secondary" onClick={() => router.push("/payments")}>+ Record Payment</Button>
          <Button size="sm" variant="secondary" onClick={() => router.push("/tickets")}>+ New Ticket</Button>
        </div>
      </div>

      {/* KPI Cards */}
      {statsLoading ? (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          {[1,2,3,4].map(i => <KpiSkeleton key={i} />)}
        </div>
      ) : statsError ? (
        <Card><CardContent className="py-2">
          <ErrorState message="Failed to load dashboard stats." onRetry={refetchStats} />
        </CardContent></Card>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          <KpiCard title="Total Clients" value={stats?.subscribers.total ?? 0} icon={Users}
            color="bg-blue-500" subtitle={`${stats?.subscribers.active ?? 0} active`} href="/clients" />
          <KpiCard title="Active Subscriptions" value={stats?.subscribers.active ?? 0} icon={Wifi}
            color="bg-green-500" subtitle={`${stats?.subscribers.suspended ?? 0} suspended`} />
          <KpiCard title="Overdue Invoices" value={stats?.billing.overdueInvoices ?? 0} icon={FileText}
            color="bg-red-500" subtitle={`${stats?.billing.unpaidInvoices ?? 0} unpaid total`} href="/invoices" />
          {isAdmin && (
            <KpiCard title="Monthly Revenue" value={formatCurrency(stats?.revenue.thisMonth ?? 0)}
              icon={DollarSign} color="bg-purple-500"
              subtitle={stats?.revenue.growth != null
                ? `${stats.revenue.growth > 0 ? "+" : ""}${stats.revenue.growth.toFixed(1)}% vs last month`
                : "vs last month"} href="/payments" />
          )}
        </div>
      )}

      {/* Secondary stats */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <Card className="cursor-pointer hover:shadow-md transition-shadow"
          onClick={() => router.push("/tickets")}>
          <CardContent className="flex items-center gap-3 py-4">
            <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-amber-50 shrink-0">
              <Ticket className="h-5 w-5 text-amber-600" />
            </div>
            <div>
              <p className="text-xs text-gray-500">Open Tickets</p>
              <p className="text-xl font-bold text-gray-900">{stats?.support.openTickets ?? 0}</p>
            </div>
          </CardContent>
        </Card>
        <Card className="cursor-pointer hover:shadow-md transition-shadow"
          onClick={() => router.push("/tickets")}>
          <CardContent className="flex items-center gap-3 py-4">
            <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-blue-50 shrink-0">
              <TrendingUp className="h-5 w-5 text-blue-600" />
            </div>
            <div>
              <p className="text-xs text-gray-500">In-Progress Tickets</p>
              <p className="text-xl font-bold text-gray-900">{stats?.support.inProgressTickets ?? 0}</p>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Revenue Chart — admin only */}
      {isAdmin && !statsLoading && (
        <Card>
          <CardHeader>
            <CardTitle>Revenue Overview</CardTitle>
          </CardHeader>
          <CardContent>
            {hasChartData ? (
              <ResponsiveContainer width="100%" height={220}>
                <LineChart data={chartData} margin={{ top: 5, right: 20, left: 0, bottom: 5 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
                  <XAxis dataKey="month" tick={{ fontSize: 12 }} />
                  <YAxis tick={{ fontSize: 12 }} tickFormatter={(v: number) => `₱${(v/1000).toFixed(0)}k`} />
                  <Tooltip formatter={(v) => formatCurrency(Number(v))} />
                  <Legend />
                  <Line type="monotone" dataKey="revenue" stroke="#0891B2"
                    strokeWidth={2} dot={{ r: 4 }} name="Revenue" />
                </LineChart>
              </ResponsiveContainer>
            ) : (
              <div className="flex flex-col items-center justify-center h-32 text-gray-400">
                <TrendingUp className="h-8 w-8 mb-2 opacity-40" />
                <p className="text-sm">Revenue data will appear once payments are recorded.</p>
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* Recent Tickets */}
      <Card>
        <CardHeader>
          <CardTitle>Recent Tickets</CardTitle>
          <Button size="sm" variant="ghost" onClick={() => router.push("/tickets")}>View all →</Button>
        </CardHeader>
        <CardContent className="p-0">
          {ticketsLoading ? (
            <div className="divide-y">
              {[1,2,3].map(i => (
                <div key={i} className="flex items-center gap-4 px-6 py-3">
                  <div className="flex-1 space-y-1.5">
                    <div className="h-3 skeleton rounded w-48" />
                    <div className="h-2 skeleton rounded w-32" />
                  </div>
                  <div className="h-5 skeleton rounded w-16" />
                </div>
              ))}
            </div>
          ) : recentTickets.length === 0 ? (
            <div className="py-10 text-center text-gray-400 text-sm">No tickets yet</div>
          ) : (
            <div className="divide-y divide-gray-50">
              {recentTickets.map((ticket) => (
                <div key={ticket.id}
                  className="flex items-center justify-between px-6 py-3 hover:bg-gray-50 cursor-pointer transition-colors"
                  onClick={() => router.push("/tickets")}>
                  <div>
                    <p className="text-sm font-medium text-gray-800">{ticket.subject}</p>
                    <p className="text-xs text-gray-400 mt-0.5">
                      {ticket.client ? `${ticket.client.firstName} ${ticket.client.lastName}` : "No client"}
                      {" • "}{formatDateTime(ticket.createdAt)}
                    </p>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge variant={priorityVariant[ticket.priority] ?? "muted"}>{ticket.priority}</Badge>
                    <Badge variant="muted">{ticket.status}</Badge>
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
