"use client";

import Link from "next/link";
import type { ReactNode } from "react";

import { DataTable } from "../../../../components/table/DataTable";
import { transactionColumns } from "../../../../components/table/features/users/columns/transactionColumns";
import { creditHistoryColumns } from "../../../../components/table/features/users/columns/creditHistoryColumns";
import Button from "../../../../components/ui/Button";
import { useModal } from "../../../../lib/modal-system/ModalContext";
import useUserDetail from "../../../../hooks/features/admin/users/useUserDetail";
import {
  convertDateStringToDate,
  formatFullName,
} from "../../../../utils/helper";
import { UserImage } from "../../../../components/ui/CustomImage";
import ClientWrapper from "../../../../components/ClientWrapper";
import Image from "next/image";
import SomethingWentWrong from "../../../../components/SomethingWentWrong";
import CustomLink from "../../../../components/ui/CustomLink";

const tableClassNames = {
  root: "w-full overflow-x-auto",
  toolbar: "mb-1",
  table: "min-w-[650px] xl:min-w-full",
  tableThead: "bg-slate-100 border-t-2 border-slate-400  relative",
  tableTheadRow: "whitespace-nowrap",
  tableTheadCell:
    "px-4 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:
    "py-2 px-3 font-body text-xs 2xl:text-sm text-table-text relative",
  pagination: "hidden",
};

export default function UserDetailPage() {
  const { openModal } = useModal();
  const { user, loading, error, isError } = useUserDetail();

  if (loading) return <UserDetailSkeleton />;
  if (isError || !user) return <SomethingWentWrong />;

  return (
    <ClientWrapper>
      <section className="w-full p-4 pt-6 2xl:pt-8 2xl:p-8">
        <div className="w-full">
          <div className="mb-5 flex flex-wrap items-center gap-2 text-base xl:gap-4 xl:text-xl">
            <CustomLink href="/admin/users" className="text-heading">
              Users
            </CustomLink>
            <span className="text-text">/</span>
            <span className="font-semibold text-link-1">
              {formatFullName(user.firstName, user.lastName)}
            </span>
          </div>

          <div className="glass-card-v2 rounded-xl p-4">
            <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
              <div className="flex min-w-0 items-start gap-3 sm:items-center sm:gap-4">
                <div className="relative h-12.5 w-12.5 shrink-0 overflow-hidden rounded-full">
                  <UserImage
                    src={user.profilePicture}
                    alt={user.firstName}
                    width={50}
                    height={50}
                    className="w-full h-full object-cover"
                  />
                </div>

                <div className="min-w-0">
                  <h2 className="font-body text-lg font-medium text-heading xl:text-xl">
                    {formatFullName(user.firstName, user.lastName)}
                  </h2>

                  <div className="mt-1 flex flex-col gap-1 text-sm text-table-text sm:flex-row sm:flex-wrap sm:items-center sm:gap-2.5 xl:text-base">
                    <span className="break-all">{user.email}</span>
                    <span className="hidden h-1 w-1 rounded-full bg-[#C7C3D4] sm:block" />
                    <span>
                      Joined {convertDateStringToDate(user.createdAt)}
                    </span>
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-3 sm:flex sm:flex-wrap sm:gap-4">
                <Button
                  variant="white"
                  className="w-full sm:w-auto"
                  onClick={() => {
                    if (user.isActive) {
                      openModal("DEACTIVATE_USER", {});
                    } else {
                      openModal("ACTIVATE_USER", {});
                    }
                  }}
                  buttonClassName="shadow-none!"
                  BtnInnerclassName="px-4.5! py-3.5! w-full"
                >
                  {user.isActive ? "Deactivate" : "Activate"}
                </Button>
              </div>
            </div>
          </div>

          <div className="mt-5 grid gap-4 sm:grid-cols-2 xl:gap-6 2xl:grid-cols-4">
            <DefaultValueCard
              title="License Key"
              value={
                user?.apiKeys && user?.apiKeys?.length ? (
                  <span className="inline-flex max-w-full rounded-full border border-link-1/20 bg-[#FBF8FF] px-4 py-2.5 text-sm font-semibold text-link break-all sm:px-5 xl:text-lg xl:leading-5">
                    {user?.apiKeys[0]?.apiKey?.slice(0, 20)}...
                  </span>
                ) : null
              }
              fallback={
                <span className="font-semibold text-heading">
                  No License Key
                </span>
              }
            />

            <DefaultValueCard
              title="Credit Balance"
              value={
                user?.wallet?.balance != null ? (
                  <p className="text-xl font-semibold text-heading xl:text-28 xl:leading-9.5">
                    ${user.wallet.balance}
                  </p>
                ) : null
              }
              fallback={
                <p className="text-xl font-semibold text-heading xl:text-28 xl:leading-9.5">
                  $0
                </p>
              }
            />

            <DefaultValueCard
              title="Last Pack"
              value={
                user?.paymentTransactions?.length ? (
                  <div className="flex flex-wrap items-center gap-3">
                    <p className="text-xl font-semibold text-heading xl:text-28 xl:leading-9.5">
                      ${user.paymentTransactions[0].amount}
                    </p>
                    <p className="text-base font-medium text-heading">
                      {user.paymentTransactions[0].packageName}
                    </p>
                  </div>
                ) : null
              }
              fallback={
                <p className="font-semibold text-heading">No purchases yet</p>
              }
            />

            <DefaultValueCard
              title="Total Spent"
              value={
                user?.totalCreditSpent != null ? (
                  <p className="text-3xl font-semibold text-heading">
                    ${user.totalCreditSpent}
                  </p>
                ) : null
              }
              fallback={
                <p className="text-3xl font-semibold text-heading">$0</p>
              }
            />
          </div>

          {/* <ManualCreditAdjustment /> */}

          <div className="mt-5 grid gap-4 xl:gap-6 2xl:grid-cols-2">
            <div className="glass-card-v2 min-w-0 rounded-xl p-4 xl:p-6">
              {user?.paymentTransactions.length > 0 ? (
                <DataTable
                  data={user?.paymentTransactions}
                  columns={transactionColumns}
                  appearance="default"
                  size="md"
                  getRowId={(row) => String(row.packageName)}
                  toolbar={
                    <h3 className="text-lg font-semibold text-heading xl:text-xl">
                      Recent Transactions
                    </h3>
                  }
                  classNames={tableClassNames}
                />
              ) : (
                <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 className="glass-card-v2 min-w-0 rounded-xl p-4 xl:p-6">
              {user?.wallet?.transactions.length > 0 ? (
                <DataTable
                  data={user?.wallet?.transactions}
                  columns={creditHistoryColumns}
                  appearance="default"
                  size="md"
                  getRowId={(row) => String(row.uuid)}
                  toolbar={
                    <h3 className="text-lg font-medium text-heading xl:text-xl">
                      Credit History
                    </h3>
                  }
                  classNames={tableClassNames}
                />
              ) : (
                <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 credit history yet
                    </h3>

                    <p className="mt-3 font-body text-sm md:text-base text-text xl:text-lg">
                      Your analyzed images and spent credits will appear here.
                    </p>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </section>
    </ClientWrapper>
  );
}

function InfoCard({ title, children }: { title: string; children: ReactNode }) {
  return (
    <div className="glass-card-v2 min-w-0 rounded-xl p-4 xl:p-6">
      <p className="mb-4 text-sm font-medium text-table-text xl:mb-5 xl:text-base">
        {title}
      </p>
      {children}
    </div>
  );
}

function DefaultValueCard({
  title,
  value,
  fallback,
}: {
  title: string;
  value: ReactNode;
  fallback: ReactNode;
}) {
  const hasValue =
    value !== undefined &&
    value !== null &&
    !(typeof value === "string" && value.trim() === "");

  return <InfoCard title={title}>{hasValue ? value : fallback}</InfoCard>;
}

function UserDetailSkeleton() {
  return (
    <section className="w-full animate-pulse overflow-hidden p-4 md:p-8">
      <div className="w-full">
        <div className="mb-5 flex items-center gap-3">
          <div className="h-5 w-14 rounded bg-gray-200" />
          <div className="h-5 w-3 rounded bg-gray-200" />
          <div className="h-5 w-40 rounded bg-gray-200" />
        </div>

        <div className="glass-card-v2 rounded-xl p-4">
          <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
            <div className="flex min-w-0 items-start gap-4">
              <div className="h-12.5 w-12.5 shrink-0 rounded-full bg-gray-200" />

              <div className="min-w-0">
                <div className="h-6 w-44 rounded bg-gray-200" />

                <div className="mt-2 flex items-center gap-2">
                  <div className="h-4 w-52 rounded bg-gray-200" />
                  <div className="h-1 w-1 rounded-full bg-gray-200" />
                  <div className="h-4 w-24 rounded bg-gray-200" />
                </div>
              </div>
            </div>

            <div className="h-11 w-32 rounded-xl bg-gray-200" />
          </div>
        </div>

        <div className="mt-5 grid gap-4 sm:grid-cols-2 xl:gap-6 2xl:grid-cols-4">
          {Array.from({ length: 4 }).map((_, index) => (
            <div key={index} className="glass-card-v2 rounded-xl p-4 xl:p-6">
              <div className="mb-4 h-5 w-28 rounded bg-gray-200" />
              <div className="h-8 w-32 rounded bg-gray-200" />
            </div>
          ))}
        </div>

        <div className="mt-5 grid gap-4 xl:gap-6 2xl:grid-cols-2">
          {Array.from({ length: 2 }).map((_, tableIndex) => (
            <div
              key={tableIndex}
              className="glass-card-v2 min-w-0 rounded-xl p-4 xl:p-6"
            >
              <div className="mb-6 h-6 w-48 rounded bg-gray-200" />

              <div className="space-y-4">
                {Array.from({ length: 6 }).map((_, rowIndex) => (
                  <div
                    key={rowIndex}
                    className="flex items-center justify-between"
                  >
                    <div className="h-4 w-32 rounded bg-gray-200" />
                    <div className="h-4 w-20 rounded bg-gray-200" />
                    <div className="h-4 w-24 rounded bg-gray-200" />
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}
