import React, { memo, useEffect, useState } from "react";
import {
  Users,
  TrendingUp,
  Clock,
  Building2,
  UserCheck,
} from "lucide-react";
import {
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  AreaChart,
  Area,
} from "recharts";
import { useNavigate } from "react-router-dom";
import ROUTE_CONSTANTS from "@/constants/route.constants";
import { API_Instance } from "@/api/axios.instance";
import API_Constants from "@/constants/api.constants";
import { Spin, Tag, Empty } from "antd";
import { getAxiosErrorMessage } from "@/utils/index.utils";
import dayjs from "dayjs";

const StatCard = memo(
  ({ title, value, icon: Icon, color, subtext, footerData, onClick }: any) => (
    <div
      className="bg-white rounded-xl p-6 shadow-sm border border-gray-100 flex flex-col hover:shadow-md transition-shadow cursor-pointer"
      onClick={onClick}
    >
      <div className="flex items-start justify-between">
        <div>
          <p className="text-sm text-gray-500 font-medium">{title}</p>
          <h3 className="text-3xl font-bold text-gray-900 mt-1">{value}</h3>
        </div>
        <span className={`p-3 rounded-xl ${color} bg-opacity-10`}>
          <Icon className={`w-6 h-6 ${color.replace("bg-", "text-")}`} />
        </span>
      </div>

      {subtext && <p className="mt-2 text-gray-600 text-sm">{subtext}</p>}

      {footerData && (
        <div className="mt-4 pt-4 border-t border-gray-50 grid grid-cols-2 gap-2 text-sm">
          {footerData.map((f: any, i: number) => (
            <div key={i}>
              <p className="text-xs text-gray-400 capitalize">{f.label}</p>
              <p className="font-semibold text-gray-700">{f.value}</p>
            </div>
          ))}
        </div>
      )}
    </div>
  ),
);

const ChartCard = memo(({ title, icon: Icon, subtitle, children }: any) => (
  <div className="bg-white p-6 rounded-xl shadow-sm border border-gray-100">
    <div className="flex justify-between items-center mb-6">
      <h3 className="text-lg font-bold flex items-center text-gray-900">
        <Icon className="w-5 h-5 mr-2 text-brand-blue" /> {title}
      </h3>
      {subtitle && (
        <span className="text-sm text-gray-400 font-medium">{subtitle}</span>
      )}
    </div>
    <div className="h-72">{children}</div>
  </div>
));

const AdminDashboard: React.FC = () => {
  const navigate = useNavigate();
  const [isLoading, setIsLoading] = useState(false);
  const [stats, setStats] = useState<any>({
    counts: {
      institutions: { total: 0, verified: 0, unverified: 0 },
      users: { totalStudents: 0, totalStaff: 0, totalPlatformUsers: 0 },
    },
    recentInstitutions: [],
    platformRegistrationTrend: [],
  });

  const getData = async () => {
    try {
      setIsLoading(true);
      const res = await API_Instance.get(`${API_Constants.dashboard}/admin`);
      setStats(res.data.data);
    } catch (error) {
      getAxiosErrorMessage(error);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    getData();
  }, []);

  if (isLoading) {
    return (
      <div className="h-[80vh] flex flex-col gap-4 items-center justify-center">
        <Spin />
        <p className="text-slate-500 font-medium animate-pulse">
          Loading analytics...
        </p>
      </div>
    );
  }

  const { counts, recentInstitutions, platformRegistrationTrend } = stats;

  const formattedTrend = (platformRegistrationTrend || []).map((t: any) => ({
    date: dayjs(t.date).format("DD MMM"),
    registrations: t.count,
  }));

  return (
    <div className="mx-auto p-6 space-y-8 animate-in fade-in duration-500">
      <header className="flex flex-col gap-1">
        <h2 className="text-2xl font-bold text-gray-900">Dashboard Overview</h2>
      </header>

      {/* Stats Cards */}
      <section className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <StatCard
          title="Total Institutions"
          value={counts?.institutions?.total?.toLocaleString() || 0}
          icon={Building2}
          color="bg-indigo-600"
          footerData={[
            {
              label: "Verified",
              value: counts?.institutions?.verified?.toLocaleString() || 0,
            },
            {
              label: "Unverified",
              value: counts?.institutions?.unverified?.toLocaleString() || 0,
            },
          ]}
          onClick={() => navigate(ROUTE_CONSTANTS.Institutions)}
        />
        <StatCard
          title="Total Platform Users"
          value={counts?.users?.totalPlatformUsers?.toLocaleString() || 0}
          icon={Users}
          color="bg-blue-600"
          footerData={[
            {
              label: "Students",
              value: counts?.users?.totalStudents?.toLocaleString() || 0,
            },
            {
              label: "Staff",
              value: counts?.users?.totalStaff?.toLocaleString() || 0,
            },
          ]}
        />
      </section>

      {/* Registration Trend Chart */}
      <section className="grid grid-cols-1 gap-8">
        <ChartCard
          title="Institution Registration Trend"
          icon={TrendingUp}
          subtitle="Past 7 Days"
        >
          {formattedTrend.length > 0 ? (
            <ResponsiveContainer width="100%" height="100%">
              <AreaChart data={formattedTrend}>
                <defs>
                  <linearGradient id="colorReg" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%" stopColor="#2563eb" stopOpacity={0.15} />
                    <stop offset="95%" stopColor="#2563eb" stopOpacity={0} />
                  </linearGradient>
                </defs>
                <CartesianGrid
                  strokeDasharray="3 3"
                  vertical={false}
                  stroke="#f1f5f9"
                />
                <XAxis
                  dataKey="date"
                  axisLine={false}
                  tickLine={false}
                  tick={{ fill: "#94a3b8", fontSize: 12 }}
                  dy={10}
                />
                <YAxis
                  axisLine={false}
                  tickLine={false}
                  tick={{ fill: "#94a3b8", fontSize: 12 }}
                  allowDecimals={false}
                />
                <Tooltip
                  contentStyle={{
                    borderRadius: "12px",
                    border: "none",
                    boxShadow: "0 10px 15px -3px rgb(0 0 0 / 0.1)",
                  }}
                />
                <Area
                  type="monotone"
                  dataKey="registrations"
                  name="New Institutions"
                  stroke="#2563eb"
                  strokeWidth={3}
                  fillOpacity={1}
                  fill="url(#colorReg)"
                />
              </AreaChart>
            </ResponsiveContainer>
          ) : (
            <div className="h-full flex items-center justify-center">
              <Empty description="No registration trend available" />
            </div>
          )}
        </ChartCard>
      </section>

      {/* Recent Activity Section */}
      <section className="grid grid-cols-1 gap-8">
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
          <div className="p-6 border-b border-gray-50 flex justify-between items-center">
            <h3 className="text-lg font-bold flex items-center text-gray-900">
              <UserCheck className="w-5 h-5 mr-3 text-emerald-500" /> Recent Registered Institutions
            </h3>
            <button
              onClick={() => navigate(ROUTE_CONSTANTS.Institutions)}
              className="text-sm font-bold text-brand-blue hover:text-blue-700 transition-colors"
            >
              View All Institutions
            </button>
          </div>

          <div className="overflow-x-auto">
            {recentInstitutions && recentInstitutions.length > 0 ? (
              <table className="min-w-full">
                <thead className="bg-slate-50/50 text-xs text-slate-500 uppercase tracking-widest">
                  <tr>
                    <th className="px-8 py-4 text-left font-bold">Institution</th>
                    <th className="px-8 py-4 text-left font-bold">Verification Status</th>
                    <th className="px-8 py-4 text-center font-bold">Students</th>
                    <th className="px-8 py-4 text-center font-bold">Staff</th>
                    <th className="px-8 py-4 text-right font-bold">Registered At</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-50">
                  {recentInstitutions.map((inst: any) => (
                    <tr
                      key={inst.id}
                      className="hover:bg-slate-50/50 transition-colors group"
                    >
                      <td className="px-8 py-5">
                        <div className="flex items-center gap-3">
                          <div className="w-10 h-10 rounded-full bg-indigo-50 flex items-center justify-center text-indigo-600 font-bold group-hover:scale-110 transition-transform">
                            {inst.institutionName?.[0] || "I"}
                          </div>
                          <div>
                            <p className="font-bold text-slate-800">
                              {inst.institutionName}
                            </p>
                            <p className="text-xs text-slate-400 font-medium">
                              {inst.email}
                            </p>
                          </div>
                        </div>
                      </td>
                      <td className="px-8 py-5">
                        <Tag
                          color={inst.isVerified ? "green" : "orange"}
                          className="rounded-full px-3"
                        >
                          {inst.isVerified ? "VERIFIED" : "PENDING"}
                        </Tag>
                      </td>
                      <td className="px-8 py-5 text-center">
                        <span className="font-bold text-slate-700">
                          {inst.totalStudents}
                        </span>
                      </td>
                      <td className="px-8 py-5 text-center">
                        <span className="font-bold text-slate-700">
                          {inst.totalStaff}
                        </span>
                      </td>
                      <td className="px-8 py-5 text-right">
                        <div className="flex flex-col items-end">
                          <span className="text-sm font-bold text-slate-600 flex items-center gap-1.5">
                            <Clock size={14} className="text-slate-400" />
                            {dayjs(inst.createdAt).format("DD/MM/YYYY")}
                          </span>
                          <span className="text-[10px] text-slate-400 font-bold uppercase mt-1">
                            {dayjs(inst.createdAt).format("hh:mm A")}
                          </span>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            ) : (
              <div className="py-20 flex justify-center">
                <Empty description="No recent institutions found" />
              </div>
            )}
          </div>
        </div>
      </section>
    </div>
  );
};

export default memo(AdminDashboard);
