"use client";

import { useEffect, useState } from "react";
import { DataTable } from "../../components/table/DataTable";
import {
  FaArrowTrendUp,
  FaArrowTrendDown,
  FaUsers,
  FaUserCheck,
  FaUserXmark,
  FaSackDollar,
  FaReceipt,
} from "react-icons/fa6";
import { registrationColumns } from "../../components/table/features/dashboard/admin/columns/registrationColumns";
import { purchaseColumns } from "../../components/table/features/dashboard/admin/columns/purchaseColumns";
import Link from "next/link";
import useFetchDashboard from "../../hooks/features/admin/useFetchDashboard";
import { convertDateStringToDate } from "../../utils/helper";
import { Registration, Purchase } from "../../types/dashboard";
import SomethingWentWrong from "../../components/SomethingWentWrong";
import CustomLink from "../../components/ui/CustomLink";

const tableClassNames = {
  root: "w-full overflow-x-auto",
  table: "min-w-full",
  tableThead: "bg-slate-100 border-t-2 border-slate-400  relative",
  tableTheadRow: "whitespace-nowrap",
  tableTheadCell:
    "px-2.5 2xl:px-4 py-2 2xl:py-2.5 text-left font-body text-sm 2xl:text-base font-medium text-heading relative",
  tableTbody: "border-t border-slate-300/50 relative",
  tableTbodyRow: `
    hover:bg-link-1/10 transition-colors
    [&>td]:border-b [&>td]:border-[#E7E7E8]
  `,
  tableTbodyCell:
    "px-2.5 2xl:px-4 py-1.5 2xl:py-2.5 font-body text-[13px] 2xl:text-sm text-table-text relative",
  pagination: "hidden",
};

function formatRegistrationStatus(status?: string): "Active" | "Inactive" {
  if (!status) return "Active";
  const normalized = status.trim().toLowerCase();
  if (
    normalized === "inactive" ||
    normalized === "deactivated" ||
    normalized === "false"
  ) {
    return "Inactive";
  }
  return "Active";
}

function formatTransactionStatus(status?: string): "Success" | "Failed" {
  if (!status) return "Success";
  const normalized = status.trim().toLowerCase();
  if (
    normalized === "failed" ||
    normalized === "fail" ||
    normalized === "error"
  ) {
    return "Failed";
  }
  return "Success";
}

export default function AdminDashboard() {
  const { data, loading, isError, error } = useFetchDashboard();
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  if (!mounted || loading) {
    return <DashboardSkeleton />;
  }

  if (isError || !data) {
    return <SomethingWentWrong />;
  }

  const stats = [
    {
      id: 1,
      title: "Total Users",
      value:
        data?.statistics?.totalUsers !== undefined
          ? data.statistics.totalUsers.toLocaleString()
          : "0",
      icon: <FaUsers />,
      iconBg: "bg-blue-500/10",
      iconColor: "text-blue-500",
    },
    {
      id: 2,
      title: "Active Users",
      value:
        data?.statistics?.activeUsers !== undefined
          ? data.statistics.activeUsers.toLocaleString()
          : "0",
      icon: <FaUserCheck />,
      iconBg: "bg-green-500/10",
      iconColor: "text-green-500",
    },
    {
      id: 3,
      title: "Inactive Users",
      value:
        data?.statistics?.inactiveUsers !== undefined
          ? data.statistics.inactiveUsers.toLocaleString()
          : "0",
      icon: <FaUserXmark />,
      iconBg: "bg-red-500/10",
      iconColor: "text-red-500",
    },
    {
      id: 4,
      title: "Total Revenue",
      value:
        data?.statistics?.totalRevenue !== undefined
          ? `$${data.statistics.totalRevenue.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
          : "$0.00",
      icon: <FaSackDollar />,
      iconBg: "bg-amber-500/10",
      iconColor: "text-amber-500",
    },
    {
      id: 5,
      title: "Transactions",
      value:
        data?.statistics?.totalTransactions !== undefined
          ? data.statistics.totalTransactions.toLocaleString()
          : "0",
      icon: <FaReceipt />,
      iconBg: "bg-purple-500/10",
      iconColor: "text-purple-500",
    },
  ];

  const registrationsData: Registration[] =
    data?.recentRegistrations.map((reg) => ({
      id: reg.uuid as any,
      user: `${reg.firstName} ${reg.lastName}`.trim(),
      email: reg.email,
      registeredOn: convertDateStringToDate(reg.createdAt),
      status: formatRegistrationStatus((reg as any).status),
    })) ?? [];

  const purchasesData: Purchase[] =
    data?.recentTransactions.map((tx) => ({
      id: tx.uuid as any,
      user: tx.userName || "N/A",
      package: tx.packageName || "N/A",
      credits: (tx as any).credits ?? 0,
      amount: tx.amount !== undefined ? `$${tx.amount}` : "$0",
      date: convertDateStringToDate(tx.createdAt),
      status: formatTransactionStatus(tx.status),
    })) ?? [];

  return (
    <section className="w-full p-4 pt-6 2xl:pt-8 2xl:p-8">
      <div className="w-full">
        <h1 className="font-body text-base lg:text-lg xl:text-xl 2xl:text-2xl font-semibold xl:leading-8.5 text-heading">
          Dashboard
        </h1>
        <p className="2xl:mt-0.5 font-body text-sm 2xl:text-base font-normal text-text ">
          Welcome back! Here’s a snapshot of your platform’s latest activity and
          key metrics.
        </p>
      </div>
      <div className="mt-8 grid gap-4 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 md:gap-3 2xl:gap-6">
        {stats.map((item) => (
          <InfoCard
            key={item.id}
            title={item.title}
            value={item.value}
            icon={item.icon}
            iconBg={item.iconBg}
            iconColor={item.iconColor}
          />
        ))}
      </div>

      <div className="mt-5 grid gap-4 2xl:gap-6 xl:grid-cols-2">
        <div className="glass-card-v2 min-w-0 rounded-xl px-4 py-3 xl:p-4 2xl:p-6">
          <DataTable
            data={registrationsData}
            columns={registrationColumns}
            appearance="default"
            size="md"
            getRowId={(row) => String(row.id)}
            toolbar={
              <h3 className="text-base xl:text-lg font-medium text-heading 2xl:text-xl">
                Recent Registrations
              </h3>
            }
            filters={
              <CustomLink
                href="/admin/users"
                className="font-medium text-link-1 text-base hover:underline"
              >
                See All
              </CustomLink>
            }
            classNames={tableClassNames}
          />
        </div>

        <div className="glass-card-v2 min-w-0 rounded-xl px-4 py-3 xl:p-4 2xl:p-6">
          <DataTable
            data={purchasesData}
            columns={purchaseColumns}
            appearance="default"
            size="md"
            getRowId={(row) => String(row.id)}
            toolbar={
              <h3 className="text-base xl:text-lg font-medium text-heading 2xl:text-xl">
                Recent Purchases
              </h3>
            }
            filters={
              <CustomLink
                href="/admin/transactions"
                className="font-medium text-link-1 text-base hover:underline"
              >
                See All
              </CustomLink>
            }
            classNames={tableClassNames}
          />
        </div>
      </div>
    </section>
  );
}

interface InfoCardProps {
  title: string;
  value: string;
  growth?: string;
  trend?: "up" | "down";
  icon?: React.ReactNode;
  iconBg?: string;
  iconColor?: string;
}

function InfoCard({
  title,
  value,
  growth,
  trend,
  icon,
  iconBg,
  iconColor,
}: InfoCardProps) {
  return (
    <div className="glass-card-v2 rounded-xl p-4 xl:p-6 overflow-hidden">
      <div className="flex items-center justify-between">
        <p className="text-table-text text-base">{title}</p>
        {icon && (
          <span
            className={`ps-4 pt-4 h-20 w-20 md:w-24 md:h-24 rounded-full absolute -right-6 -bottom-6 md:-right-8 md:-bottom-8 opacity-50 text-3xl md:text-4xl ${iconBg} ${iconColor}`}
          >
            {icon}
          </span>
        )}
      </div>
      <div className="mt-2.5 flex items-center justify-between">
        <h2 className="text-xl xl:text-2xl 2xl:text-28 font-semibold text-heading">
          {value}
        </h2>
        {growth && trend && (
          <div
            className={`flex items-center gap-1 text-base font-medium ${
              trend === "up" ? "text-green-500" : "text-red-500"
            }`}
          >
            {growth}
            {trend === "up" ? <FaArrowTrendUp /> : <FaArrowTrendDown />}
          </div>
        )}
      </div>
    </div>
  );
}

function DashboardSkeleton() {
  return (
    <section className="w-full p-4 pt-6 2xl:pt-8 2xl:p-8 animate-pulse">
      <div className="w-full">
        <div className="h-8 w-48 bg-slate-200 rounded mb-2" />
        <div className="h-4 w-96 bg-slate-200 rounded" />
      </div>

      <div className="mt-8 grid gap-4 sm:grid-cols-2 md:grid-cols-3 2xl:grid-cols-5 md:gap-3 2xl:gap-6">
        {Array.from({ length: 5 }).map((_, idx) => (
          <div
            key={idx}
            className="glass-card-v2 rounded-xl p-4 xl:p-6 bg-slate-50/50"
          >
            <div className="h-4 w-24 bg-slate-200 rounded" />
            <div className="mt-5 flex items-center justify-between">
              <div className="h-8 w-16 bg-slate-200 rounded" />
            </div>
          </div>
        ))}
      </div>

      <div className="mt-5 grid gap-4 xl:gap-6 xl:grid-cols-2">
        {Array.from({ length: 2 }).map((_, tableIdx) => (
          <div
            key={tableIdx}
            className="glass-card-v2 min-w-0 rounded-xl p-4 xl:p-6"
          >
            <div className="flex justify-between items-center mb-6">
              <div className="h-6 w-48 bg-slate-200 rounded" />
              <div className="h-4 w-16 bg-slate-200 rounded" />
            </div>

            <div className="w-full overflow-x-auto">
              <table className="min-w-full">
                <thead>
                  <tr className="border-b-2 border-slate-200">
                    {Array.from({ length: 4 }).map((_, colIdx) => (
                      <th key={colIdx} className="px-4 py-3 text-left">
                        <div className="h-4 w-20 bg-slate-200 rounded" />
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {Array.from({ length: 5 }).map((_, rowIdx) => (
                    <tr key={rowIdx} className="border-b border-slate-100">
                      {Array.from({ length: 4 }).map((_, colIdx) => (
                        <td key={colIdx} className="px-4 py-3">
                          <div className="h-4 w-24 bg-slate-200 rounded" />
                        </td>
                      ))}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}
