"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { useAuth } from "@/context/AuthContext";
import { apiFetch } from "@/lib/apiClient";
import { formatNaira, formatDateTime } from "@/lib/utils";
import type { Transaction } from "@/types";

type StatusFilter = "ALL" | "SUCCESS" | "FAILED" | "PENDING";

interface TxWithPackage extends Transaction {
  booking?: { package?: { name: string; slug: string } };
}

export default function TransactionsPage() {
  const router = useRouter();
  const { isLoading, isAuthenticated } = useAuth();
  const [transactions, setTransactions] = useState<TxWithPackage[]>([]);
  const [filter, setFilter] = useState<StatusFilter>("ALL");
  const [dataLoading, setDataLoading] = useState(true);

  useEffect(() => {
    if (!isLoading && !isAuthenticated) router.replace("/login");
  }, [isLoading, isAuthenticated, router]);

  useEffect(() => {
    if (!isAuthenticated) return;
    setDataLoading(true);
    const q = filter !== "ALL" ? `?status=${filter}` : "";
    apiFetch<{ transactions: TxWithPackage[]; total: number }>(`/transactions/me${q}`)
      .then((d) => setTransactions(d.transactions))
      .catch(console.error)
      .finally(() => setDataLoading(false));
  }, [isAuthenticated, filter]);

  const totalDeposited = transactions.filter((t) => t.status === "SUCCESS").reduce((s, t) => s + Number(t.amount), 0);
  const successCount = transactions.filter((t) => t.status === "SUCCESS").length;
  const lastDeposit = transactions.find((t) => t.status === "SUCCESS");

  const grouped = transactions.reduce<Record<string, TxWithPackage[]>>((acc, tx) => {
    const key = new Date(tx.createdAt).toLocaleDateString("en-NG", { month: "long", year: "numeric" });
    (acc[key] ??= []).push(tx);
    return acc;
  }, {});

  return (
    <div className="bg-[#f9f9f9] min-h-screen text-[#1a1c1c]">
      {/* Sticky Header */}
      <header className="sticky top-0 z-10 bg-white/95 backdrop-blur-xl border-b border-[#e2e2e2]">
        <div className="flex items-center justify-between px-5 h-16">
          <button
            onClick={() => router.push("/dashboard")}
            className="flex items-center gap-2 text-[#464651] text-sm font-semibold"
          >
            <span className="material-symbols-outlined text-[20px]">arrow_back</span>
          </button>
          <h1 className="font-bold text-[#1a1c1c] text-[18px]" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
            Activity
          </h1>
          <span className="material-symbols-outlined text-[#755b00]">tune</span>
        </div>
      </header>

      <div className="px-5 pt-4 pb-32 max-w-[430px] mx-auto">
        {/* Tabs */}
        <div className="flex border-b border-[#e2e2e2] mb-5">
          <button className="flex-1 pb-3 text-sm font-semibold text-[#1a1c1c] relative">
            Transactions
            <span className="absolute bottom-0 left-0 right-0 h-0.5 bg-[#755b00]" />
          </button>
          <button
            onClick={() => router.push("/notifications")}
            className="flex-1 pb-3 text-sm font-semibold text-[#464651] transition-colors"
          >
            Notifications
          </button>
        </div>

        {/* Summary Bar */}
        <div
          className="rounded-2xl p-5 mb-5 relative overflow-hidden text-white"
          style={{ background: "linear-gradient(135deg, #0D1145 0%, #1C2472 60%, #2D3A8C 100%)" }}
        >
          <div className="absolute top-0 right-0 -mr-6 -mt-6 opacity-10">
            <span className="material-symbols-outlined text-white" style={{ fontSize: "80px" }}>account_balance_wallet</span>
          </div>
          <div className="grid grid-cols-3 gap-3 relative z-10">
            <div>
              <p className="text-[#FED665] text-[9px] uppercase tracking-wider mb-1 font-semibold">Total Deposited</p>
              <p className="text-white font-bold text-sm">{formatNaira(totalDeposited)}</p>
            </div>
            <div className="border-x border-white/10 text-center">
              <p className="text-[#FED665] text-[9px] uppercase tracking-wider mb-1 font-semibold">Deposits</p>
              <p className="text-white font-bold text-sm">{successCount}</p>
            </div>
            <div className="text-right">
              <p className="text-[#FED665] text-[9px] uppercase tracking-wider mb-1 font-semibold">Last Deposit</p>
              <p className="text-white font-bold text-sm">
                {lastDeposit
                  ? new Date(lastDeposit.createdAt).toLocaleDateString("en-NG", { day: "numeric", month: "short" })
                  : "—"}
              </p>
            </div>
          </div>
        </div>

        {/* Filter Pills */}
        <div className="flex gap-2 mb-5 overflow-x-auto pb-1 scrollbar-hide">
          {(["ALL", "SUCCESS", "PENDING", "FAILED"] as StatusFilter[]).map((f) => (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className="px-4 py-1.5 rounded-full text-xs font-semibold whitespace-nowrap transition-all"
              style={filter === f
                ? { background: "#1a1c1c", color: "white" }
                : { background: "white", color: "#464651", border: "1px solid #e2e2e2" }}
            >
              {f === "ALL" ? "All" : f.charAt(0) + f.slice(1).toLowerCase()}
            </button>
          ))}
        </div>

        {/* Transaction List */}
        {dataLoading ? (
          <div className="space-y-3">
            {[1, 2, 3].map((i) => (
              <div key={i} className="h-16 bg-white rounded-xl animate-pulse" />
            ))}
          </div>
        ) : Object.keys(grouped).length === 0 ? (
          <div className="text-center py-16">
            <span className="material-symbols-outlined text-[#c6c5d3] text-6xl mb-4 block">receipt_long</span>
            <p className="text-[#464651] text-sm mb-4">No transactions yet</p>
            <Link
              href="/deposit"
              className="inline-block bg-[#040b61] text-white px-6 py-3 rounded-full text-sm font-semibold"
            >
              Make your first deposit →
            </Link>
          </div>
        ) : (
          <div className="space-y-6">
            {Object.entries(grouped).map(([month, txs]) => (
              <div key={month}>
                <h3 className="text-[#767682] text-[10px] font-bold uppercase tracking-widest mb-3">{month}</h3>
                <div className="space-y-2">
                  {txs.map((tx) => {
                    const isSuccess = tx.status === "SUCCESS";
                    const isFailed = tx.status === "FAILED";
                    const borderColor = isSuccess ? "#755b00" : isFailed ? "#ba1a1a" : "#FED665";
                    const bgColor = isSuccess ? "rgba(117,91,0,0.08)" : isFailed ? "rgba(186,26,26,0.08)" : "rgba(254,214,101,0.1)";

                    return (
                      <div
                        key={tx.id}
                        className="bg-white rounded-xl p-4 flex items-center justify-between hover:translate-x-1 transition-transform shadow-sm"
                        style={{ borderLeft: `4px solid ${borderColor}` }}
                      >
                        <div className="flex items-center gap-3">
                          <div
                            className="w-9 h-9 rounded-full flex items-center justify-center"
                            style={{ background: bgColor }}
                          >
                            <span
                              className="material-symbols-outlined text-[18px]"
                              style={{ color: borderColor, fontVariationSettings: "'FILL' 1" }}
                            >
                              {isSuccess ? "check_circle" : isFailed ? "cancel" : "schedule"}
                            </span>
                          </div>
                          <div>
                            <p className="font-semibold text-[#1a1c1c] text-sm">
                              {tx.booking?.package?.name ?? "Deposit"}
                            </p>
                            <p className="text-[#464651] text-xs">{formatDateTime(tx.createdAt)}</p>
                            {isFailed && (
                              <p className="text-[#767682] text-[10px] font-mono mt-0.5">
                                REF: {tx.gatewayReference.slice(-12)}
                              </p>
                            )}
                          </div>
                        </div>
                        <div className="text-right">
                          <p className="font-bold text-[#1a1c1c] text-sm">
                            {isSuccess ? "+" : ""}{formatNaira(Number(tx.amount))}
                          </p>
                          <span
                            className="text-[10px] font-bold px-2 py-0.5 rounded-full"
                            style={{ background: bgColor, color: borderColor }}
                          >
                            {tx.status.charAt(0) + tx.status.slice(1).toLowerCase()}
                          </span>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
