"use client";

import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import {
  FaUser,
  FaMapMarkerAlt,
  FaBox,
  FaWallet,
  FaChevronRight,
  FaHome,
  FaArrowUp,
  FaArrowDown,
  FaCoins,
  FaHistory,
  FaInfoCircle
} from "react-icons/fa";

type WalletInfo = {
  user_id: string;
  coin_balance: number;
  total_earned: number;
  total_redeemed: number;
  last_updated: string;
};

type CoinConfig = {
  earn_rate_percent: number;
  coin_to_inr: number;
  is_active: boolean;
  updated_at: string;
};

type Transaction = {
  txn_id: string;
  user_id: string;
  txn_type: "CREDIT" | "DEBIT";
  coins: number;
  reference_id: string | null;
  note: string;
  created_at: string;
};

type UserProfile = {
  first_name: string;
  last_name: string;
  email: string;
};

export default function WalletPage() {
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [wallet, setWallet] = useState<WalletInfo | null>(null);
  const [config, setConfig] = useState<CoinConfig | null>(null);
  const [transactions, setTransactions] = useState<Transaction[]>([]);
  const [loading, setLoading] = useState(true);
  const [filterType, setFilterType] = useState<"ALL" | "CREDIT" | "DEBIT">("ALL");

  const router = useRouter();

  useEffect(() => {
    const token = localStorage.getItem("access_token");
    if (!token) {
      router.push("/login");
      return;
    }

    const fetchData = async () => {
      try {
        // Fetch Profile
        const profileRes = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/users/me`, {
          headers: { Authorization: `Bearer ${token}` }
        });
        if (profileRes.status === 401) {
          localStorage.removeItem("access_token");
          router.push("/login");
          return;
        }
        if (profileRes.ok) {
          setProfile(await profileRes.json());
        }

        // Fetch Wallet Info
        const walletRes = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/coins/my-wallet`, {
          headers: { Authorization: `Bearer ${token}` }
        });
        if (walletRes.ok) {
          setWallet(await walletRes.json());
        }

        // Fetch Config
        const configRes = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/coins/config`, {
          headers: { Authorization: `Bearer ${token}` }
        });
        if (configRes.ok) {
          setConfig(await configRes.json());
        }

        // Fetch Transactions
        const txnsRes = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/coins/my-transactions`, {
          headers: { Authorization: `Bearer ${token}` }
        });
        if (txnsRes.ok) {
          setTransactions(await txnsRes.json());
        }
      } catch (err) {
        console.error("Failed to fetch wallet/coins data:", err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [router]);

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
      </div>
    );
  }

  const initials = profile ? `${profile.first_name?.[0] || ""}${profile.last_name?.[0] || ""}`.toUpperCase() : "U";

  const coinBalance = wallet?.coin_balance ?? 0;
  const coinToInrRate = config?.coin_to_inr ?? 1.0;
  const inrEquivalent = coinBalance * coinToInrRate;

  const filteredTxns = transactions.filter(t => {
    if (filterType === "ALL") return true;
    return t.txn_type === filterType;
  });

  const formatDate = (dateString?: string | null) => {
    if (!dateString) return "N/A";
    try {
      return new Date(dateString).toLocaleDateString('en-IN', {
        year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit'
      });
    } catch {
      return dateString;
    }
  };

  return (
    <div className="bg-[#FAF9F6] min-h-screen py-10">
      <div className="max-w-6xl mx-auto px-4 sm:px-6">

        {/* Breadcrumb */}
        <div className="flex items-center gap-2 text-xs font-semibold text-gray-400 mb-8 select-none">
          <Link href="/" className="hover:text-primary transition-colors flex items-center gap-1">
            <FaHome className="text-[11px] mb-0.5" /> Home
          </Link>
          <FaChevronRight className="text-[8px]" />
          <Link href="/profile" className="hover:text-primary transition-colors">My Account</Link>
          <FaChevronRight className="text-[8px]" />
          <span className="text-gray-600">My Coins Wallet</span>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-4 gap-8 items-start">

          {/* Shared Sidebar */}
          <div className="col-span-1 flex flex-col gap-6 lg:sticky lg:top-28">
            <div className="bg-white rounded-[2rem] border border-gray-200/60 shadow-[0_4px_25px_rgba(0,0,0,0.02)] p-8 flex flex-col items-center text-center">
              <div
                style={{ backgroundColor: "#1e293b", color: "#ffffff" }}
                className="w-20 h-20 rounded-full flex items-center justify-center text-2xl font-black mb-4 shadow-md relative shrink-0"
              >
                {initials}
                <div className="absolute bottom-0 right-0 w-5 h-5 rounded-full bg-emerald-500 border-2 border-white flex items-center justify-center text-[10px] text-white">✓</div>
              </div>
              <div className="text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-1 select-none">Welcome Back,</div>
              <h2 className="text-xl font-extrabold text-gray-800 leading-tight">{profile?.first_name || "Dealer"}</h2>
            </div>

            <div className="bg-white rounded-[2rem] border border-gray-200/60 shadow-[0_4px_25px_rgba(0,0,0,0.02)] p-6 flex flex-col gap-6">
              <div>
                <h3 className="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-3 px-2">My Account</h3>
                <nav className="flex flex-col gap-1.5">
                  <Link href="/profile/order" className="flex items-center justify-between px-3 py-2.5 rounded-xl hover:bg-gray-50 text-xs font-bold text-gray-600 hover:text-gray-900 transition-colors">
                    <span className="flex items-center gap-2.5"><FaBox className="text-gray-400" /> MY ORDERS</span>
                    <FaChevronRight className="text-[8px] text-gray-400" />
                  </Link>
                  <Link href="/profile" className="flex items-center justify-between px-3 py-2.5 rounded-xl hover:bg-gray-50 text-xs font-bold text-gray-600 hover:text-gray-900 transition-colors">
                    <span className="flex items-center gap-2.5"><FaUser className="text-gray-400" /> MY PROFILE</span>
                    <FaChevronRight className="text-[8px] text-gray-400" />
                  </Link>
                </nav>
              </div>

              <div className="border-t border-gray-100"></div>

              <div>
                <h3 className="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-3 px-2">Reward Coins</h3>
                <nav className="flex flex-col gap-1.5">
                  <Link href="/profile/wallet" className="flex items-center justify-between px-3 py-2.5 rounded-xl bg-primary-light text-primary text-xs font-bold transition-colors">
                    <span className="flex items-center gap-2.5">🪙 MY COINS</span>
                    <FaChevronRight className="text-[8px]" />
                  </Link>
                </nav>
              </div>
            </div>
          </div>

          {/* Right Column: Wallet Info & Transactions */}
          <div className="col-span-1 lg:col-span-3 flex flex-col gap-6">

            {/* Header Area */}
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 select-none">
              <div>
                <div className="text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-0.5">Rewards Ledger</div>
                <h2 className="text-xl font-black text-gray-900 uppercase tracking-tight">Reward Coins Wallet</h2>
              </div>
            </div>

            {/* Premium Wallet Dashboard Cards */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">

              {/* Primary Balance Card */}
              <div className="bg-gradient-to-br from-slate-900 to-slate-850 text-white rounded-[2rem] p-6 shadow-lg border border-slate-800 relative overflow-hidden flex flex-col justify-between min-h-[160px]">
                <div className="absolute top-[-20%] right-[-10%] opacity-10 text-9xl">
                  <FaCoins />
                </div>
                <div className="flex justify-between items-start">
                  <div>
                    <span className="text-[10px] font-black tracking-widest uppercase text-gray-400">Available Balance</span>
                    <h3 className="text-3xl font-black mt-1 flex items-center gap-2 text-amber-400">
                      🪙 {Math.round(coinBalance).toLocaleString("en-IN")}
                    </h3>
                  </div>
                  <span className="text-xs font-bold bg-amber-500/10 text-amber-400 border border-amber-500/20 px-2.5 py-1 rounded-full">
                    Active
                  </span>
                </div>
                <div className="border-t border-slate-800/80 pt-4 mt-4 flex justify-between items-center text-xs text-gray-300">
                  <span>Value equivalent:</span>
                  <span className="font-extrabold text-white text-sm">${inrEquivalent.toFixed(2)}</span>
                </div>
              </div>

              {/* Earned Card */}
              <div className="bg-white rounded-[2rem] p-6 shadow-[0_4px_25px_rgba(0,0,0,0.02)] border border-gray-200/60 flex flex-col justify-between min-h-[160px]">
                <div className="flex justify-between items-start">
                  <div>
                    <span className="text-[10px] font-black tracking-widest uppercase text-gray-400">Total Coins Earned</span>
                    <h3 className="text-2xl font-black mt-2 text-emerald-600 flex items-center gap-1.5">
                      <FaArrowUp className="text-xs" /> {Math.round(wallet?.total_earned ?? 0).toLocaleString("en-IN")}
                    </h3>
                  </div>
                  <div className="w-9 h-9 rounded-xl bg-emerald-50 border border-emerald-100 flex items-center justify-center text-emerald-500">
                    <FaArrowUp size={12} />
                  </div>
                </div>
                <p className="text-[10px] text-gray-400 font-bold border-t border-gray-100 pt-4">
                  * 1 Coin = ${ (1 / coinToInrRate).toFixed(0) } worth of shopping discount
                </p>
              </div>

              {/* Redeemed Card */}
              <div className="bg-white rounded-[2rem] p-6 shadow-[0_4px_25px_rgba(0,0,0,0.02)] border border-gray-200/60 flex flex-col justify-between min-h-[160px]">
                <div className="flex justify-between items-start">
                  <div>
                    <span className="text-[10px] font-black tracking-widest uppercase text-gray-400">Total Coins Used</span>
                    <h3 className="text-2xl font-black mt-2 text-rose-500 flex items-center gap-1.5">
                      <FaArrowDown className="text-xs" /> {Math.round(wallet?.total_redeemed ?? 0).toLocaleString("en-IN")}
                    </h3>
                  </div>
                  <div className="w-9 h-9 rounded-xl bg-rose-50 border border-rose-100 flex items-center justify-center text-rose-500">
                    <FaArrowDown size={12} />
                  </div>
                </div>
                <p className="text-[10px] text-gray-400 font-bold border-t border-gray-100 pt-4">
                  Last updated: {wallet?.last_updated ? new Date(wallet.last_updated).toLocaleDateString('en-IN') : 'Never'}
                </p>
              </div>
            </div>

            {/* Info Message */}
            <div className="bg-amber-50 border border-amber-200 rounded-2xl p-4 flex gap-3 text-xs text-amber-800">
              <FaInfoCircle className="shrink-0 mt-0.5 text-sm" />
              <div>
                <span className="font-extrabold uppercase tracking-wide mr-1.5">Reward Config:</span>
                Earn <b>{config?.earn_rate_percent ?? 2}%</b> in Coins on every successful order total! Apply your accumulated coins at checkout to redeem instant discount on purchases.
              </div>
            </div>

            {/* Transaction Ledger Table Card */}
            <div className="bg-white rounded-[2rem] border border-gray-200/60 shadow-[0_4px_25px_rgba(0,0,0,0.02)] p-6">

              {/* Header inside table card */}
              <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 pb-6 border-b border-gray-100 select-none">
                <div className="flex items-center gap-2">
                  <FaHistory className="text-gray-400" />
                  <h3 className="font-black text-gray-800 text-sm uppercase tracking-wider">Transaction Ledger</h3>
                </div>

                {/* Filters */}
                <div className="flex gap-1.5 bg-gray-50 border border-gray-200 p-1 rounded-xl text-[10px] font-bold">
                  {(["ALL", "CREDIT", "DEBIT"] as const).map(type => (
                    <button
                      key={type}
                      onClick={() => setFilterType(type)}
                      className={`px-3 py-1.5 rounded-lg uppercase tracking-wider transition-all ${filterType === type
                          ? 'bg-slate-900 text-white shadow-sm'
                          : 'text-gray-500 hover:text-gray-800'
                        }`}
                    >
                      {type === "ALL" ? "All Txns" : type === "CREDIT" ? "Earned" : "Spent"}
                    </button>
                  ))}
                </div>
              </div>

              {/* Transactions Feed */}
              {filteredTxns.length === 0 ? (
                <div className="py-16 flex flex-col items-center justify-center text-center">
                  <div className="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center text-gray-300 mb-4">
                    <FaCoins className="text-3xl" />
                  </div>
                  <h3 className="text-base font-bold text-gray-900 mb-2">No Transactions Found</h3>
                  <p className="text-xs text-gray-505 font-semibold max-w-xs leading-relaxed">
                    There are no transactions matching your selected filters yet.
                  </p>
                </div>
              ) : (
                <div className="overflow-x-auto mt-4">
                  <table className="w-full text-left border-collapse">
                    <thead>
                      <tr className="border-b border-gray-100 text-[10px] font-black text-gray-400 uppercase tracking-widest">
                        <th className="py-4 px-3">Transaction ID</th>
                        <th className="py-4 px-3">Date</th>
                        <th className="py-4 px-3">Reference</th>
                        <th className="py-4 px-3">Type</th>
                        <th className="py-4 px-3">Details</th>
                        <th className="py-4 px-3 text-right">Coins</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-50 text-xs">
                      {filteredTxns.map((txn, idx) => {
                        const isCredit = txn.txn_type === "CREDIT";

                        return (
                          <tr key={txn.txn_id || idx} className="hover:bg-gray-50/50 transition-colors group">
                            {/* Txn ID */}
                            <td className="py-4 px-3 font-black text-gray-800 uppercase tracking-tight">
                              {txn.txn_id}
                            </td>
                            {/* Date */}
                            <td className="py-4 px-3 text-gray-500 font-semibold">
                              {formatDate(txn.created_at)}
                            </td>
                            {/* Reference */}
                            <td className="py-4 px-3">
                              {txn.reference_id ? (
                                <Link
                                  href={`/profile/order/${txn.reference_id}`}
                                  className="text-primary font-black uppercase hover:underline"
                                >
                                  {txn.reference_id}
                                </Link>
                              ) : (
                                <span className="text-gray-400 font-bold">Admin Adjustment</span>
                              )}
                            </td>
                            {/* Type */}
                            <td className="py-4 px-3">
                              <span className={`inline-flex items-center gap-1 text-[9px] font-extrabold tracking-wider uppercase px-2.5 py-0.5 border rounded-full ${isCredit
                                  ? 'bg-emerald-50 text-emerald-700 border-emerald-100'
                                  : 'bg-rose-50 text-rose-700 border-rose-100'
                                }`}>
                                {isCredit ? "Credit" : "Debit"}
                              </span>
                            </td>
                            {/* Note */}
                            <td className="py-4 px-3 text-gray-600 font-semibold">
                              {txn.note}
                            </td>
                            {/* Coins Value */}
                            <td className={`py-4 px-3 text-right font-black text-sm select-none ${isCredit ? 'text-emerald-600' : 'text-rose-500'
                              }`}>
                              {isCredit ? '+' : '-'}{Math.round(txn.coins)}
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              )}

            </div>

          </div>
        </div>
      </div>
    </div>
  );
}
