"use client";

import Image from "next/image";
import { BiSolidGridAlt } from "react-icons/bi";
import { FiFileText } from "react-icons/fi";

import DashboardSectionTitle from "../../../../components/dashboard/DashboardSectionTitle";
import CreditOverviewCard from "../../../../components/dashboard/CreditOverviewCard";
import { DataTable } from "../../../../components/table/DataTable";
import { transactionHistoryColumns } from "../../../../components/table/features/dashboard/transactionHistoryColumn";
import useTransacationHistoryFetch from "../../../../hooks/features/dashboard/useTransacationHistoryFetch";
import { useAppPagination } from "../../../../hooks/useAppPagination";
import { useAppSelector } from "../../../../hooks/useAppRedux";
import ClientWrapper from "../../../../components/ClientWrapper";
import useFetchCreditSummary from "../../../../hooks/features/dashboard/useFetchCreditSummary";
import SomethingWentWrong from "../../../../components/SomethingWentWrong";

export default function DashboardPage() {
  const pagination = useAppPagination();
  const { user } = useAppSelector((state) => state.user);

  const {
    creditSummary,
    loading,
    error: creditSummaryError,
  } = useFetchCreditSummary();

  const {
    data,
    error,
    loading: transactionsHistoryLoading,
    isError,
  } = useTransacationHistoryFetch(pagination);

  const transactions = data?.transactions ?? [];
  const meta = data?.pagination;
  const isNewUser = creditSummary?.lastPurchasedPackage === null;

  if (loading) {
    return <DashboardSkeleton />;
  }

  return (
    <ClientWrapper fallback={<DashboardSkeleton />}>
      <div className="container-k">
        <p className="mb-3 xl:mb-5 2xl:mb-7.5 flex items-center gap-3 font-body text-base md:text-lg 2xl:text-xl text-link-1 font-semibold">
          Dashboard
        </p>

        <div className="mb-6 2xl:mb-10">
          <h1 className="font-heading text-2xl xl:text-2xl font-medium text-heading 2xl:text-[40px] 2xl:leading-12.5">
            Hello, {user?.firstName}!
          </h1>

          <p className="mt-1 md:mt-1.5 xl:mt-2 2xl:mt-2.5 text-sm md:text-base text-text xl:text-lg 2xl:text-xl 2xl:leading-7">
            {isNewUser
              ? "Get started by purchasing your first credit package to begin analyzing images."
              : "Welcome back! Check your available credits, explore packages and manage your account effortlessly."}
          </p>
        </div>

        <DashboardSectionTitle
          icon={<BiSolidGridAlt size={22} />}
          title="Overview"
        />

        {creditSummaryError ? (
          <SomethingWentWrong
            variant="section"
            title="Unable to load credit summary"
            description="Your credit balance could not be loaded right now. Other dashboard sections are still available."
            onRetry={() => window.location.reload()}
            buttonText="Go to packages"
            buttonHref="/dashboard/packages"
          />
        ) : (
          <CreditOverviewCard creditSummary={creditSummary} />
        )}

        <div className="mt-10">
          <DashboardSectionTitle
            icon={<FiFileText size={20} />}
            title="Transaction History"
          />

          {isError ? (
            <SomethingWentWrong
              variant="section"
              title="Unable to load transactions"
              description="Your recent transactions could not be loaded. You can still use the rest of the dashboard."
              onRetry={() => pagination.patch({})}
            />
          ) : transactionsHistoryLoading || transactions.length > 0 ? (
            <DataTable
              data={transactions}
              loading={transactionsHistoryLoading}
              columns={transactionHistoryColumns}
              classNames={{
                root: "",
                toolbar: "",
                filters: "",
                table: "rounded-xl overflow-hidden",
                tableThead: "glass-card-v2 rounded-xl",
                tableTheadRow: "",
                tableTheadCell:
                  "px-4 py-3 md:px-6 md:py-4 text-left font-body whitespace-nowrap text-sm md:text-base font-medium text-heading",
                tableTbody: "glass-card-v2 rounded-xl overflow-hidden",
                tableTbodyRow:
                  "[&:not(:last-child)>td]:border-b [&:not(:last-child)>td]:border-white",
                tableTbodyCell:
                  "px-4 py-3 md:px-6 md:py-4 font-body font-medium text-xs md:text-sm text-heading",
                pagination:
                  "mt-8 flex flex-wrap items-center justify-center gap-1",
              }}
              pagination={{
                controller: pagination,
                pageCount: meta?.totalPages,
                totalItems: meta?.total,
              }}
              sorting={pagination.sortingConfig}
            />
          ) : (
            <div className="glass-card-v2 rounded-2xl p-10 text-center md:p-16">
              <div className="relative z-10 mx-auto max-w-152.5">
                <Image
                  src={"/images/no-transaction.svg"}
                  alt="Empty"
                  width={150}
                  height={120}
                  className="mx-auto mb-6"
                />

                <h3 className="font-body text-xl font-bold text-heading">
                  No transactions yet
                </h3>

                <p className="mt-3 font-body text-sm md:text-base text-text xl:text-lg">
                  Once you purchase a credit package, your invoices and
                  transaction history will appear here.
                </p>
              </div>
            </div>
          )}
        </div>
      </div>
    </ClientWrapper>
  );
}

function DashboardSkeleton() {
  return (
    <div className="animate-pulse container-k">
      {/* Breadcrumb */}
      <div className="mb-5 h-6 w-28 rounded bg-gray-200 lg:mb-7.5" />

      {/* Greeting */}
      <div className="mb-6 2xl:mb-10">
        <div className="h-10 w-72 rounded bg-gray-200" />

        <div className="mt-3 space-y-2">
          <div className="h-5 w-full max-w-2xl rounded bg-gray-200" />
          <div className="h-5 w-3/4 rounded bg-gray-200" />
        </div>
      </div>

      {/* Overview Title */}
      <div className="mb-6 flex items-center gap-3">
        <div className="h-8 w-8 rounded-full bg-gray-200" />
        <div className="h-7 w-32 rounded bg-gray-200" />
      </div>

      {/* Credit Overview */}
      <div className="grid gap-6 lg:grid-cols-2">
        {/* Card 1 */}
        <div className="glass-card-v2 rounded-2xl p-6 md:p-7.5">
          <div className="mb-8 flex items-center justify-between">
            <div className="h-7 w-40 rounded bg-gray-200" />

            <div className="flex gap-3">
              <div className="h-12 w-40 rounded-full bg-gray-200" />
              <div className="h-12 w-12 rounded-full bg-gray-200" />
            </div>
          </div>

          <div className="mb-4 flex items-end justify-between">
            <div className="h-10 w-44 rounded bg-gray-200" />
            <div className="h-5 w-28 rounded bg-gray-200" />
          </div>

          <div className="h-2 w-full rounded-full bg-gray-200" />
        </div>

        {/* Card 2 */}
        <div className="glass-card-v2 rounded-2xl p-6 md:p-7.5">
          <div className="flex items-center justify-between">
            <div className="h-7 w-36 rounded bg-gray-200" />
            <div className="h-8 w-32 rounded-full bg-gray-200" />
          </div>

          <div className="mt-16 flex items-end justify-between">
            <div>
              <div className="h-10 w-20 rounded bg-gray-200" />
              <div className="mt-3 h-5 w-28 rounded bg-gray-200" />
            </div>

            <div className="h-12 w-36 rounded-full bg-gray-200" />
          </div>
        </div>
      </div>

      {/* Transaction History */}
      <div className="mt-10">
        <div className="mb-6 flex items-center gap-3">
          <div className="h-8 w-8 rounded-full bg-gray-200" />
          <div className="h-7 w-52 rounded bg-gray-200" />
        </div>

        <div className="glass-card-v2 overflow-hidden rounded-2xl">
          {/* Table Header */}
          <div className="grid grid-cols-5 gap-4 border-b border-white px-6 py-4">
            {Array.from({ length: 5 }).map((_, i) => (
              <div key={i} className="h-5 rounded bg-gray-200" />
            ))}
          </div>

          {/* Table Rows */}
          {Array.from({ length: 6 }).map((_, row) => (
            <div
              key={row}
              className="grid grid-cols-5 gap-4 border-b border-white px-6 py-5 last:border-b-0"
            >
              {Array.from({ length: 5 }).map((_, col) => (
                <div key={col} className="h-5 rounded bg-gray-200" />
              ))}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
