"use client";

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

interface Customer {
  id: string;
  fullName: string;
  email: string;
  phone: string;
  isVerified: boolean;
  kycVerified: boolean;
  createdAt: string;
  _count: { bookings: number };
  bookings: Array<{ totalPaid: number; status: string }>;
}

export default function AdminCustomersPage() {
  const router = useRouter();
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const PAGE_SIZE = 20;

  useEffect(() => {
    setLoading(true);
    const q = new URLSearchParams({ page: String(page), limit: String(PAGE_SIZE) });
    if (search) q.set("search", search);
    apiFetch<{ users: Customer[]; total: number }>(`/admin/customers?${q}`)
      .then((d) => { setCustomers(d.users); setTotal(d.total); })
      .catch((err) => { if (err?.status === 401 || err?.status === 403) router.replace("/admin/login"); })
      .finally(() => setLoading(false));
  }, [page, search, router]);

  const totalSaved = (c: Customer) => c.bookings.reduce((s, b) => s + Number(b.totalPaid), 0);

  return (
    <div className="p-6 max-w-7xl">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-[#111111] font-black text-2xl" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>Customers</h1>
          <p className="text-[#6B7280] text-sm mt-0.5">{total} registered customers</p>
        </div>
      </div>

      {/* Search */}
      <div className="bg-white rounded-2xl p-4 mb-4 flex gap-3" style={{ boxShadow: "0 2px 12px rgba(0,0,0,0.04)" }}>
        <input
          type="text"
          value={search}
          onChange={(e) => { setSearch(e.target.value); setPage(1); }}
          placeholder="Search by name, email or phone..."
          className="flex-1 text-sm text-[#111111] outline-none placeholder:text-[#9CA3AF]"
        />
        {search && (
          <button onClick={() => { setSearch(""); setPage(1); }} className="text-[#9CA3AF] hover:text-[#6B7280]">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/>
            </svg>
          </button>
        )}
      </div>

      {/* Table */}
      <div className="bg-white rounded-2xl overflow-hidden" style={{ boxShadow: "0 2px 12px rgba(0,0,0,0.04)" }}>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr style={{ background: "#F8F8F8", borderBottom: "1px solid #E5E7EB" }}>
                {["Customer", "Contact", "Bookings", "Total Saved", "Status", "Joined", ""].map((h) => (
                  <th key={h} className="px-5 py-3 text-left text-[10px] font-bold text-[#9CA3AF] uppercase tracking-wider">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-50">
              {loading ? Array(5).fill(0).map((_, i) => (
                <tr key={i}>
                  {Array(7).fill(0).map((_, j) => (
                    <td key={j} className="px-5 py-4"><div className="h-4 bg-gray-100 rounded animate-pulse" /></td>
                  ))}
                </tr>
              )) : customers.map((c) => (
                <tr key={c.id} className="hover:bg-gray-50 transition-colors">
                  <td className="px-5 py-4">
                    <div className="flex items-center gap-3">
                      <div className="w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold text-white shrink-0"
                        style={{ background: "#1C2472" }}>
                        {c.fullName.split(" ").map((n) => n[0]).join("").slice(0, 2).toUpperCase()}
                      </div>
                      <p className="font-semibold text-[#111111] text-sm">{c.fullName}</p>
                    </div>
                  </td>
                  <td className="px-5 py-4">
                    <p className="text-[#111111] text-sm">{c.email}</p>
                    <p className="text-[#9CA3AF] text-xs">{c.phone}</p>
                  </td>
                  <td className="px-5 py-4 text-center">
                    <span className="font-semibold text-[#111111] text-sm">{c._count.bookings}</span>
                  </td>
                  <td className="px-5 py-4">
                    <span className="font-semibold text-[#111111] text-sm">{formatNaira(totalSaved(c))}</span>
                  </td>
                  <td className="px-5 py-4">
                    <div className="flex flex-col gap-1">
                      <span className={`text-[10px] font-bold px-2 py-0.5 rounded-full w-fit ${c.isVerified ? "bg-green-100 text-green-700" : "bg-amber-100 text-amber-700"}`}>
                        {c.isVerified ? "Verified" : "Unverified"}
                      </span>
                      {c.kycVerified && (
                        <span className="text-[10px] font-bold px-2 py-0.5 rounded-full bg-blue-100 text-blue-700 w-fit">KYC ✓</span>
                      )}
                    </div>
                  </td>
                  <td className="px-5 py-4">
                    <p className="text-[#9CA3AF] text-xs">{formatDate(c.createdAt)}</p>
                  </td>
                  <td className="px-5 py-4">
                    <Link href={`/admin/customers/${c.id}`}
                      className="text-xs font-semibold text-[#B8952A] hover:underline">
                      View →
                    </Link>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        {total > PAGE_SIZE && (
          <div className="flex items-center justify-between px-5 py-4 border-t border-gray-50">
            <p className="text-[#9CA3AF] text-xs">Showing {(page - 1) * PAGE_SIZE + 1}–{Math.min(page * PAGE_SIZE, total)} of {total}</p>
            <div className="flex gap-2">
              <button onClick={() => setPage((p) => Math.max(1, p - 1))} disabled={page === 1}
                className="px-3 py-1.5 rounded-lg text-xs font-semibold border border-gray-200 text-[#6B7280] disabled:opacity-40 hover:bg-gray-50">
                Prev
              </button>
              <button onClick={() => setPage((p) => p + 1)} disabled={page * PAGE_SIZE >= total}
                className="px-3 py-1.5 rounded-lg text-xs font-semibold border border-gray-200 text-[#6B7280] disabled:opacity-40 hover:bg-gray-50">
                Next
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
