"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/context/AuthContext";
import { apiFetch, ApiError } from "@/lib/apiClient";
import { formatNaira, getProgressPercent } from "@/lib/utils";
import type { Booking } from "@/types";

const QUICK_AMOUNTS = [5000, 10000, 50000, 100000];

export default function DepositPage() {
  const router = useRouter();
  const { user, isLoading, isAuthenticated } = useAuth();
  const [bookings, setBookings] = useState<Booking[]>([]);
  const [selectedBookingId, setSelectedBookingId] = useState<string>("");
  const [amount, setAmount] = useState("");
  const [paymentMethod, setPaymentMethod] = useState<"card" | "bank">("card");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [dataLoading, setDataLoading] = useState(true);

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

  useEffect(() => {
    if (!isAuthenticated) return;
    apiFetch<Booking[]>("/bookings")
      .then((data) => {
        const active = (Array.isArray(data) ? data : (data as any).bookings ?? [])
          .filter((b: Booking) => b.status === "SAVING");
        setBookings(active);
        if (active.length > 0) setSelectedBookingId(active[0].id);
      })
      .catch(console.error)
      .finally(() => setDataLoading(false));
  }, [isAuthenticated]);

  const selectedBooking = bookings.find((b) => b.id === selectedBookingId);
  const amountNum = parseFloat(amount.replace(/,/g, "")) || 0;
  const fee = amountNum > 0 ? Math.round(amountNum * 0.015 * 100 + 10000) / 100 : 0;
  const totalCharged = amountNum + fee;
  const packageTotal = Number((selectedBooking as any)?.package?.totalCost ?? 0);
  const currentPct = selectedBooking ? getProgressPercent(Number(selectedBooking.totalPaid), packageTotal) : 0;
  const newBalance = selectedBooking ? Number(selectedBooking.totalPaid) + amountNum : amountNum;
  const newPct = packageTotal > 0 ? getProgressPercent(newBalance, packageTotal) : 0;

  async function handleProceed() {
    if (!selectedBookingId) { setError("Please select a booking"); return; }
    if (amountNum < 100) { setError("Minimum deposit is ₦100"); return; }
    setError("");
    setLoading(true);
    try {
      const data = await apiFetch<{ authorizationUrl: string }>("/payments/initiate", {
        method: "POST",
        body: JSON.stringify({ bookingId: selectedBookingId, amountNaira: amountNum }),
      });
      window.location.href = data.authorizationUrl;
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "Could not initiate payment");
      setLoading(false);
    }
  }

  if (isLoading || !user) {
    return (
      <div className="min-h-screen bg-[#f9f9f9] flex items-center justify-center">
        <div className="w-8 h-8 rounded-full border-2 border-[#040b61] border-t-transparent animate-spin" />
      </div>
    );
  }

  return (
    <div className="bg-[#f9f9f9] min-h-screen text-[#1a1c1c]">
      <main className="max-w-[430px] mx-auto min-h-screen relative flex flex-col pb-36">

        {/* Top App Bar */}
        <header className="fixed top-0 w-full max-w-[430px] h-16 flex items-center justify-between px-5 bg-[rgba(249,249,249,0.7)] backdrop-blur-xl z-50 border-b border-[#c6c5d3]/20">
          <button
            onClick={() => router.back()}
            className="w-10 h-10 flex items-center justify-center rounded-full hover:bg-[#e2e2e2] transition-colors"
          >
            <span className="material-symbols-outlined text-[#1a1c1c]">arrow_back</span>
          </button>
          <h1 className="font-headline-md text-[#1a1c1c] flex items-center gap-2 text-[20px] font-bold">
            Make a Deposit
            <span className="material-symbols-outlined text-[#FED665] text-[20px]" style={{ fontVariationSettings: "'FILL' 1" }}>lock</span>
          </h1>
          <div className="w-10" />
        </header>

        <div className="pt-20 px-5 space-y-6">
          {/* Balance Card */}
          {selectedBooking ? (
            <div className="relative overflow-hidden rounded-3xl p-6 text-white shadow-[0_32px_64px_-12px_rgba(1,7,95,0.12)]"
              style={{ background: "linear-gradient(135deg, #0D1145 0%, #1C2472 50%, #2D3896 100%)" }}>
              {bookings.length > 1 && (
                <select
                  value={selectedBookingId}
                  onChange={(e) => setSelectedBookingId(e.target.value)}
                  className="mb-2 bg-white/10 border border-white/20 text-white text-sm rounded-lg px-3 py-1 w-full"
                >
                  {bookings.map((b) => (
                    <option key={b.id} value={b.id}>{(b as any).package?.name}</option>
                  ))}
                </select>
              )}
              <div className="relative z-10">
                <p className="text-white/70 text-[14px] font-semibold mb-1">
                  {(selectedBooking as any).package?.name ?? "My Package"}
                </p>
                <h2 className="font-headline-lg text-[40px] font-bold tracking-tight mb-4">
                  {formatNaira(Number(selectedBooking.totalPaid))}
                </h2>
                <div className="space-y-2">
                  <div className="flex justify-between items-center text-[10px] font-semibold">
                    <span>{currentPct}% Funded</span>
                    <span>Target: {formatNaira(packageTotal)}</span>
                  </div>
                  <div className="h-2 w-full bg-white/20 rounded-full overflow-hidden">
                    <div
                      className="h-full bg-[#FED665] rounded-full shadow-[0_0_12px_rgba(254,214,101,0.5)] transition-all"
                      style={{ width: `${currentPct}%` }}
                    />
                  </div>
                </div>
              </div>
            </div>
          ) : !dataLoading ? (
            <div className="bg-white rounded-3xl p-8 text-center shadow-sm">
              <span className="material-symbols-outlined text-[#767682] text-5xl mb-4 block">account_balance_wallet</span>
              <p className="text-[#464651] text-sm mb-4">No active savings booking yet.</p>
              <button
                onClick={() => router.push("/packages")}
                className="bg-[#040b61] text-white px-6 py-3 rounded-full font-semibold text-sm"
              >
                Browse Packages
              </button>
            </div>
          ) : (
            <div className="h-32 bg-[#e8e8e8] rounded-3xl animate-pulse" />
          )}

          {/* Amount Input */}
          {bookings.length > 0 && (
            <>
              <div className="space-y-4">
                <label className="text-[14px] font-semibold text-[#464651] block">Enter Amount</label>
                <div className="relative group">
                  <div className="absolute left-0 bottom-2 text-[#1a1c1c] font-bold text-[32px] pr-1 border-r-2 border-transparent">₦</div>
                  <input
                    type="text"
                    inputMode="numeric"
                    value={amount}
                    onChange={(e) => {
                      const raw = e.target.value.replace(/[^0-9]/g, "");
                      setAmount(raw ? Number(raw).toLocaleString() : "");
                    }}
                    placeholder="0"
                    className="w-full bg-transparent border-b-2 border-[#c6c5d3] focus:border-[#FED665] pl-10 pb-2 text-[#1a1c1c] font-bold text-[32px] outline-none transition-colors"
                    style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}
                  />
                </div>

                {/* Quick Amount Pills */}
                <div className="flex flex-wrap gap-2">
                  {QUICK_AMOUNTS.map((a) => (
                    <button
                      key={a}
                      onClick={() => setAmount(a.toLocaleString())}
                      className="px-5 py-2 rounded-full text-[14px] font-semibold border transition-all duration-200"
                      style={amount === a.toLocaleString()
                        ? { background: "#FED665", color: "#040b61", border: "1px solid #FED665" }
                        : { background: "#e8e8e8", color: "#1a1c1c", border: "1px solid rgba(198,197,211,0.3)" }}
                    >
                      ₦{a >= 1000 ? `${a / 1000}k` : a}
                    </button>
                  ))}
                </div>
              </div>

              {/* Summary */}
              {amountNum > 0 && (
                <div className="bg-white/70 backdrop-blur-xl rounded-2xl p-4 border border-[#c6c5d3]/20 shadow-sm space-y-3 transition-all">
                  <div className="flex justify-between items-center text-[16px] text-[#464651]">
                    <span>Processing Fee (1.5%)</span>
                    <span className="text-[#1a1c1c]">{formatNaira(fee)}</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-[16px] text-[#464651]">New Balance</span>
                    <div className="text-right">
                      <span className="font-headline-md text-[#755b00] block text-[20px] font-bold">{formatNaira(newBalance)}</span>
                      <span className="text-[10px] font-semibold text-[#755b00]">{newPct}% Progress</span>
                    </div>
                  </div>
                </div>
              )}

              {/* Payment Methods */}
              <div className="space-y-3">
                <p className="text-[14px] font-semibold text-[#464651]">Select Payment Method</p>
                <div className="grid grid-cols-1 gap-3">
                  <button
                    onClick={() => setPaymentMethod("card")}
                    className="flex items-center gap-4 p-4 rounded-2xl border-2 transition-all"
                    style={paymentMethod === "card"
                      ? { borderColor: "#755b00", background: "rgba(254,217,121,0.1)" }
                      : { borderColor: "#c6c5d3", background: "#ffffff" }}
                  >
                    <div className="w-10 h-10 rounded-xl bg-[#0D1145] flex items-center justify-center">
                      <span className="material-symbols-outlined text-[#FED665]">credit_card</span>
                    </div>
                    <div className="flex-1 text-left">
                      <p className="text-[14px] font-semibold text-[#1a1c1c]">Debit/Credit Card</p>
                      <p className="text-[10px] text-[#464651]">Instant confirmation</p>
                    </div>
                    <div className="w-6 h-6 rounded-full border-2 border-[#755b00] flex items-center justify-center">
                      {paymentMethod === "card" && <div className="w-3 h-3 rounded-full bg-[#755b00]" />}
                    </div>
                  </button>

                  <button
                    onClick={() => setPaymentMethod("bank")}
                    className="flex items-center gap-4 p-4 rounded-2xl border transition-all"
                    style={paymentMethod === "bank"
                      ? { borderColor: "#755b00", background: "rgba(254,217,121,0.1)" }
                      : { borderColor: "#c6c5d3", background: "#ffffff" }}
                  >
                    <div className="w-10 h-10 rounded-xl bg-[#e8e8e8] flex items-center justify-center">
                      <span className="material-symbols-outlined text-[#464651]">account_balance</span>
                    </div>
                    <div className="flex-1 text-left">
                      <p className="text-[14px] font-semibold text-[#1a1c1c]">Bank Transfer</p>
                      <p className="text-[10px] text-[#464651]">2–5 mins confirmation</p>
                    </div>
                    <div className="w-6 h-6 rounded-full border border-[#c6c5d3]">
                      {paymentMethod === "bank" && <div className="w-3 h-3 rounded-full bg-[#755b00] m-auto mt-1" />}
                    </div>
                  </button>
                </div>
              </div>

              {/* Trust Badge */}
              <div className="flex flex-col items-center justify-center gap-2 pt-2 opacity-60">
                <div className="flex items-center gap-1">
                  <span className="material-symbols-outlined text-sm">shield</span>
                  <span className="text-[10px] font-semibold">Secured by PalmPay</span>
                </div>
              </div>

              {error && (
                <div className="p-3 rounded-xl bg-red-50 border border-red-200 text-red-600 text-sm text-center">
                  {error}
                </div>
              )}
            </>
          )}
        </div>

        {/* Sticky Footer CTA */}
        {bookings.length > 0 && (
          <footer className="sticky bottom-0 px-5 py-4 bg-[rgba(249,249,249,0.9)] backdrop-blur-xl mt-auto">
            <button
              onClick={handleProceed}
              disabled={loading || amountNum < 100}
              className="w-full h-16 bg-[#0D1145] text-white rounded-2xl font-bold text-[18px] flex items-center justify-center gap-3 active:scale-95 transition-transform shadow-xl shadow-[#0D1145]/20 disabled:opacity-50"
            >
              {loading ? (
                <>
                  <span className="material-symbols-outlined animate-spin">progress_activity</span>
                  Redirecting to PalmPay...
                </>
              ) : (
                <>
                  Proceed to Payment
                  <span className="material-symbols-outlined">arrow_forward</span>
                </>
              )}
            </button>
          </footer>
        )}
      </main>
    </div>
  );
}
