"use client"

import { useEffect, useState } from "react"
import {
  Users,
  ArrowRight,
  ShieldCheck,
  Clock,
  CalendarDays,
  BarChart3,
  FileText,
  Stethoscope,
  Tag,
  CheckCircle2,
  Hospital,
  Activity,
} from "lucide-react"
import Link from "next/link"
import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
} from "recharts"
import { Navbar } from "@/components/dashboard/navbar"

/* ─── Types ─── */
interface User {
  id: string
  name: string
  email: string
  role: "admin" | "employee"
  status: "active" | "inactive"
  createdAt: string
}

/* ─── Custom Tooltip ─── */
function CustomTooltip({ active, payload, label }: any) {
  if (!active || !payload?.length) return null
  return (
    <div
      className="rounded-xl px-3 py-2 text-sm font-sans shadow-lg border border-border"
      style={{ background: "var(--card)", color: "var(--foreground)" }}
    >
      <p className="text-xs text-muted-foreground mb-0.5">{label}</p>
      <p className="font-bold" style={{ color: "var(--brand-green)" }}>
        {payload[0].value}
      </p>
    </div>
  )
}

/* ─── Activity item ─── */
function ActivityItem({
  name,
  action,
  time,
  role,
}: {
  name: string
  action: string
  time: string
  role: "admin" | "employee"
}) {
  return (
    <div className="flex items-start gap-3 py-3 border-b border-border last:border-0">
      <div
        className="w-8 h-8 rounded-full flex items-center justify-center text-white text-xs font-bold font-sans shrink-0 mt-0.5"
        style={{ background: role === "admin" ? "var(--brand-navy)" : "var(--brand-green)" }}
        aria-hidden="true"
      >
        {name.charAt(0)}
      </div>
      <div className="flex-1 min-w-0">
        <p className="text-sm font-semibold text-foreground font-sans truncate">{name}</p>
        <p className="text-xs text-muted-foreground font-sans">{action}</p>
      </div>
      <span className="text-xs text-muted-foreground font-sans shrink-0 flex items-center gap-1 mt-0.5">
        <Clock className="w-3 h-3" aria-hidden="true" />
        {time}
      </span>
    </div>
  )
}

/* ─── Main page ─── */
export default function DashboardPage() {
  const [users, setUsers] = useState<User[]>([])
  const [totalArticles, setTotalArticles] = useState(0)
  const [publishedArticles, setPublishedArticles] = useState(0)
  const [totalDoctors, setTotalDoctors] = useState(0)
  const [publishedDoctors, setPublishedDoctors] = useState(0)
  const [totalCategories, setTotalCategories] = useState(0)
  const [totalHospitals, setTotalHospitals] = useState(0)
  const [publishedHospitals, setPublishedHospitals] = useState(0)
  const [totalProcedures, setTotalProcedures] = useState(0)
  const [publishedProcedures, setPublishedProcedures] = useState(0)
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    let mounted = true
    setIsLoading(true)

    Promise.all([
      fetch("/api/admin/users", { cache: "no-store" }).then((r) => r.json()).catch(() => ({})),
      fetch("/api/admin/articles", { cache: "no-store" }).then((r) => r.json()).catch(() => ({})),
      fetch("/api/admin/doctors", { cache: "no-store" }).then((r) => r.json()).catch(() => ({})),
      fetch("/api/admin/categories", { cache: "no-store" }).then((r) => r.json()).catch(() => ({})),
      fetch("/api/admin/hospitals", { cache: "no-store" }).then((r) => r.json()).catch(() => ({})),
      fetch("/api/admin/procedures", { cache: "no-store" }).then((r) => r.json()).catch(() => ({})),
    ]).then(([usersData, articlesData, doctorsData, categoriesData, hospitalsData, proceduresData]) => {
      if (!mounted) return

      if (usersData?.users) {
        setUsers(
          usersData.users.map((u: any) => ({
            id: u.id,
            name: u.name ?? "",
            email: u.email,
            role: u.role,
            status: u.status ?? "active",
            createdAt: u.audit?.createdAt ?? u.createdAt ?? "",
          }))
        )
      }

      if (Array.isArray(articlesData?.articles)) {
        const articles = articlesData.articles as Array<{ status: string }>
        setTotalArticles(articles.length)
        setPublishedArticles(articles.filter((a) => a.status === "published").length)
      }

      if (Array.isArray(doctorsData?.doctors)) {
        const doctors = doctorsData.doctors as Array<{ status: string }>
        setTotalDoctors(doctors.length)
        setPublishedDoctors(doctors.filter((d) => d.status === "published").length)
      }

      if (Array.isArray(hospitalsData?.hospitals)) {
        const hospitals = hospitalsData.hospitals as Array<{ status?: string }>
        setTotalHospitals(hospitals.length)
        setPublishedHospitals(hospitals.filter((h) => h.status === "published").length)
      }

      if (Array.isArray(proceduresData?.procedures)) {
        const procedures = proceduresData.procedures as Array<{ status?: string }>
        setTotalProcedures(procedures.length)
        setPublishedProcedures(procedures.filter((p) => p.status === "published").length)
      }

      if (Array.isArray(categoriesData?.categories)) {
        setTotalCategories(categoriesData.categories.length)
      }
    }).finally(() => {
      if (mounted) setIsLoading(false)
    })

    return () => { mounted = false }
  }, [])

  const totalUsers = users.length
  const totalAdmins = users.filter((u) => u.role === "admin").length

  const contentDistribution = [
    { name: "Articles", value: totalArticles, color: "var(--brand-green)" },
    { name: "Doctors", value: totalDoctors, color: "var(--brand-navy)" },
    { name: "Hospitals", value: totalHospitals, color: "#2563EB" },
    { name: "Procedures", value: totalProcedures, color: "#F97316" },
    { name: "Categories", value: totalCategories, color: "#0EA5E9" },
  ]
  const contentTotal =
    totalArticles + totalDoctors + totalCategories + totalHospitals + totalProcedures
  const publishedContentTotal =
    publishedArticles + publishedDoctors + publishedHospitals + publishedProcedures

  const chartData = [
    { label: "Articles", total: totalArticles, published: publishedArticles },
    { label: "Doctors", total: totalDoctors, published: publishedDoctors },
    { label: "Hospitals", total: totalHospitals, published: publishedHospitals },
    { label: "Procedures", total: totalProcedures, published: publishedProcedures },
    { label: "Users", total: totalUsers, published: totalAdmins },
    { label: "Categories", total: totalCategories, published: totalCategories },
  ]

  const STATS = [
    {
      label: "Total Articles",
      value: totalArticles,
      sub: `${publishedArticles} published`,
      icon: FileText,
      color: "var(--brand-green)",
      href: "/dashboard/articles",
    },
    {
      label: "Total Doctors",
      value: totalDoctors,
      sub: `${publishedDoctors} published`,
      icon: Stethoscope,
      color: "var(--brand-navy)",
      href: "/dashboard/doctors",
    },
    {
      label: "Total Hospitals",
      value: totalHospitals,
      sub: `${publishedHospitals} published`,
      icon: Hospital,
      color: "#2563EB",
      href: "/dashboard/hospitals",
    },
    {
      label: "Total Procedures",
      value: totalProcedures,
      sub: `${publishedProcedures} published`,
      icon: Activity,
      color: "#F97316",
      href: "/dashboard/procedures",
    },
    {
      label: "Total Users",
      value: totalUsers,
      sub: `${totalAdmins} administrators`,
      icon: Users,
      color: "#0EA5E9",
      href: "/dashboard/admins",
    },
    {
      label: "Categories",
      value: totalCategories,
      sub: "Active categories",
      icon: Tag,
      color: "#F59E0B",
      href: "/dashboard/categories",
    },
  ]

  const recentUsers = [...users]
    .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
    .slice(0, 5)

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

  return (
    <>
      <Navbar
        title="Dashboard"
        breadcrumbs={[{ label: "Dashboard" }]}
      />

      <div className="p-6 flex flex-col gap-6">
        {/* ── Welcome banner ── */}
        <div
          className="relative rounded-2xl overflow-hidden px-7 py-6 flex items-center justify-between gap-4 flex-wrap"
          style={{ background: "var(--brand-navy)" }}
        >
          {/* decorative cross */}
          <div className="absolute right-8 top-1/2 -translate-y-1/2 opacity-[0.06] pointer-events-none select-none" aria-hidden="true">
            <svg width="140" height="140" viewBox="0 0 30 30" fill="none">
              <rect x="11" y="0" width="8" height="30" rx="3" fill="white" />
              <rect x="0" y="11" width="30" height="8" rx="3" fill="white" />
            </svg>
          </div>
          <div className="absolute right-32 bottom-0 opacity-[0.04] pointer-events-none select-none" aria-hidden="true">
            <svg width="90" height="90" viewBox="0 0 60 60" fill="none">
              <polygon points="30,2 55,16 55,44 30,58 5,44 5,16" stroke="white" strokeWidth="2" fill="none" />
            </svg>
          </div>

          <div className="relative z-10">
            <p className="text-white/50 text-xs uppercase tracking-widest font-sans mb-1 flex items-center gap-1.5">
              <CalendarDays className="w-3.5 h-3.5" aria-hidden="true" />
              {today}
            </p>
            <h1 className="text-white text-2xl font-bold font-sans text-balance">
              Welcome back, Admin
            </h1>
            <p className="text-white/60 text-sm font-sans mt-1">
              Here&apos;s your Livist Medical system overview.
            </p>
          </div>

          <div className="relative z-10 flex items-center gap-3 shrink-0">
            <div
              className="flex items-center gap-2 px-4 py-2.5 rounded-xl text-xs font-semibold font-sans"
              style={{ background: "rgba(43,182,115,0.20)", color: "#2BB673", border: "1px solid rgba(43,182,115,0.30)" }}
            >
              <ShieldCheck className="w-4 h-4" aria-hidden="true" />
              System Secure
            </div>
          </div>
        </div>

        {/* ── Stat cards ── */}
        <div className="grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 gap-4">
          {STATS.map((stat) => {
            const Icon = stat.icon
            return (
              <Link
                key={stat.label}
                href={stat.href}
                className="bg-card rounded-2xl p-5 border border-border flex flex-col gap-3 hover:border-[var(--brand-green)]/40 transition-colors group"
              >
                <div className="flex items-center justify-between">
                  <div
                    className="w-10 h-10 rounded-xl flex items-center justify-center shrink-0"
                    style={{ background: `${stat.color}18` }}
                  >
                    <Icon className="w-5 h-5" style={{ color: stat.color }} aria-hidden="true" />
                  </div>
                  <ArrowRight
                    className="w-4 h-4 text-muted-foreground group-hover:text-foreground transition-colors"
                    aria-hidden="true"
                  />
                </div>
                <div>
                  <p className="text-3xl font-bold text-foreground font-sans leading-none">
                    {isLoading ? "—" : stat.value}
                  </p>
                  <p className="text-sm font-semibold text-foreground font-sans mt-1">{stat.label}</p>
                  <p className="text-xs text-muted-foreground font-sans mt-0.5">{stat.sub}</p>
                </div>
              </Link>
            )
          })}
        </div>

        {/* ── Charts row ── */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
          {/* Bar chart — total vs published */}
          <div className="lg:col-span-2 bg-card rounded-2xl border border-border p-5 flex flex-col gap-4">
            <div className="flex items-center justify-between gap-2 flex-wrap">
              <div>
                <div className="flex items-center gap-2">
                  <BarChart3 className="w-4 h-4" style={{ color: "var(--brand-green)" }} aria-hidden="true" />
                  <h2 className="text-sm font-bold text-foreground font-sans">Content Overview</h2>
                </div>
                <p className="text-xs text-muted-foreground font-sans mt-0.5">
                  Total vs published records per section
                </p>
              </div>
              <div className="flex items-center gap-3">
                <span className="flex items-center gap-1.5 text-xs font-semibold font-sans text-muted-foreground">
                  <span className="w-2.5 h-2.5 rounded-sm inline-block" style={{ background: "rgba(43,182,115,0.25)" }} />
                  Total
                </span>
                <span className="flex items-center gap-1.5 text-xs font-semibold font-sans text-muted-foreground">
                  <span className="w-2.5 h-2.5 rounded-sm inline-block" style={{ background: "var(--brand-green)" }} />
                  Published
                </span>
              </div>
            </div>
            <div className="h-[200px] w-full">
              <ResponsiveContainer width="100%" height="100%">
                <AreaChart data={chartData} margin={{ top: 4, right: 4, left: -20, bottom: 0 }}>
                  <defs>
                    <linearGradient id="totalGrad" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#2BB673" stopOpacity={0.10} />
                      <stop offset="95%" stopColor="#2BB673" stopOpacity={0} />
                    </linearGradient>
                    <linearGradient id="publishedGrad" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#2BB673" stopOpacity={0.25} />
                      <stop offset="95%" stopColor="#2BB673" stopOpacity={0} />
                    </linearGradient>
                  </defs>
                  <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />
                  <XAxis
                    dataKey="label"
                    tick={{ fontSize: 11, fontFamily: "var(--font-rokkitt)", fill: "var(--muted-foreground)" }}
                    axisLine={false}
                    tickLine={false}
                  />
                  <YAxis
                    tick={{ fontSize: 11, fontFamily: "var(--font-rokkitt)", fill: "var(--muted-foreground)" }}
                    axisLine={false}
                    tickLine={false}
                    allowDecimals={false}
                  />
                  <Tooltip content={<CustomTooltip />} />
                  <Area
                    type="monotone"
                    dataKey="total"
                    stroke="rgba(43,182,115,0.4)"
                    strokeWidth={2}
                    fill="url(#totalGrad)"
                    dot={{ r: 3, fill: "rgba(43,182,115,0.5)", strokeWidth: 0 }}
                  />
                  <Area
                    type="monotone"
                    dataKey="published"
                    stroke="#2BB673"
                    strokeWidth={2.5}
                    fill="url(#publishedGrad)"
                    dot={{ r: 4, fill: "#2BB673", strokeWidth: 0 }}
                    activeDot={{ r: 6, fill: "#2BB673", strokeWidth: 0 }}
                  />
                </AreaChart>
              </ResponsiveContainer>
            </div>
          </div>

          {/* Pie chart — content distribution */}
          <div className="bg-card rounded-2xl border border-border p-5 flex flex-col gap-4">
            <div>
              <div className="flex items-center gap-2">
                <div className="w-4 h-4 rounded-full" style={{ background: "var(--brand-green)" }} aria-hidden="true" />
                <h2 className="text-sm font-bold text-foreground font-sans">Content Distribution</h2>
              </div>
              <p className="text-xs text-muted-foreground font-sans mt-0.5">
                Articles, doctors, hospitals, procedures &amp; categories
              </p>
            </div>

            <div className="flex-1 flex items-center justify-center">
              {isLoading || contentTotal === 0 ? (
                <div className="flex flex-col items-center gap-2 text-muted-foreground">
                  <div className="w-24 h-24 rounded-full border-4 border-border border-dashed" />
                  <span className="text-xs font-sans">No data yet</span>
                </div>
              ) : (
                <div className="relative w-[140px] h-[140px]">
                  <PieChart width={140} height={140}>
                    <Pie
                      data={contentDistribution}
                      cx={65}
                      cy={65}
                      innerRadius={45}
                      outerRadius={65}
                      dataKey="value"
                      strokeWidth={0}
                    >
                      {contentDistribution.map((entry, index) => (
                        <Cell key={index} fill={entry.color} />
                      ))}
                    </Pie>
                  </PieChart>
                  <div className="absolute inset-0 flex flex-col items-center justify-center pointer-events-none">
                    <span className="text-2xl font-bold text-foreground font-sans leading-none">{contentTotal}</span>
                    <span className="text-[10px] text-muted-foreground font-sans">total</span>
                  </div>
                </div>
              )}
            </div>

            {/* Legend */}
            <div className="flex flex-col gap-2">
              {contentDistribution.map((item) => (
                <div key={item.name} className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <div className="w-2.5 h-2.5 rounded-full shrink-0" style={{ background: item.color }} aria-hidden="true" />
                    <span className="text-xs text-muted-foreground font-sans">{item.name}</span>
                  </div>
                  <span className="text-xs font-bold text-foreground font-sans">{isLoading ? "—" : item.value}</span>
                </div>
              ))}
              <div className="flex items-center justify-between border-t border-border pt-2 mt-1">
                <div className="flex items-center gap-2">
                  <CheckCircle2 className="w-3 h-3 shrink-0" style={{ color: "var(--brand-green)" }} aria-hidden="true" />
                  <span className="text-xs text-muted-foreground font-sans">Published</span>
                </div>
                <span className="text-xs font-bold text-foreground font-sans">
                  {isLoading ? "—" : publishedContentTotal}
                </span>
              </div>
            </div>
          </div>
        </div>

        {/* ── Bottom row: Recent users + Quick links ── */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
          {/* Recent Users */}
          <div className="lg:col-span-2 bg-card rounded-2xl border border-border overflow-hidden">
            <div className="flex items-center justify-between px-5 py-4 border-b border-border">
              <h2 className="text-sm font-bold text-foreground font-sans">Recently Added Users</h2>
              <Link
                href="/dashboard/admins"
                className="flex items-center gap-1 text-xs font-semibold font-sans transition-colors hover:opacity-80"
                style={{ color: "var(--brand-green)" }}
              >
                View all
                <ArrowRight className="w-3 h-3" aria-hidden="true" />
              </Link>
            </div>
            <div className="px-5 divide-y divide-border">
              {isLoading ? (
                <div className="py-10 text-center text-sm text-muted-foreground font-sans">Loading...</div>
              ) : recentUsers.length === 0 ? (
                <div className="py-10 text-center text-sm text-muted-foreground font-sans">No users found.</div>
              ) : (
                recentUsers.map((u) => (
                  <ActivityItem
                    key={u.id}
                    name={u.name || u.email}
                    action={`${u.role === "admin" ? "Administrator" : "Staff member"} · ${u.email}`}
                    time={new Date(u.createdAt).toLocaleDateString("en-US", { month: "short", day: "numeric" })}
                    role={u.role}
                  />
                ))
              )}
            </div>
          </div>

          {/* Quick links + status */}
          <div className="flex flex-col gap-4">
            {/* System status */}
            <div className="bg-card rounded-2xl border border-border p-5 flex flex-col gap-3">
              <h2 className="text-sm font-bold text-foreground font-sans">System Status</h2>
              {[
                { label: "Authentication", ok: true },
                { label: "Database", ok: true },
                { label: "API Server", ok: true },
              ].map((s) => (
                <div key={s.label} className="flex items-center justify-between">
                  <span className="text-xs text-muted-foreground font-sans">{s.label}</span>
                  <div className="flex items-center gap-1.5">
                    <span
                      className="w-2 h-2 rounded-full"
                      style={{ background: s.ok ? "var(--brand-green)" : "#ef4444" }}
                      aria-hidden="true"
                    />
                    <span
                      className="text-xs font-semibold font-sans"
                      style={{ color: s.ok ? "var(--brand-green)" : "#ef4444" }}
                    >
                      {s.ok ? "Operational" : "Down"}
                    </span>
                  </div>
                </div>
              ))}
            </div>

            {/* Quick actions */}
            <div className="bg-card rounded-2xl border border-border p-5 flex flex-col gap-3">
              <h2 className="text-sm font-bold text-foreground font-sans">Quick Actions</h2>
              {[
                { href: "/dashboard/articles", label: "Manage Articles", sub: "Add, edit, delete", Icon: FileText, color: "rgba(43,182,115,0.10)", iconColor: "var(--brand-green)" },
                { href: "/dashboard/doctors", label: "Manage Doctors", sub: "Add, edit, delete", Icon: Stethoscope, color: "rgba(29,45,104,0.10)", iconColor: "var(--brand-navy)" },
                { href: "/dashboard/admins", label: "Manage Users", sub: "Add, edit, delete", Icon: Users, color: "rgba(14,165,233,0.10)", iconColor: "#0EA5E9" },
                { href: "/dashboard/categories", label: "Manage Categories", sub: "Add, edit, delete", Icon: Tag, color: "rgba(245,158,11,0.10)", iconColor: "#F59E0B" },
              ].map(({ href, label, sub, Icon, color, iconColor }) => (
                <Link
                  key={href}
                  href={href}
                  className="flex items-center justify-between gap-2 px-3.5 py-3 rounded-xl border border-border hover:border-[#2BB673]/50 hover:bg-accent/30 transition-all group"
                >
                  <div className="flex items-center gap-2.5">
                    <div
                      className="w-8 h-8 rounded-lg flex items-center justify-center shrink-0"
                      style={{ background: color }}
                      aria-hidden="true"
                    >
                      <Icon className="w-4 h-4" style={{ color: iconColor }} />
                    </div>
                    <div>
                      <p className="text-xs font-semibold text-foreground font-sans">{label}</p>
                      <p className="text-[10px] text-muted-foreground font-sans">{sub}</p>
                    </div>
                  </div>
                  <ArrowRight className="w-3.5 h-3.5 text-muted-foreground group-hover:text-foreground transition-colors shrink-0" aria-hidden="true" />
                </Link>
              ))}
            </div>
          </div>
        </div>
      </div>
    </>
  )
}
