import dayjs from "dayjs";
import toast from "react-hot-toast";
import { useAuth } from "@/hooks/useAuth";
import { useNavigate } from "react-router-dom";
import type { ColumnsType } from "antd/es/table";
import { useDebounce } from "@/hooks/useDebounce";
import React, { useEffect, useState } from "react";
import { API_Instance } from "@/api/axios.instance";
import { Role } from "@/constants/navLink.constants";
import API_Constants from "@/constants/api.constants";
import ROUTE_CONSTANTS from "@/constants/route.constants";
import { getAxiosErrorMessage } from "@/utils/index.utils";
import { ISubscriptionPlan, IStaffMember } from "@/types";
import { fetchLanguageOptions } from "@/hooks/useLanguageOptions";
import { Card, Select, Table, Tag, Pagination, Input, Button, Empty, Skeleton, DatePicker, Tooltip } from "antd";
import { Search, Users, CheckCircle, XCircle, BarChart3, Mail, Phone, CreditCard, Download } from "lucide-react";

import Modal from "@/components/shared/Modal";

interface IStudentRow {
  id: string;
  studentName: string;
  email: string;
  phone: string;
  examName: string;
  language: string;
  isVerified: boolean;
  registrationDate: string;
  subscriptionStatus: string | null;
  planName: string;
  expiryDate: string | null;
  subscription?: {
    status: string;
    amount: number;
    startDate: string;
    endDate: string | null;
    trialEndsAt: string | null;
  } | null;
  subscriptionPlan?: {
    planName: string;
    planType: string;
    duration: number;
  } | null;
}

interface IStats {
  totalEnrolled: number;
  verifiedCount: number;
  pendingCount: number;
  paidCount: number;
  expiredCount: number;
}

const paginationInitial = { page: 1, limit: 10, total: 0, totalPages: 0 };

const filterInitial = {
  search: "",
  isVerified: undefined,
  planType: undefined,
  planStatus: undefined,
  examId: undefined,
  language: undefined,
  regStartDate: undefined,
  regEndDate: undefined,
};

const ProgressOverview: React.FC = () => {
  const { user } = useAuth();
  const navigate = useNavigate();
  const [languageOptions, setLanguageOptions] = useState<any[]>([]);
  const isAdmin = user.role === Role.ADMIN;
  const isInstitution = user.role === Role.INSTITUTION || user.role === Role.STAFF;

  const [filterValues, setFilterValues] = useState({
    ...filterInitial,
    institutionId: undefined as string | undefined,
  });

  const debouncedSearch = useDebounce(filterValues.search, 600);

  const [subscriptions, setSubscriptions] = useState<ISubscriptionPlan[]>([]);

  useEffect(() => {
    const loadLanguages = async () => {
      try {
        const options = await fetchLanguageOptions();
        setLanguageOptions(options);
      } catch {
        setLanguageOptions([]);
      }
    };

    void loadLanguages();
  }, []);
  const [institutions, setInstitutions] = useState<{ id: string; name: string }[]>([]);
  const [instSearch, setInstSearch] = useState("");
  const debouncedInstSearch = useDebounce(instSearch, 500);
  const [instPage, setInstPage] = useState(1);
  const [hasMoreInst, setHasMoreInst] = useState(true);
  const [loadingInst, setLoadingInst] = useState(false);

  const [exams, setExams] = useState<{ id: string; examName: string }[]>([]);
  const [examSearch, setExamSearch] = useState("");
  const debouncedExamSearch = useDebounce(examSearch, 500);
  const [examPage, setExamPage] = useState(1);
  const [hasMoreExams, setHasMoreExams] = useState(true);
  const [loadingExams, setLoadingExams] = useState(false);

  const [students, setStudents] = useState<IStudentRow[]>([]);
  const [staffs, setStaffs] = useState<IStaffMember[]>([]);
  const [stats, setStats] = useState<IStats | null>(null);
  const [loading, setLoading] = useState(false);
  const [exportLoading, setExportLoading] = useState(false);
  const [pagination, setPagination] = useState(paginationInitial);
  const [entityType, setEntityType] = useState<"student" | "staff">("student");
  const [isSubscriptionModalOpen, setIsSubscriptionModalOpen] = useState(false);
  const [viewingSubscription, setViewingSubscription] = useState<IStudentRow | null>(null);

  const fetchSubscriptions = React.useCallback(async (institutionId?: string) => {
    try {
      const params: any = { limit: 1000, includeHidden: true };
      if (isAdmin && institutionId) {
        params.institutionId = institutionId;
      }
      const res = await API_Instance.get(API_Constants.subscriptionPlans, {
        params,
      });
      setSubscriptions(res.data?.data ?? res.data ?? []);
    } catch (error) {
      console.error("Error fetching subscriptions:", error);
    }
  }, [isAdmin]);

  const fetchInstitutions = async (search = "", page = 1) => {
    setLoadingInst(true);
    try {
      const res = await API_Instance.get(API_Constants.institutionsList, {
        params: { search, page, limit: 10 },
      });
      const newInst = res.data.data || [];
      setInstitutions((prev) => (page === 1 ? newInst : [...prev, ...newInst]));
      setHasMoreInst(newInst.length === 10);
    } catch (e) {
      console.error(e);
    } finally {
      setLoadingInst(false);
    }
  };

  const fetchExams = async (search = "", page = 1, instId?: string) => {
    setLoadingExams(true);
    try {
      const params: any = { search, page, limit: 10 };
      if (instId) params.institutionId = instId;
      const res = await API_Instance.get(API_Constants.exams, { params });
      const newExams = res.data.data || [];
      setExams((prev) => (page === 1 ? newExams : [...prev, ...newExams]));
      setHasMoreExams(newExams.length === 10);
    } catch (e) {
      console.error(e);
    } finally {
      setLoadingExams(false);
    }
  };

  const fetchReport = async (
    page = 1,
    limit = 10,
    overrides: Record<string, any> = {}
  ) => {
    setLoading(true);
    try {
      const params: any = {
        page,
        limit,
        search: filterValues.search,
        examId: filterValues.examId,
        planStatus: filterValues.planStatus,
        planType: filterValues.planType,
        isVerified: filterValues.isVerified,
        language: filterValues.language,
        regStartDate: filterValues.regStartDate,
        regEndDate: filterValues.regEndDate,
        ...overrides,
      };
      if (isAdmin && filterValues.institutionId) {
        params.institutionId = filterValues.institutionId;
      }

      if (entityType !== "student") {
        delete params.planType;
        delete params.planStatus;
        delete params.planName;
        delete params.language;
      }

      const endpoint = entityType === "staff" ? API_Constants.staff : API_Constants.studentStats;
      const res = await API_Instance.get(endpoint, { params });
      if (entityType === "staff") {
        const data = res.data.data || [];
        setStaffs(data);
        setStudents([]);
        setStats({
          totalEnrolled: res.data.meta?.total || data.length,
          verifiedCount: data.filter((staff: any) => staff.isVerified).length,
          pendingCount: data.filter((staff: any) => !staff.isVerified).length,
          paidCount: 0,
          expiredCount: 0,
        });
        setPagination(res.data.meta || paginationInitial);
      } else {
        const data = res.data.data || [];
        setStudents(data);
        setStaffs([]);
        setStats(res.data.stats || null);
        setPagination(res.data.meta || paginationInitial);
      }
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
    } finally {
      setLoading(false);
    }
  };

  const handleExportPDF = async () => {
    if ((entityType === "staff" && staffs.length === 0) || (entityType === "student" && students.length === 0)) {
      toast.error("No data available to export.");
      return;
    }
    setExportLoading(true);
    try {
      const endpoint = entityType === "staff" ? `${API_Constants.reports}/staffs-report-pdf` : `${API_Constants.reports}/students-report-pdf`;
      const fileName = entityType === "staff" ? `Exam_Staff_Report_${dayjs().format("YYYY-MM-DD")}.pdf` : `Exam_Student_Report_${dayjs().format("YYYY-MM-DD")}.pdf`;
      const res = await API_Instance.get(endpoint, {
        params: {
          search: filterValues.search,
          examId: filterValues.examId,
          planType: filterValues.planType,
          planStatus: filterValues.planStatus,
          isVerified: filterValues.isVerified,
          language: filterValues.language,
          regStartDate: filterValues.regStartDate,
          regEndDate: filterValues.regEndDate,
          institutionId: filterValues.institutionId,
        },
        responseType: "blob",
      });

      const blobUrl = window.URL.createObjectURL(new Blob([res.data], { type: "application/pdf" }));
      const link = document.createElement("a");
      link.href = blobUrl;
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(blobUrl);
      toast.success("PDF downloaded successfully.");
    } catch (error) {
      console.error(`Failed to download ${entityType} report PDF:`, error);
      toast.error("Failed to export PDF report.");
    } finally {
      setExportLoading(false);
    }
  };

  useEffect(() => {
    fetchSubscriptions(filterValues.institutionId);
  }, [fetchSubscriptions, filterValues.institutionId]);

  useEffect(() => {
    if (!isAdmin) return;
    setInstPage(1);
    fetchInstitutions(debouncedInstSearch, 1);
  }, [debouncedInstSearch]);

  useEffect(() => {
    if (!isAdmin || instPage <= 1) return;
    fetchInstitutions(debouncedInstSearch, instPage);
  }, [instPage]);

  useEffect(() => {
    setFilterValues((prev) => ({ ...prev, examId: undefined, planType: undefined }));
    setExams([]);
    setExamPage(1);
    fetchExams(debouncedExamSearch, 1, filterValues.institutionId);
  }, [filterValues.institutionId]);

  useEffect(() => {
    setExamPage(1);
    setExams([]);
    fetchExams(debouncedExamSearch, 1, filterValues.institutionId);
  }, [debouncedExamSearch]);

  useEffect(() => {
    if (examPage <= 1) return;
    fetchExams(debouncedExamSearch, examPage, filterValues.institutionId);
  }, [examPage]);

  useEffect(() => {
    if (!isAdmin) {
      fetchReport(1, pagination.limit, { search: debouncedSearch });
    } else if (entityType === "student" && filterValues.institutionId) {
      fetchReport(1, pagination.limit, { search: debouncedSearch });
    } else if (entityType === "staff" && filterValues.institutionId) {
      fetchReport(1, pagination.limit, { search: debouncedSearch });
    } else {
      setStudents([]);
      setStaffs([]);
      setStats(null);
    }
  }, [
    entityType,
    debouncedSearch,
    filterValues.examId,
    filterValues.planStatus,
    filterValues.planType,
    filterValues.isVerified,
    filterValues.language,
    filterValues.regStartDate,
    filterValues.regEndDate,
    filterValues.institutionId,
  ]);

  const studentColumns: ColumnsType<IStudentRow> = [
    {
      title: "Student Name",
      key: "studentName",
      width: isInstitution ? "25%" : 200,
      fixed: isInstitution ? undefined : ("left" as const),
      render: (_, r) => (
        <div className="flex flex-col gap-1">
          <span className="font-semibold text-slate-700">{r.studentName}</span>
        </div>
      ),
    },
    {
      title: "Email & Phone",
      key: "emailPhone",
      width: isInstitution ? "35%" : "300px",
      render: (_, r) => (
        <div className="flex flex-col gap-1 text-sm text-slate-600">
          <div className="flex items-center gap-1">
            <Mail size={14} className="text-slate-400" />
            <span>{r.email}</span>
          </div>
          {r.phone && r.phone !== "—" && (
            <div className="flex items-center gap-1">
              <Phone size={14} className="text-slate-400" />
              <span className="text-sm">{r.phone}</span>
            </div>
          )}
        </div>
      ),
    },
    ...(!isInstitution
      ? [
          {
            title: "Verified",
            key: "verified",
            render: (_, r: IStudentRow) => (
              <Tag
                color={r.isVerified ? "success" : "warning"}
                className="flex w-fit items-center gap-1"
              >
                {r.isVerified ? (
                  <CheckCircle size={12} />
                ) : (
                  <XCircle size={12} />
                )}
                {r.isVerified ? "Verified" : "Pending"}
              </Tag>
            ),
          },
        ]
      : []),
    {
      title: "Exam",
      dataIndex: "examName",
      key: "examName",
      width: isInstitution ? "25%" : undefined,
      render: (text, r) => (
        <div className="flex flex-col gap-1 text-slate-600">
          <span className="text-xs">{text}</span>
          <Tag
            color="blue"
            className="w-max text-[10px] border-none rounded-full"
          >
            {r.language}
          </Tag>
        </div>
      ),
    },
    ...(!isInstitution
      ? [
          {
            title: "Subscription",
            key: "subscription",
            render: (_, r: IStudentRow) => (
              <div className="flex flex-col gap-1 text-sm text-slate-600">
                {!r.subscriptionStatus ? (
                  <Tag color="error" className="flex w-fit items-center gap-1">
                    <XCircle size={12} />
                    No Subscription Found
                  </Tag>
                ) : (
                  <>
                    <div className="flex items-center gap-2">
                      <span className="font-medium">{r.planName || "N/A"}</span>
                      <Tag
                        color={
                          r.subscriptionStatus === "ACTIVE"
                            ? "success"
                            : r.subscriptionStatus === "EXPIRED"
                              ? "error"
                              : "warning"
                        }
                        className="m-0 px-2 py-0 text-[10px] uppercase font-bold rounded-full"
                      >
                        {r.subscriptionStatus}
                      </Tag>
                    </div>
                    <div className="flex items-center gap-2 mt-1">
                      <Button
                        type="link"
                        size="small"
                        className="p-0 h-auto text-[12px] flex items-center gap-1 w-fit"
                        onClick={() => {
                          setViewingSubscription(r);
                          setIsSubscriptionModalOpen(true);
                        }}
                      >
                        View Details
                      </Button>
                    </div>
                  </>
                )}
              </div>
            ),
          },
          {
            title: "Registration Date",
            key: "registrationDate",
            render: (_, r: IStudentRow) => (
              <span className="text-xs text-slate-500 italic">
                {dayjs(r.registrationDate).format("DD-MM-YYYY HH:mm:ss A")}
              </span>
            ),
          },
          {
            title: "Valid Till",
            key: "expiryDate",
            render: (_, r: IStudentRow) => (
              <span className="text-xs text-slate-500 italic">
                {r.expiryDate ? dayjs(r.expiryDate).format("DD-MM-YYYY HH:mm:ss A") : "N/A"}
              </span>
            ),
          },
        ]
      : []),
    ...(!isAdmin
      ? [
        {
          title: "Action",
          key: "action",
          width: isInstitution ? "15%" : 150,
          fixed: isInstitution ? undefined : ("right" as const),
          align: "center" as const,
          render: (_, r: IStudentRow) => {
            const isPending = !r.isVerified;

            const actionButton = (
              <span>
                <Button
                  type="link"
                  size="small"
                  disabled={isPending}
                  className={`font-semibold p-0 ${isPending
                    ? "text-slate-400 cursor-not-allowed"
                    : "text-blue-600 hover:text-blue-700"
                    }`}
                  onClick={() =>
                    navigate(
                      ROUTE_CONSTANTS.StudentPerformance.replace(
                        ":studentId",
                        r.id
                      )
                    )
                  }
                >
                  View Performance
                </Button>
              </span>
            );

            return isPending ? (
              <Tooltip title="Verification pending. Performance cannot be viewed yet.">
                {actionButton}
              </Tooltip>
            ) : (
              actionButton
            );
          },
        },
      ]
      : [])
  ];

  const staffColumns: ColumnsType<IStaffMember> = [
    {
      title: "Staff Name",
      key: "staffName",
      width: 200,
      fixed: "left" as const,
      render: (_, r) => (
        <div className="flex flex-col gap-1">
          <span className="font-semibold text-slate-700">{`${r.firstName} ${r.lastName || ""}`.trim()}</span>
          {r.designation && <span className="text-xs text-slate-500">{r.designation}</span>}
        </div>
      ),
    },
    {
      title: "Email & Phone",
      key: "emailPhone",
      render: (_, r) => (
        <div className="flex flex-col gap-1 text-sm text-slate-600">
          <div className="flex items-center gap-1">
            <Mail size={14} className="text-slate-400" />
            <span>{r.email}</span>
          </div>
          {r.phone && (
            <div className="flex items-center gap-1">
              <Phone size={14} className="text-slate-400" />
              <span className="text-sm">{r.phone}</span>
            </div>
          )}
        </div>
      ),
    },
    {
      title: "Role",
      dataIndex: "roleName",
      key: "roleName",
      render: (text) => <span className="text-slate-600">{text || "Staff"}</span>,
    },
    {
      title: "Joined",
      key: "joinedDate",
      render: (_, r) => {
        const joinedValue = r.createdAt || r.registrationDate;
        return (
          <span className="text-xs text-slate-500 italic">
            {joinedValue ? dayjs(joinedValue).format("DD-MM-YYYY HH:mm:ss A") : "N/A"}
          </span>
        );
      },
    },
    {
      title: "Status",
      key: "verified",
      render: (_, r) => (
        <Tag
          color={r.isVerified ? "success" : "warning"}
          className="flex w-fit items-center gap-1"
        >
          {r.isVerified ? <CheckCircle size={12} /> : <XCircle size={12} />}
          {r.isVerified ? "Verified" : "Pending"}
        </Tag>
      ),
    },
  ];

  const columns: ColumnsType<any> = entityType === "staff" ? staffColumns : studentColumns;

  const StatCard = ({
    icon,
    label,
    value,
    color,
  }: {
    icon: React.ReactNode;
    label: string;
    value: number;
    color: string;
  }) => (
    <Card className="shadow-sm border border-slate-200 rounded-xl flex-1">
      <div className="flex items-center gap-4">
        <div className={`p-3 rounded-xl ${color}`}>{icon}</div>
        <div>
          <p className="text-slate-500 text-sm">{label}</p>
          <p className="text-2xl font-bold text-slate-800">{value}</p>
        </div>
      </div>
    </Card>
  );

  return (
    <div className="flex flex-col gap-6 px-4 py-6">
      {/* Header */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <h2 className="text-2xl font-bold text-slate-800 flex items-center gap-2">
            <BarChart3 className="text-blue-600" />Progress Overview
          </h2>
          <p className="text-slate-500 text-sm mt-1">
            {isAdmin
              ? entityType === "student"
                ? "Select an institution to view student, staff enrollment & subscription stats."
                : "Select staff to view their status and verification counts."
              : "Select a student to analyze their academic performance and progress."}
          </p>
        </div>
        <Button
          type="primary"
          icon={<Download size={16} />}
          loading={exportLoading}
          onClick={handleExportPDF}
          disabled={
            exportLoading ||
            (entityType === "student" && !filterValues.examId && isAdmin && !filterValues.institutionId) ||
            (entityType === "staff" && isAdmin && !filterValues.institutionId)
          }
          className="bg-blue-600 hover:bg-blue-700 rounded-lg font-medium"
        >
          {exportLoading ? "Generating PDF..." : "Export PDF"}
        </Button>
      </div>

      {/* Filters Card */}
      <Card className="shadow-sm border border-slate-200 rounded-xl">
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-4 gap-4 mb-6 p-4 bg-slate-50 rounded-xl border border-slate-100">

          {isAdmin && (
            <Select
              placeholder="Select Institution"
              className="w-full"
              allowClear
              showSearch
              filterOption={false}
              value={filterValues.institutionId}
              loading={loadingInst}
              onSearch={(v) => setInstSearch(v)}
              onChange={(v) =>
                setFilterValues((prev) => ({ ...prev, institutionId: v }))
              }
              onPopupScroll={(e) => {
                const t = e.target as HTMLElement;
                if (
                  Math.ceil(t.scrollTop + t.offsetHeight) >= t.scrollHeight &&
                  hasMoreInst &&
                  !loadingInst
                ) {
                  setInstPage((p) => p + 1);
                }
              }}
              options={institutions.map((i) => ({ label: i.name, value: i.id }))}
            />
          )}

          {isAdmin && filterValues.institutionId && (
            <Select
              placeholder="Student / Staff"
              className="w-full"
              value={entityType}
              onChange={(value) => setEntityType(value as "student" | "staff")}
              options={[
                { label: "Student", value: "student" },
                { label: "Staff", value: "staff" },
              ]}
            />
          )}

          {(!isAdmin || filterValues.institutionId) && (
            <div className="w-full">
              <Input
                placeholder={entityType === "staff" ? "Search staff, email or phone..." : "Search student, email or phone..."}
                prefix={<Search size={16} className="text-slate-400" />}
                allowClear
                value={filterValues.search}
                onChange={(e) =>
                  setFilterValues((prev) => ({ ...prev, search: e.target.value }))
                }
                className="w-full"
              />
            </div>
          )}

          {(!isAdmin || filterValues.institutionId) && !isInstitution && (
            <Select
              placeholder="Verification Status"
              className="w-full"
              allowClear
              value={filterValues.isVerified}
              onChange={(val) =>
                setFilterValues((prev) => ({ ...prev, isVerified: val }))
              }
              options={[
                { label: "Verified", value: "true" },
                { label: "Pending", value: "false" },
              ]}
            />
          )}

          {entityType === "student" && (!isAdmin || filterValues.institutionId) && (
            <Select
              placeholder={isAdmin && !filterValues.institutionId ? "Select Exam (Select institution first)" : "Select Exam"}
              className="w-full"
              allowClear
              showSearch
              filterOption={false}
              value={filterValues.examId}
              loading={loadingExams}
              onSearch={(v) => setExamSearch(v)}
              onChange={(v) =>
                setFilterValues((prev) => ({ ...prev, examId: v }))
              }
              onPopupScroll={(e) => {
                const t = e.target as HTMLElement;
                if (
                  Math.ceil(t.scrollTop + t.offsetHeight) >= t.scrollHeight &&
                  hasMoreExams &&
                  !loadingExams
                ) {
                  setExamPage((p) => p + 1);
                }
              }}
              options={exams.map((e) => ({ label: e.examName, value: e.id }))}
            />
          )}

          {entityType === "student" && (!isAdmin || filterValues.institutionId) && !isInstitution && (
            <Select
              placeholder="Subscription Plan"
              className="w-full"
              allowClear
              value={filterValues.planType}
              onChange={(val) =>
                setFilterValues((prev) => ({ ...prev, planType: val }))
              }
              options={Array.from(
                new Map(
                  subscriptions
                    .filter(p => (p.isActive || p.planType.toLowerCase() === 'trial') && p.planName && p.planType)
                    .map((plan) => [plan.planType, plan.planName])
                )
              ).map(([planType, planName]) => ({
                label: planName,
                value: planType,
              }))}
            />
          )}

          {entityType === "student" && (!isAdmin || filterValues.institutionId) && !isInstitution && (
            <Select
              placeholder="Subscription Status"
              className="w-full"
              allowClear
              value={filterValues.planStatus}
              onChange={(val) =>
                setFilterValues((prev) => ({ ...prev, planStatus: val }))
              }
              options={[
                { label: "Active", value: "ACTIVE" },
                { label: "Expired", value: "EXPIRED" },
              ]}
            />
          )}

          {entityType === "student" && (!isAdmin || filterValues.institutionId) && (
            <Select
              placeholder="Language (Mother Tongue)"
              className="w-full"
              allowClear
              value={filterValues.language}
              onChange={(val) =>
                setFilterValues((prev) => ({ ...prev, language: val }))
              }
              options={languageOptions}
            />
          )}

          {(!isAdmin || filterValues.institutionId) && !isInstitution && (
            <div className="sm:col-span-2 flex items-center justify-between gap-2 border border-slate-300 rounded-lg px-3 bg-white h-[32px] w-full">
              <DatePicker
                placeholder="Reg from"
                format="DD/MM/YYYY"
                className="border-none p-0 shadow-none flex-1 text-xs"
                value={filterValues.regStartDate ? dayjs(filterValues.regStartDate, "DD/MM/YYYY") : null}
                disabledDate={(current) => {
                  const isFuture = current && current > dayjs().endOf('day');
                  const isAfterEnd = filterValues.regEndDate
                    ? current && current > dayjs(filterValues.regEndDate, "DD/MM/YYYY").endOf('day')
                    : false;
                  return isFuture || isAfterEnd;
                }}
                onChange={(date) => {
                  setFilterValues((prev) => ({
                    ...prev,
                    regStartDate: date ? date.format("DD/MM/YYYY") : undefined,
                  }));
                }}
              />
              <span className="text-slate-300 text-xs px-1 font-medium">to</span>
              <DatePicker
                placeholder="Reg to"
                format="DD/MM/YYYY"
                className="border-none p-0 shadow-none flex-1 text-xs"
                value={filterValues.regEndDate ? dayjs(filterValues.regEndDate, "DD/MM/YYYY") : null}
                disabledDate={(current) => {
                  const isFuture = current && current > dayjs().endOf('day');
                  const isBeforeStart = filterValues.regStartDate
                    ? current && current < dayjs(filterValues.regStartDate, "DD/MM/YYYY").startOf('day')
                    : false;
                  return isFuture || isBeforeStart;
                }}
                onChange={(date) => {
                  setFilterValues((prev) => ({
                    ...prev,
                    regEndDate: date ? date.format("DD/MM/YYYY") : undefined,
                  }));
                }}
              />
            </div>
          )}

        </div>

        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 px-1">
          <div className="flex items-center gap-4">
            <Button
              type="link"
              size="small"
              className="text-slate-500 hover:text-blue-600 p-0 h-auto font-medium"
              onClick={() => {
                setFilterValues({
                  ...filterInitial,
                  institutionId: undefined,
                });
              }}
            >
              Clear All Filters
            </Button>
          </div>
        </div>
      </Card>

      {/* Stats Cards */}
      {(stats || loading) && (
        <div className={`grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 ${entityType === "student" ? "xl:grid-cols-5" : "xl:grid-cols-3"} gap-4`}>
          {loading ? (
            [1, 2, 3, 4, 5].map((k) => (
              <Card key={k} className="shadow-sm border border-slate-200 rounded-xl flex-1">
                <Skeleton active paragraph={{ rows: 1 }} />
              </Card>
            ))
          ) : stats ? (
            <>
              <StatCard
                icon={<Users size={22} className="text-blue-600" />}
                label={entityType === "staff" ? "Total Staff" : "Total Enrolled"}
                value={stats.totalEnrolled}
                color="bg-blue-50"
              />
              <StatCard
                icon={<CheckCircle size={22} className="text-green-600" />}
                label={entityType === "staff" ? "Verified Staffs" : "Verified Students"}
                value={stats.verifiedCount}
                color="bg-green-50"
              />
              <StatCard
                icon={<XCircle size={22} className="text-amber-500" />}
                label={entityType === "staff" ? "Pending Staffs" : "Pending Students"}
                value={stats.pendingCount}
                color="bg-amber-50"
              />
              {entityType === "student" && (
                <>
                  <StatCard
                    icon={<CreditCard size={22} className="text-purple-600" />}
                    label="Active Subscriptions"
                    value={stats.paidCount}
                    color="bg-purple-50"
                  />
                  <StatCard
                    icon={<XCircle size={22} className="text-red-500" />}
                    label="Expired Subscriptions"
                    value={stats.expiredCount}
                    color="bg-red-50"
                  />
                </>
              )}
            </>
          ) : null}
        </div>
      )}

      {/* Table */}
      <Card className="shadow-sm border border-slate-200 rounded-xl">
        {!stats && !loading ? (
          <Empty
            description={
              isAdmin
                ? "Select an institution to view student stats"
                : "Select an exam to view students"
            }
            className="py-16"
          />
        ) : (
          <>
            <div className="flex justify-between items-center mb-4">
              <div className="text-slate-500 text-sm font-medium bg-slate-100 px-3 py-1 rounded-md border border-slate-200">
                Total Records: <span className="font-bold text-slate-800">{pagination.total}</span>
              </div>
            </div>
            <Table
              columns={columns}
              dataSource={entityType === "staff" ? staffs : students}
              loading={loading}
              rowKey="id"
              pagination={false}
              scroll={{ x: "max-content" }}
              className="border border-slate-100 rounded-lg overflow-hidden"
            />
            <div className="flex justify-end mt-4">
              <Pagination
                current={pagination.page}
                total={pagination.total}
                pageSize={pagination.limit}
                onChange={(page, pageSize) => {
                  setPagination((prev) => ({ ...prev, page, limit: pageSize }));
                  fetchReport(page, pageSize);
                }}
                showSizeChanger
                showTotal={(total) => `Total ${total} items`}
              />
            </div>
          </>
        )}
      </Card>

      <Modal
        isOpen={isSubscriptionModalOpen}
        onClose={() => setIsSubscriptionModalOpen(false)}
        title="Subscription Details"
      >
        {viewingSubscription && (
          <div className="flex flex-col gap-4">
            <div className="bg-slate-50 p-4 rounded-lg border border-slate-100">
              <div className="flex justify-between items-center mb-4">
                <span className="text-slate-500 font-medium">
                  Plan Information
                </span>
                <Tag
                  color={
                    viewingSubscription.subscription?.status === "ACTIVE"
                      ? "success"
                      : viewingSubscription.subscription?.status === "EXPIRED"
                        ? "error"
                        : "warning"
                  }
                  className="font-bold px-3 py-1 rounded-full uppercase"
                >
                  {viewingSubscription.subscription?.status || "N/A"}
                </Tag>
              </div>
              <div className="grid grid-cols-2 gap-y-3">
                <div className="flex flex-col">
                  <span className="text-xs text-slate-400 uppercase tracking-wider">
                    Plan Name
                  </span>
                  <span className="font-semibold text-slate-700">
                    {viewingSubscription.subscriptionPlan?.planName || "Trial"}
                  </span>
                </div>
                <div className="flex flex-col">
                  <span className="text-xs text-slate-400 uppercase tracking-wider">
                    Duration
                  </span>
                  <span className="font-semibold text-slate-700">
                    {viewingSubscription.subscriptionPlan?.duration || 7} Days
                  </span>
                </div>
                <div className="flex flex-col">
                  <span className="text-xs text-slate-400 uppercase tracking-wider">
                    Amount Paid
                  </span>
                  <span className="font-semibold text-slate-700">
                    ₹{viewingSubscription.subscription?.amount || 0}
                  </span>
                </div>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="p-3 bg-white border border-slate-100 rounded-lg flex flex-col gap-1">
                <span className="text-xs text-slate-400 font-medium uppercase tracking-tight">
                  Start Date
                </span>
                <div className="flex items-center gap-2 text-slate-600">
                  <CheckCircle size={14} className="text-green-500" />
                  <span className="font-medium">
                    {viewingSubscription.subscription?.startDate
                      ? dayjs(
                        viewingSubscription.subscription.startDate,
                      ).format("DD-MM-YYYY hh:mm A")
                      : "N/A"}
                  </span>
                </div>
              </div>
              <div className="p-3 bg-white border border-slate-100 rounded-lg flex flex-col gap-1">
                <span className="text-xs text-slate-400 font-medium uppercase tracking-tight">
                  End Date
                </span>
                <div className="flex items-center gap-2 text-slate-600">
                  <XCircle size={14} className="text-red-500" />
                  <span className="font-medium">
                    {viewingSubscription.subscription?.endDate
                      ? dayjs(viewingSubscription.subscription.endDate).format(
                        "DD-MM-YYYY hh:mm A",
                      )
                      : "N/A"}
                  </span>
                </div>
              </div>
            </div>

            {viewingSubscription?.subscription?.trialEndsAt && (
              <div className="p-3 bg-blue-50 border border-blue-100 rounded-lg flex flex-col gap-1">
                <span className="text-xs text-blue-400 font-medium uppercase tracking-tight">
                  Trial Period Ends At
                </span>
                <div className="flex items-center gap-2 text-blue-700">
                  <span className="font-semibold">
                    {dayjs(viewingSubscription.subscription.trialEndsAt).format(
                      "DD-MM-YYYY hh:mm A",
                    )}
                  </span>
                </div>
              </div>
            )}

            <div className="flex justify-end mt-4">
              <Button onClick={() => setIsSubscriptionModalOpen(false)} type="primary" className="bg-slate-800 hover:bg-slate-700 border-none">
                Close
              </Button>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default ProgressOverview;