"use client";

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

interface DashboardStats {
  totalCustomers: number;
  totalBookings: number;
  totalRevenue: number;
  pendingTransactions: number;
  recentTransactions: Array<{
    id: string;
    amount: number;
    status: string;
    createdAt: string;
    booking: { user: { fullName: string; email: string }; package: { name: string } };
  }>;
  packageStats: Array<{ name: string; slotsBooked: number; slotsAvailable: number }>;
}

function StatCard({ label, value, icon, color }: { label: string; value: string | number; icon: string; color: string }) {
  return (
    <div className="bg-white rounded-2xl p-5" style={{ boxShadow: "0 2px 12px rgba(0,0,0,0.04)" }}>
      <div className="flex items-center justify-between mb-3">
        <p className="text-[#6B7280] text-xs font-semibold uppercase tracking-wider">{label}</p>
        <div className="w-9 h-9 rounded-xl flex items-center justify-center text-base" style={{ background: `${color}15` }}>
          {icon}
        </div>
      </div>
      <p className="text-[#111111] font-black text-2xl" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>{value}</p>
    </div>
  );
}

export default function AdminDashboardPage() {
  const router = useRouter();
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [unauthorized, setUnauthorized] = useState(false);

  useEffect(() => {
    apiFetch<DashboardStats>("/admin/dashboard")
      .then(setStats)
      .catch((err) => {
        if (err?.status === 401 || err?.status === 403) setUnauthorized(true);
      })
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    if (unauthorized) router.replace("/admin/login");
  }, [unauthorized, router]);

  if (loading) {
    return (
      <div className="p-6 space-y-4">
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          {[1, 2, 3, 4].map((i) => <div key={i} className="h-28 bg-white rounded-2xl animate-pulse" />)}
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 max-w-7xl">
      <div className="mb-6">
        <h1 className="text-[#111111] font-black text-2xl" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
          Dashboard
        </h1>
        <p className="text-[#6B7280] text-sm mt-0.5">
          {new Date().toLocaleDateString("en-NG", { weekday: "long", day: "numeric", month: "long", year: "numeric" })}
        </p>
      </div>

      {/* Stats grid */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <StatCard label="Total Customers" value={stats?.totalCustomers ?? 0} icon="👥" color="#1C2472" />
        <StatCard label="Active Bookings" value={stats?.totalBookings ?? 0} icon="📦" color="#B8952A" />
        <StatCard label="Total Revenue" value={formatNaira(stats?.totalRevenue ?? 0)} icon="💰" color="#22C55E" />
        <StatCard label="Pending Payments" value={stats?.pendingTransactions ?? 0} icon="⏳" color="#F59E0B" />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
        {/* Recent transactions */}
        <div className="lg:col-span-2 bg-white rounded-2xl p-5" style={{ boxShadow: "0 2px 12px rgba(0,0,0,0.04)" }}>
          <div className="flex items-center justify-between mb-4">
            <h2 className="font-bold text-[#111111]" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>Recent Transactions</h2>
            <Link href="/admin/transactions" className="text-xs font-semibold text-[#B8952A]">View all</Link>
          </div>
          <div className="space-y-3">
            {(stats?.recentTransactions ?? []).length === 0 ? (
              <p className="text-[#6B7280] text-sm text-center py-8">No transactions yet</p>
            ) : (stats?.recentTransactions ?? []).map((tx) => {
              const isSuccess = tx.status === "SUCCESS";
              const borderColor = isSuccess ? "#B8952A" : tx.status === "FAILED" ? "#EF4444" : "#F59E0B";
              return (
                <div key={tx.id} className="flex items-center justify-between p-3 rounded-xl"
                  style={{ background: "#F8F8F8", borderLeft: `3px solid ${borderColor}` }}>
                  <div className="min-w-0">
                    <p className="font-semibold text-[#111111] text-sm truncate">{tx.booking?.user?.fullName}</p>
                    <p className="text-[#6B7280] text-xs truncate">{tx.booking?.package?.name}</p>
                    <p className="text-[#9CA3AF] text-[10px]">{formatDate(tx.createdAt)}</p>
                  </div>
                  <div className="text-right shrink-0 ml-3">
                    <p className="font-bold text-[#111111] text-sm">{formatNaira(tx.amount)}</p>
                    <span className="text-[10px] font-bold px-2 py-0.5 rounded-full"
                      style={{ background: `${borderColor}15`, color: borderColor }}>
                      {tx.status}
                    </span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Package capacity */}
        <div className="bg-white rounded-2xl p-5" style={{ boxShadow: "0 2px 12px rgba(0,0,0,0.04)" }}>
          <div className="flex items-center justify-between mb-4">
            <h2 className="font-bold text-[#111111]" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>Package Capacity</h2>
            <Link href="/admin/packages" className="text-xs font-semibold text-[#B8952A]">Manage</Link>
          </div>
          <div className="space-y-4">
            {(stats?.packageStats ?? []).length === 0 ? (
              <p className="text-[#6B7280] text-sm text-center py-8">No packages yet</p>
            ) : (stats?.packageStats ?? []).map((pkg, i) => {
              const total = pkg.slotsBooked + pkg.slotsAvailable;
              const pct = total > 0 ? Math.round((pkg.slotsBooked / total) * 100) : 0;
              return (
                <div key={i}>
                  <div className="flex justify-between text-sm mb-1">
                    <p className="font-semibold text-[#111111] truncate">{pkg.name}</p>
                    <span className="text-[#B8952A] font-bold shrink-0 ml-2">{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>
                  <p className="text-[#9CA3AF] text-xs mt-0.5">{pkg.slotsBooked}/{total} slots</p>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}
