"use client";

import { useEffect, useMemo, useState } from "react";
import { m } from "framer-motion";
import { Search, TrendingUp, XCircle, ArrowDownLeft, ArrowUpRight, ChevronLeft, ChevronRight, ArrowUpDown, ArrowUp, ArrowDown } from "lucide-react";
import { Container } from "@/components/common/Container";
import { AgentProfitLogsSkeleton } from "@/components/skeletons/AgentProfitLogsSkeleton";
import { useAgentProfitLogs, type ProfitLog } from "@/hooks/queries/useAgentDashboard";
import { cn } from "@/lib/utils";
import { useTranslation } from "@/hooks/useTranslation";

// ─── Animation variants ───────────────────────────────────────────────────────

const containerVariants = {
  hidden: { opacity: 0 },
  visible: { opacity: 1, transition: { staggerChildren: 0.08, delayChildren: 0.05 } },
};
const itemVariants = {
  hidden: { opacity: 0, y: 15 },
  visible: { opacity: 1, y: 0, transition: { type: "spring", stiffness: 300, damping: 24 } },
};

// ─── Type badge ───────────────────────────────────────────────────────────────

const TYPE_META: Record<string, { cls: string; icon: React.ElementType }> = {
  "money in":  { cls: "bg-emerald-50 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-400", icon: ArrowDownLeft },
  "money out": { cls: "bg-rose-50 text-rose-700 dark:bg-rose-500/10 dark:text-rose-400",             icon: ArrowUpRight  },
};

function TypeBadge({ type }: { type: string }) {
  const meta = TYPE_META[type.toLowerCase()] ?? {
    cls: "bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300",
    icon: TrendingUp,
  };
  const Icon = meta.icon;
  return (
    <span className={cn("inline-flex items-center gap-1 rounded-md px-2 py-0.5 text-xs font-semibold", meta.cls)}>
      <Icon className="icon-xs" />
      {type}
    </span>
  );
}

// ─── Sortable column header ───────────────────────────────────────────────────

function HeaderItem({
  field,
  label,
  sortField,
  sortDir,
  onSort,
}: {
  field: SortField;
  label: string;
  sortField: SortField | null;
  sortDir: SortDir;
  onSort: (field: SortField) => void;
}) {
  const isSorted = sortField === field;
  return (
    <button
      type="button"
      onClick={() => onSort(field)}
      className={cn(
        "flex items-center gap-1.5 text-sm font-medium capitalize transition-colors hover:text-slate-600 dark:hover:text-slate-200 text-start outline-none",
        isSorted ? "text-brand-600 dark:text-brand-400" : "text-slate-400"
      )}
    >
      <span>{label}</span>
      {isSorted ? (
        sortDir === "asc" ? <ArrowUp className="icon-xs" /> : <ArrowDown className="icon-xs" />
      ) : (
        <ArrowUpDown className="h-3 w-3 opacity-40" />
      )}
    </button>
  );
}

// ─── Main view ────────────────────────────────────────────────────────────────

const PAGE_SIZE = 10;
type SortField = "transaction_id" | "date" | "type" | "commission";
type SortDir = "asc" | "desc";

export function AgentProfitLogsView() {
  const { t } = useTranslation();
  const { data, isLoading, isError } = useAgentProfitLogs();
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);
  const [sortField, setSortField] = useState<SortField | null>("date");
  const [sortDir, setSortDir] = useState<SortDir>("desc");

  useEffect(() => { setPage(1); }, [search]);

  const logs: ProfitLog[] = useMemo(() => data ?? [], [data]);

  const filtered = useMemo(() => {
    const q = search.toLowerCase();
    if (!q) return logs;
    return logs.filter(
      (l) =>
        l.transaction_id.toLowerCase().includes(q) ||
        l.type.toLowerCase().includes(q) ||
        l.currency.toLowerCase().includes(q),
    );
  }, [logs, search]);

  const sorted = useMemo(() => {
    if (!sortField) return filtered;
    return [...filtered].sort((a, b) => {
      let res = 0;
      if (sortField === "transaction_id") {
        res = a.transaction_id.localeCompare(b.transaction_id);
      } else if (sortField === "type") {
        res = a.type.localeCompare(b.type);
      } else if (sortField === "commission") {
        res = a.total_commissions - b.total_commissions;
      } else if (sortField === "date") {
        const da = new Date(`${a.created_month} ${a.created_date}, 2026`).getTime() || 0;
        const db = new Date(`${b.created_month} ${b.created_date}, 2026`).getTime() || 0;
        res = da - db;
      }
      return sortDir === "asc" ? res : -res;
    });
  }, [filtered, sortField, sortDir]);

  function handleSort(field: SortField) {
    if (sortField === field) {
      setSortDir((prev) => (prev === "asc" ? "desc" : "asc"));
    } else {
      setSortField(field);
      setSortDir("asc");
    }
  }

  const total       = logs.reduce((s, l) => s + l.total_commissions, 0);
  const moneyIn     = logs.filter((l) => l.type.toLowerCase() === "money in").reduce((s, l) => s + l.total_commissions, 0);
  const moneyOut    = logs.filter((l) => l.type.toLowerCase() === "money out").reduce((s, l) => s + l.total_commissions, 0);

  const currency = logs[0]?.currency ?? "";

  // Pagination — reset on search change
  const totalPages = Math.max(1, Math.ceil(sorted.length / PAGE_SIZE));
  const safePage   = Math.min(page, totalPages);
  const pageStart  = (safePage - 1) * PAGE_SIZE;
  const paginated  = sorted.slice(pageStart, pageStart + PAGE_SIZE);



  if (isLoading) return <AgentProfitLogsSkeleton />;

  if (isError) {
    return (
      <Container className="max-w-full pb-10">
        <div className="flex flex-col items-center gap-4 rounded-[1.5rem] border border-rose-200 bg-rose-50 p-16 text-center dark:border-rose-500/20 dark:bg-rose-500/10">
          <XCircle className="h-10 w-10 text-rose-500" />
          <p className="font-semibold text-slate-900 dark:text-white">{t("agent.profitLog.failedToLoad")}</p>
        </div>
      </Container>
    );
  }

  return (
    <Container className="max-w-full space-y-6 lg:space-y-8">
      <m.div variants={containerVariants} initial="hidden" animate="visible" className="space-y-6 lg:space-y-8">

        {/* Page header */}
        <m.div variants={itemVariants}>
          <header className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
            <div className="flex items-center gap-4">
              <div className="icon-box-md grid place-items-center rounded-2xl bg-gradient-to-br from-emerald-500 to-brand-500 text-white shadow-lg">
                <TrendingUp className="icon-xl" />
              </div>
              <div>
                <h1 className="text-2xl font-bold tracking-tight text-slate-900 dark:text-white">{t("agent.profitLog.title")}</h1>
                <p className="mt-1 text-sm text-slate-500 dark:text-slate-400">{t("agent.profitLog.subtitle")}</p>
              </div>
            </div>
          </header>
        </m.div>

        {/* Stats row — under header, like the transactions page */}
        {currency && (
          <m.div variants={itemVariants}>
            <div className="flex gap-2 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden sm:gap-3">
              {[
                { icon: TrendingUp,    label: t("agent.profitLog.statTotal"),    value: total,    color: "text-brand-600 dark:text-brand-300" },
                { icon: ArrowDownLeft, label: t("agent.profitLog.statMoneyIn"),  value: moneyIn,  color: "text-emerald-600 dark:text-emerald-400" },
                { icon: ArrowUpRight,  label: t("agent.profitLog.statMoneyOut"), value: moneyOut, color: "text-rose-500 dark:text-rose-400" },
              ].map(({ icon: Icon, label, value, color }) => (
                <div key={label} className="flex min-h-[4.5rem] w-56 shrink-0 items-center gap-3 rounded-xl border border-slate-200/60 bg-white px-4 py-2.5 sm:min-h-[5rem] sm:w-72 sm:gap-4 sm:rounded-2xl sm:px-5 sm:py-4 dark:border-slate-800/60 dark:bg-slate-900/40">
                  <div className={`grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-slate-100 dark:bg-slate-800 sm:h-11 sm:w-11 ${color}`}>
                    <Icon className="h-5 w-5" />
                  </div>
                  <div className="min-w-0 space-y-1.5">
                    <p className="whitespace-nowrap text-sm font-medium capitalize leading-tight text-slate-400">{label}</p>
                    <p className={`whitespace-nowrap text-sm font-semibold tabular-nums leading-none sm:text-lg ${color}`}>
                      {currency} {value.toFixed(2)}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </m.div>
        )}

        {/* Logs card */}
        <m.div variants={itemVariants}>
          <div className="overflow-hidden rounded-3xl border border-slate-200/60 bg-white shadow-sm dark:border-slate-800/60 dark:bg-slate-900/40">

            {/* Card header */}
            <div className="flex flex-wrap items-center gap-4 border-b border-slate-100/80 p-6 sm:p-7 dark:border-slate-800/60">
              <div className="flex items-center gap-3">
                <div className="grid h-9 w-9 shrink-0 place-items-center rounded-xl bg-emerald-50 dark:bg-emerald-500/10">
                  <TrendingUp className="h-4 w-4 text-emerald-600 dark:text-emerald-400" />
                </div>
                <div>
                  <h2 className="text-[length:var(--text-lg-fixed)] font-semibold text-slate-900 dark:text-white">{t("agent.profitLog.commissionRecords")}</h2>
                  <p className="mt-0.5 text-sm font-medium text-slate-400">{t("agent.profitLog.records").replace("{n}", String(sorted.length))}</p>
                </div>
              </div>

              {/* Search */}
              <div className="relative w-full sm:ms-auto sm:max-w-xs sm:w-auto">
                <Search className="pointer-events-none absolute start-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-400" />
                <input
                  type="search"
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  placeholder={t("agent.profitLog.searchPlaceholder")}
                  autoComplete="off"
                  className="h-9 w-full rounded-xl border border-slate-200 bg-slate-50 ps-9 pe-4 text-sm outline-none transition focus:border-brand-400 focus:bg-white dark:border-slate-700 dark:bg-slate-800/60 dark:text-white dark:focus:bg-slate-800"
                />
              </div>
            </div>

            {/* Scrollable table area */}
            <div className="overflow-x-auto">
              <div className="min-w-[800px] w-full">

            {/* Column headers */}
            <div className="grid grid-cols-4 items-center gap-4 border-b border-slate-100/80 px-6 py-3 dark:border-slate-800/60 sm:px-7">
              <HeaderItem field="transaction_id" label={t("agent.profitLog.colTransactionId")} sortField={sortField} sortDir={sortDir} onSort={handleSort} />
              <HeaderItem field="date" label={t("agent.profitLog.colDate")} sortField={sortField} sortDir={sortDir} onSort={handleSort} />
              <HeaderItem field="type" label={t("agent.profitLog.colType")} sortField={sortField} sortDir={sortDir} onSort={handleSort} />
              <HeaderItem field="commission" label={t("agent.profitLog.colCommission")} sortField={sortField} sortDir={sortDir} onSort={handleSort} />
            </div>

            {/* Rows */}
            {sorted.length === 0 ? (
              <div className="flex flex-col items-center gap-4 py-16 text-center">
                <div className="icon-box-md grid place-items-center rounded-2xl bg-slate-100 dark:bg-slate-800">
                  <TrendingUp className="h-5 w-5 text-slate-400" />
                </div>
                <p className="text-sm font-semibold text-slate-500 dark:text-slate-400">
                  {search ? t("agent.profitLog.noMatchingRecords") : t("agent.profitLog.noRecordsFound")}
                </p>
              </div>
            ) : (
              <>
                <div>
                  {paginated.map((log, i) => (
                    <m.div
                      key={log.transaction_id}
                      initial={{ opacity: 0, y: 4 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: i * 0.02, type: "spring", stiffness: 300, damping: 26 }}
                      className="grid grid-cols-4 items-center gap-4 px-6 py-5 transition-colors hover:bg-slate-50/60 dark:hover:bg-slate-800/40 sm:px-7"
                    >
                      <p className="whitespace-nowrap text-sm font-semibold tabular-nums text-brand-600 dark:text-brand-400">
                        {log.transaction_id}
                      </p>
                      <p className="whitespace-nowrap text-sm text-slate-400">
                        {log.created_date} {log.created_month}
                      </p>
                      <div className="whitespace-nowrap">
                        <TypeBadge type={log.type} />
                      </div>
                      <p className="whitespace-nowrap text-start text-sm font-bold tabular-nums text-emerald-600 dark:text-emerald-400">
                        {log.total_commissions.toFixed(2)}{" "}
                        <span className="text-xs font-semibold text-slate-400">{log.currency}</span>
                      </p>
                    </m.div>
                  ))}
                </div>

                {/* Pagination */}
                {sorted.length > PAGE_SIZE && (
                  <div className="flex items-center justify-between border-t border-slate-100/80 px-6 py-6 dark:border-slate-800/60 sm:px-7 sm:py-7">
                    <p className="text-xs font-medium text-slate-400">
                      {sorted.length > 0
                        ? t("agent.profitLog.range").replace("{start}", String(pageStart + 1)).replace("{end}", String(Math.min(pageStart + PAGE_SIZE, sorted.length))).replace("{total}", String(sorted.length))
                        : "0 records"}
                    </p>
                    <div className="flex items-center gap-1">
                      <button
                        type="button"
                        onClick={() => setPage((p) => Math.max(1, p - 1))}
                        disabled={safePage === 1}
                        className="btn-icon-sm rounded-full border border-slate-200 bg-white text-slate-500 transition hover:border-brand-300 hover:text-brand-600 disabled:cursor-not-allowed disabled:opacity-40 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-400"
                      >
                        <ChevronLeft className="icon-md rtl:-scale-x-100" />
                      </button>
                      {Array.from({ length: totalPages }, (_, i) => i + 1)
                        .filter((n) => n === 1 || n === totalPages || Math.abs(n - safePage) <= 1)
                        .reduce<(number | "…")[]>((acc, n, idx, arr) => {
                          if (idx > 0 && n - (arr[idx - 1] as number) > 1) acc.push("…");
                          acc.push(n);
                          return acc;
                        }, [])
                        .map((n, i) =>
                          n === "…" ? (
                            <span key={`e-${i}`} className="px-1 text-xs text-slate-400">…</span>
                          ) : (
                            <button
                              key={n}
                              type="button"
                              onClick={() => setPage(n as number)}
                              className={cn(
                                "h-8 min-w-8 rounded-full px-2 text-xs font-semibold transition",
                                safePage === n
                                  ? "bg-brand-600 text-white shadow-sm"
                                  : "border border-slate-200 bg-white text-slate-600 hover:border-brand-300 hover:text-brand-600 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-300",
                              )}
                            >
                              {n}
                            </button>
                          ),
                        )}
                      <button
                        type="button"
                        onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                        disabled={safePage === totalPages}
                        className="btn-icon-sm rounded-full border border-slate-200 bg-white text-slate-500 transition hover:border-brand-300 hover:text-brand-600 disabled:cursor-not-allowed disabled:opacity-40 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-400"
                      >
                        <ChevronRight className="icon-md rtl:-scale-x-100" />
                      </button>
                    </div>
                  </div>
                )}

              </>
            )}

              </div>
            </div>
          </div>
        </m.div>

      </m.div>
    </Container>
  );
}
