"use client";

import {
  AlertTriangle,
  ArrowRight,
  CreditCard,
  Mail,
  TrendingUp,
  Users,
} from "lucide-react";
import Link from "next/link";
import {
  Bar,
  BarChart,
  Cell,
  Pie,
  PieChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";

import { StatCard } from "@/components/admin/stat-card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { ANALYTICS_DATA } from "@/data/analytics";
import { ARCHETYPES } from "@/data/archetypes";
import { EMAIL_TEMPLATES } from "@/data/email-templates";
import { DEMO_USERS } from "@/data/users";

const archetypeColorMap = Object.fromEntries(ARCHETYPES.map((a) => [a.id, a.color]));

const archetypeDistributionData = ANALYTICS_DATA.archetypeDistribution.map((d) => ({
  ...d,
  name: ARCHETYPES.find((a) => a.id === d.archetypeId)?.name.replace("The ", "") ?? d.archetypeId,
  color: archetypeColorMap[d.archetypeId] ?? "#888",
}));

function StatusBadge({ status }: { status: string }) {
  const map: Record<string, string> = {
    active: "bg-emerald-50 text-emerald-700 border-emerald-200",
    suspended: "bg-red-50 text-red-600 border-red-200",
    pending: "bg-amber-50 text-amber-700 border-amber-200",
  };
  return (
    <span className={`inline-flex rounded-full border px-2 py-0.5 text-xs font-medium capitalize ${map[status] ?? "bg-gray-50 text-gray-600 border-gray-200"}`}>
      {status}
    </span>
  );
}

function PackageBadge({ pkg }: { pkg: string | null | undefined }) {
  if (!pkg) return <span className="text-xs text-gray-400">—</span>;
  const map: Record<string, string> = {
    starter: "bg-blue-50 text-blue-700 border-blue-200",
    advanced: "bg-teal-50 text-teal-700 border-teal-200",
    professional: "bg-violet-50 text-violet-700 border-violet-200",
  };
  return (
    <span className={`inline-flex rounded-full border px-2 py-0.5 text-xs font-medium capitalize ${map[pkg] ?? "bg-gray-50 text-gray-600 border-gray-200"}`}>
      {pkg}
    </span>
  );
}

export default function AdminDashboardPage() {
  const recentUsers = DEMO_USERS.slice(0, 5);
  const recentEmails = EMAIL_TEMPLATES.slice(0, 3);

  return (
    <div className="space-y-6 p-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-gray-900">Dashboard</h1>
        <p className="text-sm text-gray-500">Welcome back. Here&apos;s what&apos;s happening with Novalife today.</p>
      </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
        <StatCard
          title="Total Users"
          value="1,247"
          trend="+12%"
          trendUp={true}
          icon={Users}
          description="Registered accounts"
        />
        <StatCard
          title="Active Subscriptions"
          value="183"
          trend="+8%"
          trendUp={true}
          icon={TrendingUp}
          description="Professional plan subscribers"
        />
        <StatCard
          title="Revenue (MTD)"
          value="CHF 7,640"
          trend="+24%"
          trendUp={true}
          icon={CreditCard}
          description="May 2026"
        />
        <StatCard
          title="Submissions Today"
          value="24"
          trend="+3 since yesterday"
          trendUp={true}
          icon={Mail}
          description="New quiz completions"
        />
      </div>

      {/* Charts Row */}
      <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
        {/* Revenue Chart */}
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-base font-semibold">Revenue Over Time</CardTitle>
            <p className="text-xs text-gray-500">Monthly revenue in CHF (Jan–May 2026)</p>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={240}>
              <BarChart data={ANALYTICS_DATA.revenue} margin={{ top: 4, right: 8, bottom: 4, left: 0 }}>
                <XAxis dataKey="date" tick={{ fontSize: 11 }} />
                <YAxis tick={{ fontSize: 11 }} />
                <Tooltip
                  formatter={(v) => [`CHF ${Number(v).toLocaleString()}`, "Revenue"]}
                  contentStyle={{ fontSize: 12, borderRadius: 8 }}
                />
                <Bar dataKey="value" fill="#0F766E" radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* Archetype Distribution */}
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-base font-semibold">Archetype Distribution</CardTitle>
            <p className="text-xs text-gray-500">Share of users by metabolic archetype</p>
          </CardHeader>
          <CardContent>
            <div className="flex items-center gap-4">
              <ResponsiveContainer width="100%" height={200}>
                <PieChart>
                  <Pie
                    data={archetypeDistributionData}
                    cx="50%"
                    cy="50%"
                    innerRadius={55}
                    outerRadius={85}
                    paddingAngle={2}
                    dataKey="count"
                  >
                    {archetypeDistributionData.map((entry) => (
                      <Cell key={entry.archetypeId} fill={entry.color} />
                    ))}
                  </Pie>
                  <Tooltip
                    formatter={(v, _n, p) => [`${Number(v)} users (${(p as { payload?: { name?: string } }).payload?.name ?? ""})`, ""]}
                    contentStyle={{ fontSize: 12, borderRadius: 8 }}
                  />
                </PieChart>
              </ResponsiveContainer>
              <div className="shrink-0 space-y-1.5">
                {archetypeDistributionData.map((d) => (
                  <div key={d.archetypeId} className="flex items-center gap-2 text-xs">
                    <span className="h-2.5 w-2.5 shrink-0 rounded-full" style={{ backgroundColor: d.color }} />
                    <span className="text-gray-600 truncate max-w-[100px]">{d.name}</span>
                    <span className="font-semibold text-gray-900">{d.percentage}%</span>
                  </div>
                ))}
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Bottom Row */}
      <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
        {/* Recent Users Table */}
        <Card className="lg:col-span-2">
          <CardHeader className="flex flex-row items-center justify-between pb-3">
            <CardTitle className="text-base font-semibold">Recent Users</CardTitle>
            <Link href="/admin/users">
              <Button variant="ghost" size="sm" className="h-7 gap-1 text-xs text-teal-700 hover:text-teal-800">
                View all <ArrowRight className="h-3 w-3" />
              </Button>
            </Link>
          </CardHeader>
          <CardContent className="p-0">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-gray-100 bg-gray-50/50">
                  <th className="px-4 py-2.5 text-left text-xs font-medium text-gray-500">Name</th>
                  <th className="px-4 py-2.5 text-left text-xs font-medium text-gray-500">Archetype</th>
                  <th className="px-4 py-2.5 text-left text-xs font-medium text-gray-500">Package</th>
                  <th className="px-4 py-2.5 text-left text-xs font-medium text-gray-500">Status</th>
                  <th className="px-4 py-2.5 text-left text-xs font-medium text-gray-500">Joined</th>
                </tr>
              </thead>
              <tbody>
                {recentUsers.map((user) => {
                  const archetype = ARCHETYPES.find((a) => a.id === user.archetypeResult?.primaryArchetype);
                  return (
                    <tr key={user.id} className="border-b border-gray-50 hover:bg-gray-50/50 transition-colors">
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-2">
                          <div
                            className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-xs font-bold text-white"
                            style={{ backgroundColor: archetype?.color ?? "#0F766E" }}
                          >
                            {user.firstName[0]}{user.lastName[0]}
                          </div>
                          <div>
                            <p className="font-medium text-gray-900">{user.firstName} {user.lastName}</p>
                            <p className="text-xs text-gray-400">{user.email}</p>
                          </div>
                        </div>
                      </td>
                      <td className="px-4 py-3">
                        {archetype ? (
                          <Badge
                            className="text-[10px] font-medium"
                            style={{ backgroundColor: archetype.color + "22", color: archetype.color, borderColor: archetype.color + "44" }}
                          >
                            {archetype.name.replace("The ", "")}
                          </Badge>
                        ) : <span className="text-xs text-gray-400">—</span>}
                      </td>
                      <td className="px-4 py-3"><PackageBadge pkg={user.purchasedPackage} /></td>
                      <td className="px-4 py-3"><StatusBadge status={user.status} /></td>
                      <td className="px-4 py-3 text-xs text-gray-500">
                        {new Date(user.createdAt).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "2-digit" })}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </CardContent>
        </Card>

        {/* Right column */}
        <div className="space-y-4">
          {/* GLP-1 Alert */}
          <Card className="border-amber-200 bg-amber-50">
            <CardHeader className="pb-2">
              <div className="flex items-center gap-2">
                <AlertTriangle className="h-4 w-4 text-amber-600" />
                <CardTitle className="text-sm font-semibold text-amber-800">GLP-1 Review Required</CardTitle>
              </div>
            </CardHeader>
            <CardContent>
              <p className="mb-3 text-sm text-amber-700">
                3 new GLP-1 eligible cases require medical review before notification.
              </p>
              <Link href="/admin/glp1">
                <Button size="sm" className="w-full gap-2 bg-amber-600 hover:bg-amber-700 text-white text-xs">
                  Review Cases <ArrowRight className="h-3 w-3" />
                </Button>
              </Link>
            </CardContent>
          </Card>

          {/* Email Activity */}
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-semibold">Email Activity</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              {recentEmails.map((tpl) => (
                <div key={tpl.id} className="flex items-center justify-between text-xs">
                  <div className="min-w-0 flex-1">
                    <p className="font-medium text-gray-800 truncate">{tpl.name}</p>
                    <p className="text-gray-400">{tpl.sentCount.toLocaleString()} sent</p>
                  </div>
                  <div className="shrink-0 text-right">
                    <p className="font-semibold text-emerald-700">{tpl.openRate}%</p>
                    <p className="text-gray-400">open</p>
                  </div>
                </div>
              ))}
              <Link href="/admin/email">
                <Button variant="ghost" size="sm" className="mt-1 h-7 w-full gap-1 text-xs text-teal-700">
                  View all <ArrowRight className="h-3 w-3" />
                </Button>
              </Link>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
