import React, { memo } from "react";
import {
  Users,
  FileText,
  HelpCircle,
  TrendingUp,
  CheckCircle,
  Clock,
  Search,
  ArrowRight,
  BarChart2,
  UserCheck,
  Wallet,
  CreditCard
} from "lucide-react";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  AreaChart,
  Area,
  LineChart,
  Line,
  Legend,
} from "recharts";
import { useNavigate } from "react-router-dom";
import ROUTE_CONSTANTS from "@/constants/route.constants";
import { useQuery, keepPreviousData } from "@tanstack/react-query";
import { API_Instance } from "@/api/axios.instance";
import API_Constants from "@/constants/api.constants";
import { Spin, Tag, Empty } from "antd";
import dayjs from "dayjs";

// -------------------------------------
// Reusable Stat Card
// -------------------------------------
const StatCard = memo(
  ({ title, value, icon: Icon, color, subtext, footerData, onCardClick, onTitleValueClick }: any) => {
    return (
      <div
        onClick={onCardClick ? onCardClick : undefined}
        className={`bg-white rounded-xl p-6 shadow-sm border border-gray-100 flex flex-col hover:shadow-md transition-shadow ${onCardClick ? "cursor-pointer select-none" : ""
          }`}
      >
        <div className="flex items-start justify-between">
          <div
            onClick={(e) => {
              if (onTitleValueClick) {
                e.stopPropagation();
                onTitleValueClick();
              }
            }}
            className={onTitleValueClick ? "cursor-pointer group/title select-none" : ""}
          >
            <p className={`text-sm text-gray-500 font-medium ${onTitleValueClick ? "group-hover/title:text-gray-700 transition-colors" : ""}`}>
              {title}
            </p>
            <h3 className={`text-3xl font-bold text-gray-900 mt-1 ${onTitleValueClick ? "group-hover/title:underline decoration-2" : ""}`}>
              {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-4 gap-2 text-sm">
            {footerData.map((f: any, i: number) => (
              <div
                key={i}
                onClick={(e) => {
                  if (f.onClick) {
                    e.stopPropagation();
                    f.onClick();
                  }
                }}
                className={f.onClick ? "cursor-pointer hover:opacity-80 transition-opacity select-none" : ""}
              >
                <p className="text-xs text-gray-400 capitalize hover:underline">{f.label}</p>
                <p className="font-semibold text-gray-700">{f.value}</p>
              </div>
            ))}
          </div>
        )}
      </div>
    )
  }
);

// Original Chart Card layout
const ChartCard = memo(({ title, icon: Icon, subtitle, rightAction, children }: any) => (
  <div className="bg-white p-6 rounded-xl shadow-sm border border-gray-100 h-full">
    <div className="flex justify-between items-center mb-4">
      <div className="flex items-center justify-between w-full gap-4">
        <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>
      {rightAction && <div>{rightAction}</div>}
    </div>
    <div className="h-72">{children}</div>
  </div>
));

// -------------------------------------
// Main Component
// -------------------------------------
const InstitutionDashboardPage: React.FC = () => {
  const navigate = useNavigate();

  const {
    data: stats,
    isLoading,
    error,
  } = useQuery({
    queryKey: ["institutionDashboardStats"],
    queryFn: async () => {
      const res = await API_Instance.get(
        `${API_Constants.dashboard}/institution`
      );
      return res.data.data;
    },
    placeholderData: keepPreviousData,
  });

  const subscriptionTrend = Array.isArray((stats as any)?.studentSubscriptionTrend)
    ? (stats as any).studentSubscriptionTrend
    : [];
  const subscriptionLoading = isLoading;

  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>
    );
  }

  if (error) {
    return (
      <div className="p-12 flex justify-center">
        <div className="bg-red-50 border border-red-100 p-6 rounded-2xl text-center max-w-md">
          <p className="text-red-600 font-semibold mb-2">
            Failed to load analytics
          </p>
          <p className="text-red-500 text-sm">
            There was an error connecting to the server. Please check your
            connection and try again.
          </p>
        </div>
      </div>
    );
  }

  const { counts = {}, recentResults = [], questionsBySubject = [], trend = [] } = stats || {};

  const studentTotal = counts?.students?.total ?? (Number(counts?.students) || 0);
  const testTotal = counts?.tests?.total ?? (Number(counts?.tests) || 0);
  const staffTotal = counts?.staff?.total ?? (Number(counts?.staff) || 0);

  const formattedTrend = trend.map((t: any) => ({
    date: dayjs(t.date).format("DD MMM"),
    submissions: t.count,
  }));

  const formattedSubscriptionTrend = subscriptionTrend.map((t: any) => ({
    date: dayjs(t.date).format("DD MMM"),
    registered: t.registeredCount ?? t.registered ?? 0,
    subscribed: t.activeSubscriptionCount ?? t.subscribed ?? 0,
  }));

  const formattedSubjects = questionsBySubject.map((s: any) => ({
    subject: s.subjectName,
    questions: s.count,
  }));

  const getExamTypeTag = (type: string) => {
    switch (type?.toUpperCase()) {
      case "PRACTICE":
        return <Tag color="blue" className="rounded-full px-3 font-semibold">PRACTICE</Tag>;
      case "MOCK":
        return <Tag color="purple" className="rounded-full px-3 font-semibold">MOCK TEST</Tag>;
      case "OQP":
      case "PYQ":
        return <Tag color="orange" className="rounded-full px-3 font-semibold">PYQ TEST</Tag>;
      default:
        return <Tag color="default" className="rounded-full px-3 font-semibold">{type || "TEST"}</Tag>;
    }
  };

  return (
    <div className="w-full max-w-[1600px] 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">
          Institution Dashboard
        </h2>
        <p className="text-gray-500 font-medium">
          Welcome back! Here's an overview of your institution's performance.
        </p>
      </header>

      {/* Stats Cards Layout */}
      <section className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {/* Card 1: Total Students */}
        <StatCard
          title="Total Students"
          value={studentTotal}
          icon={Users}
          color="bg-orange-500"
          onCardClick={() => navigate(ROUTE_CONSTANTS.Students)}
          footerData={[
            { label: "verified", value: counts?.students?.verified ?? 0, onClick: () => navigate(ROUTE_CONSTANTS.Students, { state: { isVerified: "true" } }) },
            { label: "pending", value: counts?.students?.pending ?? 0, onClick: () => navigate(ROUTE_CONSTANTS.Students, { state: { isVerified: "false" } }) },
            { label: "active", value: counts?.students?.paid ?? 0, onClick: () => navigate(ROUTE_CONSTANTS.Students, { state: { planStatus: "ACTIVE" } }) },
            { label: "expired", value: counts?.students?.expired ?? 0, onClick: () => navigate(ROUTE_CONSTANTS.Students, { state: { planStatus: "EXPIRED" } }) },
          ]}
        />

        {/* Card 2: Total Staff */}
        <StatCard
          title="Total Staffs"
          value={staffTotal.toLocaleString()}
          icon={HelpCircle}
          color="bg-blue-600"
          onCardClick={() => navigate(ROUTE_CONSTANTS.Staffs)}
          footerData={[
            { label: "verified", value: counts?.staff?.verified ?? 0, onClick: () => navigate(ROUTE_CONSTANTS.Staffs, { state: { isVerified: "true" } }) },
            { label: "pending", value: counts?.staff?.pending ?? 0, onClick: () => navigate(ROUTE_CONSTANTS.Staffs, { state: { isVerified: "false" } }) },
          ]}
        />

        {/* Card 3: Total Tests */}
        <StatCard
          title="Total Tests"
          value={testTotal}
          icon={FileText}
          color="bg-emerald-500"
          onTitleValueClick={null}
          footerData={[
            {
              label: "practice test",
              value: counts?.tests?.practiceTest ?? 0,
              onClick: () => navigate(ROUTE_CONSTANTS.QuestionBank)
            },
            {
              label: "mock test",
              value: counts?.tests?.mockTest ?? 0,
              onClick: () => navigate(ROUTE_CONSTANTS.MockTest || ROUTE_CONSTANTS.PracticeTest)
            },
            {
              label: "PYQs test",
              value: counts?.tests?.pyqTest ?? counts?.tests?.OldQuestionsPapers ?? 0,
              onClick: () => navigate(ROUTE_CONSTANTS.OldQuestionsPapers || ROUTE_CONSTANTS.PracticeTest)
            },
          ]}
        />
      </section>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        {/* Overall Performance Card */}
        <div
          onClick={() => navigate(ROUTE_CONSTANTS.Reports)}
          className="group bg-gradient-to-br from-blue-50/50 via-white to-white rounded-2xl p-6 border border-blue-100/60 shadow-sm hover:shadow-md transition-all cursor-pointer flex flex-col justify-between"
        >
          <div>
            <div className="flex items-center justify-between">
              <span className="p-3 text-blue-800 bg-blue-100 rounded-xl">
                <BarChart2 className="w-5 h-5" />
              </span>
              <span className="text-xs font-semibold text-blue-600 group-hover:translate-x-1 transition-transform flex items-center gap-1">
                Explore <ArrowRight className="w-3.5 h-3.5" />
              </span>
            </div>
            <h4 className="font-bold text-gray-900 text-base mt-4">
              Overall Student Performance
            </h4>
            <p className="text-xs text-gray-500 mt-1 leading-relaxed">
              Review institutional progress and track benchmarks over time.
            </p>
          </div>
          <div className="flex gap-2 mt-5 text-[10px] font-semibold text-blue-700 uppercase">
            <span className="bg-blue-100/60 rounded-md px-2 py-0.5">Practice</span>
            <span className="bg-blue-100/60 rounded-md px-2 py-0.5">Mock</span>
            <span className="bg-blue-100/60 rounded-md px-2 py-0.5">PYQ</span>
          </div>
        </div>

        {/* Individual Performance Card */}
        <div
          onClick={() => navigate(ROUTE_CONSTANTS.ProgressOverview)}
          className="group bg-gradient-to-br from-emerald-50/50 via-white to-white rounded-2xl p-6 border border-emerald-100/60 shadow-sm hover:shadow-md transition-all cursor-pointer flex flex-col justify-between"
        >
          <div>
            <div className="flex items-center justify-between">
              <span className="p-3 text-emerald-600 bg-emerald-100/60 rounded-xl">
                <UserCheck className="w-5 h-5" />
              </span>
              <span className="text-xs font-semibold text-emerald-600 group-hover:translate-x-1 transition-transform flex items-center gap-1">
                Explore <ArrowRight className="w-3.5 h-3.5" />
              </span>
            </div>
            <h4 className="font-bold text-gray-900 text-base mt-4">
              Individual Student Evaluations
            </h4>
            <p className="text-xs text-gray-500 mt-1 leading-relaxed">
              Analyze individual student performance records using comparisons.
            </p>
          </div>
          <div className="flex gap-2 mt-5 text-[10px] font-semibold text-emerald-700 uppercase">
            <span className="bg-emerald-100/60 rounded-md px-2 py-0.5">Practice</span>
            <span className="bg-emerald-100/60 rounded-md px-2 py-0.5">Mock</span>
            <span className="bg-emerald-100/60 rounded-md px-2 py-0.5">PYQ</span>
          </div>
        </div>

        {/* Payment Card */}
        <div
          onClick={() => navigate(ROUTE_CONSTANTS.Payments)}
          className="group bg-gradient-to-br from-purple-50/50 via-white to-white rounded-2xl p-6 border border-purple-100/60 shadow-sm hover:shadow-md transition-all cursor-pointer flex flex-col justify-between"
        >
          <div>
            <div className="flex items-center justify-between">
              <span className="p-3 text-orange-600 bg-orange-100/60 rounded-xl">
                <CreditCard className="w-5 h-5" />
              </span>
              <span className="text-xs font-semibold text-orange-600 group-hover:translate-x-1 transition-transform flex items-center gap-1">
                Explore <ArrowRight className="w-3.5 h-3.5" />
              </span>
            </div>
            <h4 className="font-bold text-gray-900 text-base mt-4">
              Payment History & Billing
            </h4>
            <p className="text-xs text-gray-500 mt-1 leading-relaxed">
              Access billing receipts, subscription plans, and transaction statuses.
            </p>
          </div>
          <div className="flex gap-2 mt-5 text-[10px] font-semibold text-orange-700 uppercase">
            <span className="bg-orange-100/60 rounded-md px-2 py-0.5">Receipts</span>
            <span className="bg-orange-100/60 rounded-md px-2 py-0.5">Plans</span>
            <span className="bg-orange-100/60 rounded-md px-2 py-0.5">History</span>
          </div>
        </div>
      </div>

      <section className="grid grid-cols-2 gap-6 items-stretch">
        {/* Chart 1 - Submissions Trend */}
        <ChartCard
          title="Submissions Trend"
          icon={TrendingUp}
          subtitle="Last 7 Days"
        >
          {formattedTrend.length > 0 ? (
            <ResponsiveContainer width="100%" height="100%">
              <AreaChart data={formattedTrend} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
                <defs>
                  <linearGradient id="colorSub" 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 }}
                />
                <Tooltip
                  contentStyle={{
                    borderRadius: "12px",
                    border: "none",
                    boxShadow: "0 10px 15px -3px rgb(0 0 0 / 0.1)",
                  }}
                />
                <Area
                  type="monotone"
                  dataKey="submissions"
                  stroke="#2563eb"
                  strokeWidth={3}
                  fillOpacity={1}
                  fill="url(#colorSub)"
                />
              </AreaChart>
            </ResponsiveContainer>
          ) : (
            <div className="h-full flex items-center justify-center">
              <Empty description="No submission data available yet" />
            </div>
          )}
        </ChartCard>

        {/* Chart 2 - Subscription Analytics */}
        <ChartCard
          title="Subscription Analytics"
          icon={Wallet}
          subtitle="Last 7 Days"
        >
          {subscriptionLoading ? (
            <div className="h-full flex items-center justify-center">
              <Spin />
            </div>
          ) : formattedSubscriptionTrend.length > 0 ? (
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={formattedSubscriptionTrend} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
                <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 }}
                />
                <Tooltip
                  contentStyle={{
                    borderRadius: "12px",
                    border: "none",
                    boxShadow: "0 10px 15px -3px rgb(0 0 0 / 0.1)",
                  }}
                  formatter={(value: any) => value.toLocaleString()}
                />
                <Legend
                  wrapperStyle={{ paddingTop: "20px" }}
                  iconType="line"
                />
                <Line
                  type="monotone"
                  dataKey="registered"
                  stroke="#2563eb"
                  strokeWidth={3}
                  name="Registered Students"
                  dot={{ fill: "#2563eb", r: 2 }}
                  activeDot={{ r: 4 }}
                />
                <Line
                  type="monotone"
                  dataKey="subscribed"
                  stroke="#10b981"
                  strokeWidth={3}
                  name="Active Subscriptions"
                  dot={{ fill: "#10b981", r: 2 }}
                  activeDot={{ r: 4 }}
                />
              </LineChart>
            </ResponsiveContainer>
          ) : (
            <div className="h-full flex items-center justify-center">
              <Empty description="No subscription data available yet" />
            </div>
          )}
        </ChartCard>

        {/* Chart 2 - Questions by Subject */}
        {/* <ChartCard
          title="Questions by Subject"
          icon={Search}
          subtitle="Top Categories"
        >
          {formattedSubjects.length > 0 ? (
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={formattedSubjects} layout="vertical">
                <CartesianGrid
                  strokeDasharray="3 3"
                  horizontal={false}
                  stroke="#f1f5f9"
                />
                <XAxis type="number" hide />
                <YAxis
                  dataKey="subject"
                  type="category"
                  axisLine={false}
                  tickLine={false}
                  width={100}
                  tick={{ fill: "#475569", fontSize: 12, fontWeight: 500 }}
                />
                <Tooltip
                  cursor={{ fill: "#f8fafc" }}
                  contentStyle={{
                    borderRadius: "12px",
                    border: "none",
                    boxShadow: "0 10px 15px -3px rgb(0 0 0 / 0.1)",
                  }}
                />
                <Bar
                  dataKey="questions"
                  fill="#10b981"
                  radius={[0, 4, 4, 0]}
                  barSize={20}
                />
              </BarChart>
            </ResponsiveContainer>
          ) : (
            <div className="h-full flex items-center justify-center">
              <Empty description="No question data available" />
            </div>
          )}
        </ChartCard> */}
      </section>

      {/* Recent Activity Section */}
      <section className="w-full 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">
              <CheckCircle className="w-5 h-5 mr-3 text-emerald-500" /> Recent
              Test Submissions
            </h3>
            <button
              onClick={() => navigate(ROUTE_CONSTANTS.Reports)}
              className="text-sm font-bold text-brand-blue hover:text-blue-700 transition-colors"
            >
              View Detailed Reports
            </button>
          </div>

          <div className="overflow-x-auto">
            {recentResults.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">Student</th>
                    <th className="px-8 py-4 text-left font-bold">Exam Name</th>
                    <th className="px-8 py-4 text-left font-bold">Test Type</th>
                    <th className="px-8 py-4 text-left font-bold">Test Title</th>
                    <th className="px-8 py-4 text-center font-bold">Score</th>
                    <th className="px-8 py-4 text-right font-bold">Submitted At</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-50">
                  {recentResults.map((result: any) => (
                    <tr
                      key={result.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">
                            {result.studentId?.firstName?.[0] || "S"}
                          </div>
                          <div>
                            <p className="font-bold text-slate-800">
                              {result.studentId?.firstName}{" "}
                              {result.studentId?.lastName}
                            </p>
                            <p className="text-xs text-slate-400 font-medium">
                              {result.studentId?.email}
                            </p>
                          </div>
                        </div>
                      </td>
                      <td className="px-8 py-5">
                        <span className="font-semibold text-slate-700">
                          {result.examName}
                        </span>
                      </td>
                      <td className="px-8 py-5">
                        {getExamTypeTag(result.examType)}
                      </td>
                      <td className="px-8 py-5">
                        <span className="font-semibold text-slate-700">
                          {result.testId?.title}
                        </span>
                      </td>
                      <td className="px-8 py-5 text-center">
                        <Tag
                          color={
                            result.obtainedMarks / result.totalMarks >= 0.8
                              ? "green"
                              : result.obtainedMarks / result.totalMarks >= 0.5
                                ? "orange"
                                : "red"
                          }
                          className="rounded-lg border-none font-bold px-3 py-0.5"
                        >
                          {result.obtainedMarks} / {result.totalMarks}
                        </Tag>
                      </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(result.createdAt).format("DD/MM/YYYY")}
                          </span>
                          <span className="text-[10px] text-slate-400 font-bold uppercase mt-1">
                            {dayjs(result.createdAt).format("hh:mm A")}
                          </span>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            ) : (
              <div className="py-20 flex justify-center">
                <Empty description="No recent submissions found" />
              </div>
            )}
          </div>
        </div>
      </section>
    </div>
  );
};

export default memo(InstitutionDashboardPage);
