"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 } from "@/lib/utils";
import type { Booking } from "@/types";

type Step = "form" | "confirm" | "done";

const BANKS = [
  "Access Bank", "GTBank", "First Bank", "Zenith Bank", "UBA",
  "Fidelity Bank", "Sterling Bank", "Union Bank", "Wema Bank",
  "Polaris Bank", "Keystone Bank", "Heritage Bank", "Opay",
  "Kuda Bank", "Moniepoint", "PalmPay", "Carbon", "Other",
];

export default function WithdrawalPage() {
  const router = useRouter();
  const { user, isLoading, isAuthenticated } = useAuth();

  const [bookings, setBookings] = useState<Booking[]>([]);
  const [dataLoading, setDataLoading] = useState(true);
  const [step, setStep] = useState<Step>("form");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");

  // Form fields
  const [selectedBookingId, setSelectedBookingId] = useState("");
  const [reason, setReason] = useState("");
  const [bankName, setBankName] = useState("");
  const [accountNo, setAccountNo] = useState("");
  const [accountName, setAccountName] = useState("");

  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 !== "CANCELLED");
        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 totalPaid = Number(selectedBooking?.totalPaid ?? 0);
  const penaltyAmt = totalPaid * 0.1;
  const netPayout = totalPaid - penaltyAmt;

  function validate(): string {
    if (!selectedBookingId) return "Please select a booking";
    if (totalPaid <= 0) return "No funds available to withdraw";
    if (reason.trim().length < 10) return "Please enter a detailed reason (minimum 10 characters)";
    if (!bankName) return "Please select your bank";
    if (accountNo.replace(/\D/g, "").length !== 10) return "Account number must be exactly 10 digits";
    if (accountName.trim().length < 3) return "Please enter your account name";
    return "";
  }

  function handleContinue() {
    const err = validate();
    if (err) { setError(err); return; }
    setError("");
    setStep("confirm");
  }

  async function handleSubmit() {
    setSubmitting(true);
    setError("");
    try {
      await apiFetch("/withdrawals", {
        method: "POST",
        body: JSON.stringify({
          bookingId: selectedBookingId,
          reason: reason.trim(),
          bankName,
          accountNo: accountNo.replace(/\D/g, ""),
          accountName: accountName.trim(),
        }),
      });
      setStep("done");
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "Could not submit request. Please try again.");
      setStep("form");
    } finally {
      setSubmitting(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 flex flex-col pb-36">

        {/* Header */}
        <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.9)] backdrop-blur-xl z-50 border-b border-[#c6c5d3]/20">
          <button
            onClick={() => step === "confirm" ? setStep("form") : 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-bold text-[18px] text-[#1a1c1c]">
            {step === "done" ? "Request Submitted" : "Request Withdrawal"}
          </h1>
          <div className="w-10" />
        </header>

        <div className="pt-20 px-5">

          {/* ── DONE STATE ── */}
          {step === "done" && (
            <div className="flex flex-col items-center justify-center pt-16 text-center gap-6">
              <div className="w-24 h-24 rounded-full flex items-center justify-center"
                style={{ background: "linear-gradient(135deg, #040b61, #1C2472)" }}>
                <span className="material-symbols-outlined text-[#FED665] text-5xl"
                  style={{ fontVariationSettings: "'FILL' 1" }}>task_alt</span>
              </div>
              <div>
                <h2 className="text-2xl font-black text-[#1a1c1c] mb-2">Request Received</h2>
                <p className="text-[#464651] text-sm leading-relaxed max-w-xs">
                  Your withdrawal request has been submitted. Our team will review it within
                  <strong> 3–5 business days</strong> and contact you on your registered details.
                </p>
              </div>
              <div className="w-full bg-white rounded-2xl p-5 border border-[#c6c5d3]/20 text-left space-y-3">
                <div className="flex justify-between text-sm">
                  <span className="text-[#767682]">Savings Amount</span>
                  <span className="font-bold text-[#1a1c1c]">{formatNaira(totalPaid)}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-[#767682]">Processing Fee (10%)</span>
                  <span className="font-bold text-red-500">− {formatNaira(penaltyAmt)}</span>
                </div>
                <div className="h-px bg-[#c6c5d3]/30" />
                <div className="flex justify-between">
                  <span className="font-bold text-[#1a1c1c]">Net Payout</span>
                  <span className="font-black text-[#755b00] text-lg">{formatNaira(netPayout)}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-[#767682]">To Account</span>
                  <span className="font-semibold text-[#1a1c1c]">{bankName} • {accountNo.slice(-4).padStart(accountNo.length, "•")}</span>
                </div>
              </div>
              <button
                onClick={() => router.push("/dashboard")}
                className="w-full h-14 bg-[#0D1145] text-white rounded-2xl font-bold text-base"
              >
                Back to Dashboard
              </button>
            </div>
          )}

          {/* ── CONFIRM STATE ── */}
          {step === "confirm" && (
            <div className="space-y-5 pt-4">
              {/* Warning */}
              <div className="flex gap-3 p-4 rounded-2xl border border-amber-200 bg-amber-50">
                <span className="material-symbols-outlined text-amber-500 text-xl shrink-0 mt-0.5"
                  style={{ fontVariationSettings: "'FILL' 1" }}>warning</span>
                <div>
                  <p className="font-bold text-amber-800 text-sm mb-1">Please read before confirming</p>
                  <p className="text-amber-700 text-xs leading-relaxed">
                    A <strong>10% processing fee</strong> will be deducted from your total savings.
                    Your booking will be <strong>cancelled</strong> once withdrawal is approved.
                    This action cannot be undone.
                  </p>
                </div>
              </div>

              {/* Breakdown */}
              <div className="bg-white rounded-3xl p-6 border border-[#c6c5d3]/20 space-y-4 shadow-sm">
                <h3 className="font-black text-[#1a1c1c] text-base">Withdrawal Summary</h3>
                <div className="space-y-3">
                  <div className="flex justify-between text-sm">
                    <span className="text-[#767682]">Booking</span>
                    <span className="font-semibold">{(selectedBooking as any)?.package?.name}</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-[#767682]">Total Saved</span>
                    <span className="font-semibold">{formatNaira(totalPaid)}</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-[#767682]">Processing Fee (10%)</span>
                    <span className="font-semibold text-red-500">− {formatNaira(penaltyAmt)}</span>
                  </div>
                  <div className="h-px bg-[#c6c5d3]/30" />
                  <div className="flex justify-between">
                    <span className="font-bold text-[#1a1c1c]">You Receive</span>
                    <span className="font-black text-[#755b00] text-xl">{formatNaira(netPayout)}</span>
                  </div>
                </div>
                <div className="pt-2 border-t border-[#c6c5d3]/20 space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-[#767682]">Bank</span>
                    <span className="font-semibold">{bankName}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-[#767682]">Account No.</span>
                    <span className="font-semibold">{accountNo}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-[#767682]">Account Name</span>
                    <span className="font-semibold">{accountName}</span>
                  </div>
                </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 className="flex gap-3 pt-2">
                <button
                  onClick={() => setStep("form")}
                  className="flex-1 h-14 rounded-2xl border-2 border-[#c6c5d3] text-[#464651] font-bold"
                >
                  Go Back
                </button>
                <button
                  onClick={handleSubmit}
                  disabled={submitting}
                  className="flex-1 h-14 rounded-2xl bg-red-600 text-white font-bold flex items-center justify-center gap-2 disabled:opacity-60"
                >
                  {submitting
                    ? <span className="material-symbols-outlined animate-spin">progress_activity</span>
                    : "Confirm Request"}
                </button>
              </div>
            </div>
          )}

          {/* ── FORM STATE ── */}
          {step === "form" && (
            <div className="space-y-6 pt-4">

              {/* Policy Banner */}
              <div className="rounded-2xl p-4 border border-[#040b61]/20 bg-[#040b61]/5">
                <div className="flex items-center gap-2 mb-2">
                  <span className="material-symbols-outlined text-[#040b61] text-base"
                    style={{ fontVariationSettings: "'FILL' 1" }}>info</span>
                  <p className="font-bold text-[#040b61] text-sm">Withdrawal Policy</p>
                </div>
                <ul className="text-xs text-[#464651] space-y-1 leading-relaxed">
                  <li>• A <strong>10% processing fee</strong> is deducted from total savings</li>
                  <li>• Processing takes <strong>3–5 business days</strong> after approval</li>
                  <li>• Not available within <strong>30 days</strong> of departure</li>
                  <li>• Your booking will be <strong>cancelled</strong> upon approval</li>
                </ul>
              </div>

              {/* Booking Selector */}
              <div className="space-y-2">
                <label className="text-sm font-bold text-[#464651]">Select Booking</label>
                {dataLoading ? (
                  <div className="h-14 bg-[#e8e8e8] rounded-2xl animate-pulse" />
                ) : bookings.length === 0 ? (
                  <p className="text-sm text-[#767682] text-center py-4">No active bookings found.</p>
                ) : (
                  <select
                    value={selectedBookingId}
                    onChange={(e) => setSelectedBookingId(e.target.value)}
                    className="w-full h-14 px-4 rounded-2xl border border-[#c6c5d3] bg-white text-[#1a1c1c] font-semibold text-sm appearance-none"
                  >
                    {bookings.map((b) => (
                      <option key={b.id} value={b.id}>
                        {(b as any).package?.name} — {formatNaira(Number(b.totalPaid))} saved
                      </option>
                    ))}
                  </select>
                )}
              </div>

              {selectedBooking && totalPaid > 0 && (
                <div className="rounded-2xl p-4 bg-white border border-[#c6c5d3]/20 shadow-sm flex justify-between items-center">
                  <div>
                    <p className="text-xs text-[#767682] mb-0.5">You Will Receive</p>
                    <p className="text-2xl font-black text-[#755b00]">{formatNaira(netPayout)}</p>
                    <p className="text-xs text-[#767682]">after 10% fee ({formatNaira(penaltyAmt)} deducted)</p>
                  </div>
                  <div className="text-right">
                    <p className="text-xs text-[#767682] mb-0.5">Total Saved</p>
                    <p className="text-lg font-bold text-[#1a1c1c]">{formatNaira(totalPaid)}</p>
                  </div>
                </div>
              )}

              {/* Reason */}
              <div className="space-y-2">
                <label className="text-sm font-bold text-[#464651]">Reason for Withdrawal</label>
                <textarea
                  value={reason}
                  onChange={(e) => setReason(e.target.value)}
                  placeholder="Please explain why you need to withdraw your savings..."
                  rows={3}
                  className="w-full px-4 py-3 rounded-2xl border border-[#c6c5d3] bg-white text-[#1a1c1c] text-sm resize-none focus:border-[#FED665] outline-none transition-colors"
                />
                <p className="text-xs text-[#767682] text-right">{reason.length} chars (min 10)</p>
              </div>

              {/* Bank Details */}
              <div className="space-y-4">
                <p className="text-sm font-bold text-[#464651]">Bank Details for Payout</p>

                <div className="space-y-2">
                  <label className="text-xs font-semibold text-[#767682] uppercase tracking-wide">Bank Name</label>
                  <select
                    value={bankName}
                    onChange={(e) => setBankName(e.target.value)}
                    className="w-full h-14 px-4 rounded-2xl border border-[#c6c5d3] bg-white text-[#1a1c1c] text-sm appearance-none"
                  >
                    <option value="">Select your bank</option>
                    {BANKS.map((b) => <option key={b} value={b}>{b}</option>)}
                  </select>
                </div>

                <div className="space-y-2">
                  <label className="text-xs font-semibold text-[#767682] uppercase tracking-wide">Account Number</label>
                  <input
                    type="text"
                    inputMode="numeric"
                    maxLength={10}
                    value={accountNo}
                    onChange={(e) => setAccountNo(e.target.value.replace(/\D/g, "").slice(0, 10))}
                    placeholder="0123456789"
                    className="w-full h-14 px-4 rounded-2xl border border-[#c6c5d3] bg-white text-[#1a1c1c] text-sm font-mono tracking-widest focus:border-[#FED665] outline-none transition-colors"
                  />
                </div>

                <div className="space-y-2">
                  <label className="text-xs font-semibold text-[#767682] uppercase tracking-wide">Account Name</label>
                  <input
                    type="text"
                    value={accountName}
                    onChange={(e) => setAccountName(e.target.value)}
                    placeholder="As it appears on your bank account"
                    className="w-full h-14 px-4 rounded-2xl border border-[#c6c5d3] bg-white text-[#1a1c1c] text-sm focus:border-[#FED665] outline-none transition-colors"
                  />
                </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>
              )}

              <button
                onClick={handleContinue}
                disabled={!selectedBookingId || totalPaid <= 0}
                className="w-full h-14 bg-[#0D1145] text-white rounded-2xl font-bold text-base flex items-center justify-center gap-2 disabled:opacity-40 mt-2"
              >
                Continue
                <span className="material-symbols-outlined">arrow_forward</span>
              </button>
            </div>
          )}
        </div>
      </main>
    </div>
  );
}
