"use client";

import React, { useMemo } from "react";
import Link from "next/link";
import {
  Users,
  Ticket,
  Wallet,
  BarChart3,
  Shield,
  Building2,
  MapPin,
  TrendingUp,
  UserPlus,
  CreditCard,
  Activity,
  RefreshCw,
  Landmark,
  Clock,
  CheckCircle2,
  XCircle,
} from "lucide-react";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { Separator } from "@/components/ui/separator";
import {
  useAdminShortcuts,
  useAdminWeeklyStats,
  useAdminRecentActivities,
  useAdminStats,
} from "@/contexts/AdminStats";
import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from "recharts";
import { useAuth } from "@/contexts/AuthContext";

// ─── KPI config ───────────────────────────────────────────────────────────────

const KPI_META = [
  { key: "Paiements",             icon: CreditCard, href: "/admin/payments",      color: "text-rose-600",    bg: "bg-rose-50"    },
  { key: "Nouveaux utilisateurs", icon: UserPlus,   href: "/admin/users",         color: "text-blue-600",    bg: "bg-blue-50"    },
  { key: "Compagnies",            icon: Building2,  href: "/admin/companies",     color: "text-amber-600",   bg: "bg-amber-50"   },
  { key: "Opérateurs",            icon: Shield,     href: "/admin/company-admins",color: "text-violet-600",  bg: "bg-violet-50"  },
  { key: "Trajets actifs",        icon: MapPin,     href: "/admin/routes",        color: "text-teal-600",    bg: "bg-teal-50"    },
  { key: "Gares",                 icon: Landmark,   href: "/admin/stations",      color: "text-orange-600",  bg: "bg-orange-50"  },
] as const;

// ─── Quick nav config ─────────────────────────────────────────────────────────

const QUICK_NAV = [
  { label: "Utilisateurs", href: "/admin/users",    icon: Users,       color: "text-blue-600",  bg: "bg-blue-50"  },
  { label: "Paiements",    href: "/admin/payments", icon: Wallet,      color: "text-rose-600",  bg: "bg-rose-50"  },
  { label: "Compagnies",   href: "/admin/companies",icon: Building2,   color: "text-amber-600", bg: "bg-amber-50" },
  { label: "Trajets",      href: "/admin/routes",   icon: MapPin,      color: "text-teal-600",  bg: "bg-teal-50"  },
] as const;

// ─── Subcomponents ────────────────────────────────────────────────────────────

function KpiCard({
  title,
  count,
  description,
  href,
}: {
  title: string;
  count: string;
  description: string;
  href: string;
}) {
  const meta = KPI_META.find((m) => m.key === title) ?? KPI_META[0];
  const Icon = meta.icon;

  return (
    <Link href={href}>
      <Card className="group cursor-pointer border border-gray-200 bg-white shadow-none hover:shadow-md hover:border-gray-200 transition-all duration-200">
        <CardContent className="p-5">
          <div className="flex items-start justify-between mb-4">
            <div className={`p-2 rounded-lg ${meta.bg}`}>
              <Icon className={`w-4 h-4 ${meta.color}`} />
            </div>
            <TrendingUp className="w-3.5 h-3.5 text-gray-300 group-hover:text-gray-400 transition-colors" />
          </div>
          <p className="text-2xl font-bold text-gray-900 tracking-tight tabular-nums">
            {count}
          </p>
          <p className="text-xs font-medium text-gray-500 mt-1 truncate">{title}</p>
          <p className="text-[11px] text-gray-400 mt-0.5 truncate">{description}</p>
        </CardContent>
      </Card>
    </Link>
  );
}

function KpiSkeleton() {
  return (
    <Card className="border border-gray-200 shadow-none">
      <CardContent className="p-5 space-y-3">
        <Skeleton className="h-8 w-8 rounded-lg" />
        <Skeleton className="h-7 w-16" />
        <Skeleton className="h-3 w-24" />
      </CardContent>
    </Card>
  );
}

function ActivityItem({
  icon,
  iconClass,
  title,
  subtitle,
  time,
  badge,
}: {
  icon: React.ReactNode;
  iconClass: string;
  title: string;
  subtitle: string;
  time: string;
  badge?: { label: string; variant: "default" | "secondary" | "destructive" | "outline" };
}) {
  return (
    <div className="flex items-center gap-3 py-2.5 group">
      <div className={`w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0 ${iconClass}`}>
        {icon}
      </div>
      <div className="flex-1 min-w-0">
        <p className="text-sm font-medium text-gray-800 truncate">{title}</p>
        <p className="text-[11px] text-gray-400">{subtitle}</p>
      </div>
      <div className="flex flex-col items-end gap-1 flex-shrink-0">
        {badge && (
          <Badge variant={badge.variant} className="text-[10px] px-1.5 py-0 h-4">
            {badge.label}
          </Badge>
        )}
        <span className="text-[10px] text-gray-400 whitespace-nowrap">{time}</span>
      </div>
    </div>
  );
}

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function AdminDashboardPage() {
  const { shortcuts, loading, error } = useAdminShortcuts();
  const { data: weeklyStats, loading: loadingWeekly } = useAdminWeeklyStats();
  const { data: recent, loading: loadingRecent } = useAdminRecentActivities();
  const { refreshStats } = useAdminStats();
  const { user } = useAuth();

  const chartData = useMemo(() => {
    if (!weeklyStats) return [];
    const days = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"];
    return weeklyStats.users.map((u, i) => ({
      day: days[i] ?? `J${i + 1}`,
      Utilisateurs: u.count,
      Paiements: weeklyStats.payments[i]?.count ?? 0,
    }));
  }, [weeklyStats]);

  const activities = useMemo(() => {
    if (!recent) return [];
    type ActivityItem = {
      id: string;
      icon: React.ReactNode;
      iconClass: string;
      title: string;
      subtitle: string;
      time: string;
      badge?: { label: string; variant: "default" | "secondary" | "destructive" | "outline" };
      rawTime: Date;
    };
    const items: ActivityItem[] = [];

    recent.users.slice(0, 3).forEach((u) =>
      items.push({
        id: `u-${u.id}`,
        icon: <UserPlus className="w-3.5 h-3.5" />,
        iconClass: "bg-blue-50 text-blue-600",
        title: `${u.first_name} ${u.last_name}`,
        subtitle: "Nouvel utilisateur inscrit",
        time: new Date(u.created_at).toLocaleString("fr-FR", { dateStyle: "short", timeStyle: "short" }),
        rawTime: new Date(u.created_at),
      })
    );

    recent.payments.slice(0, 4).forEach((p) =>
      items.push({
        id: `p-${p.id}`,
        icon: p.status === "failed"
          ? <XCircle className="w-3.5 h-3.5" />
          : <CheckCircle2 className="w-3.5 h-3.5" />,
        iconClass: p.status === "failed" ? "bg-rose-50 text-rose-600" : "bg-emerald-50 text-emerald-600",
        title: `Paiement #${p.id}`,
        subtitle: p.status === "failed" ? "Paiement échoué" : "Paiement validé",
        time: new Date(p.created_at).toLocaleString("fr-FR", { dateStyle: "short", timeStyle: "short" }),
        badge: p.status === "failed"
          ? { label: "Échoué", variant: "destructive" as const }
          : { label: "Validé", variant: "secondary" as const },
        rawTime: new Date(p.created_at),
      })
    );

    recent.bookings.slice(0, 3).forEach((b) =>
      items.push({
        id: `b-${b.id}`,
        icon: <Ticket className="w-3.5 h-3.5" />,
        iconClass: "bg-amber-50 text-amber-600",
        title: `Réservation #${b.id}`,
        subtitle: b.status === "confirmed" ? "Confirmée" : b.status === "pending" ? "En attente" : b.status,
        time: new Date(b.created_at).toLocaleString("fr-FR", { dateStyle: "short", timeStyle: "short" }),
        rawTime: new Date(b.created_at),
      })
    );

    return items.sort((a, b) => b.rawTime.getTime() - a.rawTime.getTime()).slice(0, 8);
  }, [recent]);

  const today = new Date().toLocaleDateString("fr-FR", {
    weekday: "long",
    day: "numeric",
    month: "long",
    year: "numeric",
  });

  return (
    <div className="space-y-6">

      {/* ── Header ── */}
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-xl font-semibold text-gray-900">
            Bonjour{user?.firstName ? `, ${user.firstName}` : ""} 👋
          </h1>
          <p className="text-sm text-gray-400 mt-0.5 capitalize">{today}</p>
        </div>
        <Button
          variant="outline"
          size="sm"
          onClick={() => refreshStats()}
          className="gap-1.5 text-xs text-gray-600 border-gray-200"
        >
          <RefreshCw className="w-3.5 h-3.5" />
          Actualiser
        </Button>
      </div>

      {/* ── Error ── */}
      {error && (
        <div className="flex items-center gap-2 text-sm text-rose-600 bg-rose-50 border border-rose-100 rounded-lg px-4 py-3">
          <XCircle className="w-4 h-4 flex-shrink-0" />
          {error}
        </div>
      )}

      {/* ── KPI Grid ── */}
      <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-4">
        {loading
          ? Array.from({ length: 6 }).map((_, i) => <KpiSkeleton key={i} />)
          : shortcuts.map((sc) => (
              <KpiCard
                key={sc.title}
                title={sc.title}
                count={sc.count}
                description={sc.description}
                href={sc.link}
              />
            ))}
      </div>

      {/* ── Chart + Activity ── */}
      <div className="grid grid-cols-1 xl:grid-cols-5 gap-4">

        {/* Chart */}
        <Card className="xl:col-span-3 border border-gray-200 shadow-none">
          <CardHeader className="pb-0 pt-5 px-6">
            <div className="flex items-center justify-between">
              <div>
                <CardTitle className="text-sm font-semibold text-gray-800 flex items-center gap-2">
                  <BarChart3 className="w-4 h-4 text-rose-500" />
                  Activité hebdomadaire
                </CardTitle>
                <CardDescription className="text-xs mt-0.5">
                  Utilisateurs &amp; paiements — 7 derniers jours
                </CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent className="px-2 pt-4 pb-4">
            {loadingWeekly || !weeklyStats ? (
              <div className="h-60 flex items-center justify-center">
                <RefreshCw className="w-5 h-5 text-gray-200 animate-spin" />
              </div>
            ) : (
              <div className="h-60">
                <ResponsiveContainer width="100%" height="100%">
                  <AreaChart data={chartData} margin={{ top: 4, right: 16, left: -16, bottom: 0 }}>
                    <defs>
                      <linearGradient id="gUsers" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="0%" stopColor="#e11d48" stopOpacity={0.15} />
                        <stop offset="100%" stopColor="#e11d48" stopOpacity={0} />
                      </linearGradient>
                      <linearGradient id="gPayments" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="0%" stopColor="#3b82f6" stopOpacity={0.15} />
                        <stop offset="100%" stopColor="#3b82f6" stopOpacity={0} />
                      </linearGradient>
                    </defs>
                    <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" vertical={false} />
                    <XAxis
                      dataKey="day"
                      axisLine={false}
                      tickLine={false}
                      tick={{ fill: "#94a3b8", fontSize: 11 }}
                      dy={8}
                    />
                    <YAxis
                      allowDecimals={false}
                      axisLine={false}
                      tickLine={false}
                      tick={{ fill: "#94a3b8", fontSize: 11 }}
                    />
                    <Tooltip
                      contentStyle={{
                        backgroundColor: "#fff",
                        border: "1px solid #e2e8f0",
                        borderRadius: "8px",
                        boxShadow: "0 4px 16px -4px rgb(0 0 0 / 0.08)",
                        fontSize: "12px",
                      }}
                      cursor={{ stroke: "#e2e8f0", strokeWidth: 1 }}
                    />
                    <Area
                      type="monotone"
                      dataKey="Utilisateurs"
                      stroke="#e11d48"
                      strokeWidth={2}
                      fill="url(#gUsers)"
                      dot={false}
                      activeDot={{ r: 3, strokeWidth: 0, fill: "#e11d48" }}
                    />
                    <Area
                      type="monotone"
                      dataKey="Paiements"
                      stroke="#3b82f6"
                      strokeWidth={2}
                      fill="url(#gPayments)"
                      dot={false}
                      activeDot={{ r: 3, strokeWidth: 0, fill: "#3b82f6" }}
                    />
                  </AreaChart>
                </ResponsiveContainer>
              </div>
            )}
            <div className="flex items-center gap-4 px-4 mt-2">
              <span className="flex items-center gap-1.5 text-[11px] text-gray-500">
                <span className="w-2 h-2 rounded-full bg-rose-500" />
                Utilisateurs
              </span>
              <span className="flex items-center gap-1.5 text-[11px] text-gray-500">
                <span className="w-2 h-2 rounded-full bg-blue-500" />
                Paiements
              </span>
            </div>
          </CardContent>
        </Card>

        {/* Activity feed */}
        <Card className="xl:col-span-2 border border-gray-200 shadow-none">
          <CardHeader className="pb-0 pt-5 px-6">
            <div className="flex items-center justify-between">
              <CardTitle className="text-sm font-semibold text-gray-800 flex items-center gap-2">
                <Activity className="w-4 h-4 text-rose-500" />
                Activité récente
              </CardTitle>
              <span className="relative flex h-2 w-2">
                <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75" />
                <span className="relative inline-flex rounded-full h-2 w-2 bg-emerald-500" />
              </span>
            </div>
          </CardHeader>
          <CardContent className="px-6 pt-3 pb-5">
            {loadingRecent || !recent ? (
              <div className="space-y-3 pt-2">
                {Array.from({ length: 5 }).map((_, i) => (
                  <div key={i} className="flex items-center gap-3">
                    <Skeleton className="w-8 h-8 rounded-lg flex-shrink-0" />
                    <div className="flex-1 space-y-1.5">
                      <Skeleton className="h-3 w-32" />
                      <Skeleton className="h-2.5 w-20" />
                    </div>
                  </div>
                ))}
              </div>
            ) : activities.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-10 text-gray-400">
                <Clock className="w-7 h-7 mb-2 opacity-30" />
                <p className="text-xs">Aucune activité récente</p>
              </div>
            ) : (
              <div className="divide-y divide-gray-50">
                {activities.map((a) => (
                  <ActivityItem key={a.id} {...a} />
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* ── Quick nav ── */}
      <Card className="border border-gray-200 shadow-none">
        <CardContent className="p-0">
          <div className="grid grid-cols-2 sm:grid-cols-4 divide-x divide-gray-100">
            {QUICK_NAV.map((link) => {
              const Icon = link.icon;
              return (
                <Link
                  key={link.href}
                  href={link.href}
                  className="flex items-center justify-center gap-2.5 py-4 px-4 hover:bg-gray-50 transition-colors group"
                >
                  <span className={`w-7 h-7 rounded-lg flex items-center justify-center ${link.bg} ${link.color} group-hover:scale-110 transition-transform duration-150`}>
                    <Icon className="w-3.5 h-3.5" />
                  </span>
                  <span className="text-sm font-medium text-gray-700">{link.label}</span>
                </Link>
              );
            })}
          </div>
        </CardContent>
      </Card>

    </div>
  );
}
