"use client";

import { useEffect, useState } from "react";
import { useRouter, useParams } from "next/navigation";
import Link from "next/link";
import { apiFetch } from "@/lib/apiClient";
import { formatNaira, formatDate, formatDateTime, getProgressPercent } from "@/lib/utils";

interface CustomerDetail {
  id: string;
  fullName: string;
  email: string;
  phone: string;
  isVerified: boolean;
  kycVerified: boolean;
  dob?: string;
  gender?: string;
  stateOfOrigin?: string;
  createdAt: string;
  bookings: Array<{
    id: string;
    status: string;
    totalPaid: number;
    createdAt: string;
    package: { name: string; slug: string; totalCost: number; departureDate: string };
    transactions: Array<{ id: string; amount: number; status: string; gatewayReference: string; createdAt: string }>;
  }>;
}

export default function CustomerDetailPage() {
  const router = useRouter();
  const { id } = useParams<{ id: string }>();
  const [customer, setCustomer] = useState<CustomerDetail | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    apiFetch<CustomerDetail>(`/admin/customers/${id}`)
      .then(setCustomer)
      .catch((err) => { if (err?.status === 401 || err?.status === 403) router.replace("/admin/login"); })
      .finally(() => setLoading(false));
  }, [id, router]);

  if (loading) {
    return (
      <div className="p-6 space-y-4">
        <div className="h-40 bg-white rounded-2xl animate-pulse" />
        <div className="h-60 bg-white rounded-2xl animate-pulse" />
      </div>
    );
  }

  if (!customer) return null;

  const totalSaved = customer.bookings.reduce((s, b) => s + b.totalPaid, 0);
  const initials = customer.fullName.split(" ").map((n) => n[0]).join("").slice(0, 2).toUpperCase();

  return (
    <div className="p-6 max-w-4xl">
      {/* Back */}
      <Link href="/admin/customers" className="inline-flex items-center gap-2 text-[#6B7280] text-sm mb-5 hover:text-[#111111]">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <path d="M19 12H5M12 19l-7-7 7-7"/>
        </svg>
        Back to Customers
      </Link>

      {/* Profile card */}
      <div className="bg-white rounded-2xl p-6 mb-5 flex items-start gap-5" style={{ boxShadow: "0 2px 12px rgba(0,0,0,0.04)" }}>
        <div className="w-16 h-16 rounded-2xl flex items-center justify-center flex-shrink-0"
          style={{ background: "#1C2472" }}>
          <span className="text-white font-black text-xl" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>{initials}</span>
        </div>
        <div className="flex-1 min-w-0">
          <div className="flex items-start justify-between">
            <div>
              <h1 className="font-black text-xl text-[#111111]" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>{customer.fullName}</h1>
              <p className="text-[#6B7280] text-sm">{customer.email}</p>
              <p className="text-[#9CA3AF] text-sm">{customer.phone}</p>
            </div>
            <div className="flex flex-col gap-1 items-end">
              <span className={`text-[10px] font-bold px-2 py-0.5 rounded-full ${customer.isVerified ? "bg-green-100 text-green-700" : "bg-amber-100 text-amber-700"}`}>
                {customer.isVerified ? "✓ Verified" : "Unverified"}
              </span>
              {customer.kycVerified && (
                <span className="text-[10px] font-bold px-2 py-0.5 rounded-full bg-blue-100 text-blue-700">KYC ✓</span>
              )}
            </div>
          </div>
          <div className="grid grid-cols-3 gap-4 mt-4 pt-4 border-t border-gray-50">
            <div>
              <p className="text-[#9CA3AF] text-xs uppercase tracking-wider mb-0.5">Total Saved</p>
              <p className="font-bold text-[#B8952A]">{formatNaira(totalSaved)}</p>
            </div>
            <div>
              <p className="text-[#9CA3AF] text-xs uppercase tracking-wider mb-0.5">Bookings</p>
              <p className="font-bold text-[#111111]">{customer.bookings.length}</p>
            </div>
            <div>
              <p className="text-[#9CA3AF] text-xs uppercase tracking-wider mb-0.5">Joined</p>
              <p className="font-bold text-[#111111]">{formatDate(customer.createdAt)}</p>
            </div>
          </div>
        </div>
      </div>

      {/* Bookings */}
      <h2 className="font-bold text-[#111111] mb-3" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>Savings Bookings</h2>
      {customer.bookings.length === 0 ? (
        <div className="bg-white rounded-2xl p-8 text-center" style={{ boxShadow: "0 2px 12px rgba(0,0,0,0.04)" }}>
          <p className="text-[#6B7280] text-sm">No bookings yet</p>
        </div>
      ) : (
        <div className="space-y-4">
          {customer.bookings.map((booking) => {
            const pct = getProgressPercent(booking.totalPaid, booking.package.totalCost);
            const statusColors: Record<string, string> = {
              SAVING: "#F59E0B", FULLY_FUNDED: "#B8952A", CONFIRMED: "#22C55E", CANCELLED: "#EF4444",
            };
            return (
              <div key={booking.id} className="bg-white rounded-2xl p-5" style={{ boxShadow: "0 2px 12px rgba(0,0,0,0.04)" }}>
                <div className="flex justify-between items-start mb-3">
                  <div>
                    <p className="font-bold text-[#111111]">{booking.package.name}</p>
                    <p className="text-[#9CA3AF] text-xs">Departure: {formatDate(booking.package.departureDate)}</p>
                  </div>
                  <span className="text-[10px] font-bold px-2 py-0.5 rounded-full"
                    style={{ background: `${statusColors[booking.status] ?? "#E5E7EB"}20`, color: statusColors[booking.status] ?? "#6B7280" }}>
                    {booking.status.replace("_", " ")}
                  </span>
                </div>
                <div className="mb-3">
                  <div className="flex justify-between text-sm mb-1">
                    <span className="text-[#6B7280]">{formatNaira(booking.totalPaid)} of {formatNaira(booking.package.totalCost)}</span>
                    <span className="text-[#B8952A] font-bold">{pct}%</span>
                  </div>
                  <div className="h-2 rounded-full bg-gray-100">
                    <div className="h-full rounded-full bg-[#B8952A] transition-all" style={{ width: `${pct}%` }} />
                  </div>
                </div>

                {booking.transactions.length > 0 && (
                  <div>
                    <p className="text-[#9CA3AF] text-xs uppercase tracking-wider mb-2">Recent Transactions</p>
                    <div className="space-y-1.5">
                      {booking.transactions.slice(0, 5).map((tx) => {
                        const isSuccess = tx.status === "SUCCESS";
                        const c = isSuccess ? "#B8952A" : tx.status === "FAILED" ? "#EF4444" : "#F59E0B";
                        return (
                          <div key={tx.id} className="flex justify-between items-center py-1.5 border-b border-gray-50 last:border-0">
                            <div>
                              <p className="text-[#111111] text-xs font-semibold">{formatNaira(tx.amount)}</p>
                              <p className="text-[#9CA3AF] text-[10px]">{formatDateTime(tx.createdAt)}</p>
                            </div>
                            <span className="text-[10px] font-bold px-2 py-0.5 rounded-full"
                              style={{ background: `${c}15`, color: c }}>
                              {tx.status}
                            </span>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
