"use client";

import { useState, useEffect } from "react";
import { useAuth } from "@/lib/auth";
import {
  ShoppingCart, Users, Package, DollarSign, TrendingUp,
  Clock, CheckCircle2, XCircle, Loader2, RefreshCw, AlertTriangle,
  Percent, Ticket, ArrowUpRight, BarChart3
} from "lucide-react";

const API = process.env.NEXT_PUBLIC_API_URL ;

interface DashData {
  totalOrders: number; todayOrders: number; monthOrders: number; totalPaid: number;
  totalUsers: number; totalProducts: number; activeVouchers: number;
  grossRevenue: number; monthRevenue: number; totalDiscount: number;
  pendingOrders: number; processingOrders: number; failedOrders: number; successOrders: number;
  unpaidOrders: number; paidRatio: number;
  revenueChart: { date: string; revenue: number; orders: number; paid: number }[];
  bestSellers: { game_name: string; product_name: string; icon_url: string; total_orders: number; paid_orders: number; net_revenue: number }[];
}

function fmt(n: number) { return `Rp${n.toLocaleString("id-ID")},-`; }

export default function AdminDashboard() {
  const { token } = useAuth();
  const [d, setD] = useState<DashData | null>(null);
  const [loading, setLoading] = useState(true);
  const [syncing, setSyncing] = useState(false);

  const fetch_ = async () => {
    if (!token) return;
    try {
      const res = await fetch(`${API}/api/admin/dashboard`, { headers: { Authorization: `Bearer ${token}` } });
      const json = await res.json();
      if (json.success) setD(json.data);
    } catch (e) { console.error(e); } finally { setLoading(false); }
  };

  const sync = async () => {
    setSyncing(true);
    try {
      const res = await fetch(`${API}/api/admin/sync-products`, { method: "POST", headers: { Authorization: `Bearer ${token}` } });
      const json = await res.json();
      alert(json.message); fetch_();
    } catch { alert("Gagal sync"); } finally { setSyncing(false); }
  };

  useEffect(() => { fetch_(); }, [token]);

  if (loading) return <div className="flex items-center justify-center py-32"><Loader2 className="animate-spin text-muted" size={32} /></div>;
  if (!d) return <p className="text-muted text-center py-20">Gagal memuat data</p>;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <h1 className="text-lg sm:text-xl font-bold text-white">Overview</h1>
          <p className="text-[10px] sm:text-xs text-muted mt-0.5">Statistik toko {process.env.NEXT_PUBLIC_APP_NAME}</p>
        </div>
        <button onClick={sync} disabled={syncing} className="flex items-center gap-2 px-3 py-1.5 sm:px-4 sm:py-2 rounded-lg bg-red-500/10 border border-red-500/20 text-red-400 text-[10px] sm:text-xs font-bold hover:bg-red-500/20 transition-all">
          <RefreshCw size={12} className={syncing ? "animate-spin" : ""} />
          {syncing ? "Syncing..." : "Sync Produk"}
        </button>
      </div>

      <div className="grid grid-cols-2 gap-3 sm:gap-4">
        {[
          { label: "Total Orders", val: d.totalOrders.toLocaleString(), icon: ShoppingCart, color: "text-blue-400", bg: "bg-blue-500/10", sub: `Hari ini: ${d.todayOrders}` },
          { label: "Total Paid", val: d.totalPaid.toLocaleString(), icon: CheckCircle2, color: "text-green-400", bg: "bg-green-500/10", sub: `Bulan ini: ${d.monthOrders}` },
          { label: "Paid Ratio", val: `${d.paidRatio}%`, icon: Percent, color: "text-purple-400", bg: "bg-purple-500/10", sub: `% Paid Ratio` },
          { label: "Unpaid", val: d.unpaidOrders.toLocaleString(), icon: Clock, color: "text-yellow-400", bg: "bg-yellow-500/10", sub: "Menunggu bayar" },
        ].map((c) => {
          const I = c.icon;
          return (
            <div key={c.label} className="bg-dark-surface rounded-xl p-3 sm:p-5 border border-dark-border relative overflow-hidden group hover:border-white/10 transition-all">
              <p className={`text-xl sm:text-3xl font-bold ${c.color} mb-0.5`}>{c.val}</p>
              <p className="text-[10px] sm:text-xs text-muted font-medium">{c.label}</p>
              <p className="text-[9px] text-muted/60 mt-1 flex items-center gap-1"><I size={9} />{c.sub}</p>
            </div>
          );
        })}
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
        <div className="bg-dark-surface rounded-xl p-4 border border-dark-border">
          <div className="flex items-center gap-2 mb-1.5 text-muted text-[10px] sm:text-xs"><DollarSign size={12} />Gross Revenue</div>
          <p className="text-base sm:text-xl font-bold text-white truncate">{fmt(d.grossRevenue)}</p>
        </div>
        <div className="bg-dark-surface rounded-xl p-4 border border-dark-border">
          <div className="flex items-center gap-2 mb-1.5 text-muted text-[10px] sm:text-xs"><TrendingUp size={12} />Revenue Bulan Ini</div>
          <p className="text-base sm:text-xl font-bold text-green-400 truncate">{fmt(d.monthRevenue)}</p>
        </div>
        <div className="bg-dark-surface rounded-xl p-4 border border-dark-border">
          <div className="flex items-center gap-2 mb-1.5 text-muted text-[10px] sm:text-xs"><Ticket size={12} />Total Diskon</div>
          <p className="text-base sm:text-xl font-bold text-red-400 truncate">-{fmt(d.totalDiscount)}</p>
        </div>
      </div>

      <div className="grid grid-cols-3 sm:grid-cols-5 gap-2 sm:gap-3">
        {[
          { label: "Menunggu", val: d.pendingOrders, icon: Clock, c: "text-yellow-400 bg-yellow-500/10" },
          { label: "Diproses", val: d.processingOrders, icon: RefreshCw, c: "text-blue-400 bg-blue-500/10" },
          { label: "Sukses", val: d.successOrders, icon: CheckCircle2, c: "text-green-400 bg-green-500/10" },
          { label: "Gagal", val: d.failedOrders, icon: XCircle, c: "text-red-400 bg-red-500/10" },
          { label: "Voucher", val: d.activeVouchers, icon: Ticket, c: "text-purple-400 bg-purple-500/10" },
        ].map((s) => {
          const I = s.icon;
          return (
            <div key={s.label} className="bg-dark-surface rounded-xl p-3 border border-dark-border flex flex-col sm:flex-row items-center gap-1.5 sm:gap-3">
              <div className={`w-7 h-7 sm:w-9 sm:h-9 rounded-lg flex items-center justify-center shrink-0 ${s.c.split(" ")[1]}`}><I size={14} className={s.c.split(" ")[0]} /></div>
              <div className="text-center sm:text-left"><p className="text-sm sm:text-lg font-bold text-white">{s.val}</p><p className="text-[8px] sm:text-[10px] text-muted">{s.label}</p></div>
            </div>
          );
        })}
      </div>

      {/* Chart + Best Sellers */}
      <div className="grid grid-cols-1 lg:grid-cols-5 gap-6">
        {/* Revenue Chart */}
        <div className="lg:col-span-3 bg-dark-surface rounded-xl p-4 sm:p-6 border border-dark-border">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-xs sm:text-sm font-bold text-white flex items-center gap-2"><BarChart3 size={14} />Revenue 7 Hari</h3>
            <div className="flex items-center gap-3 text-[9px] text-muted">
              <span className="flex items-center gap-1"><span className="w-1.5 h-1.5 rounded-full bg-green-500/60" />Paid</span>
            </div>
          </div>
          {d.revenueChart.length > 0 ? (
            <div className="flex items-end gap-1.5 sm:gap-3 h-28 sm:h-44">
              {d.revenueChart.map((day) => {
                const maxR = Math.max(...d.revenueChart.map(x => x.revenue || 0), 1);
                const h = Math.max(((day.revenue || 0) / maxR) * 100, 4);
                return (
                  <div key={day.date} className="flex-1 flex flex-col items-center gap-1">
                    <p className="text-[7px] sm:text-[8px] text-muted font-medium hidden sm:block">{fmt(day.revenue || 0)}</p>
                    <div className="w-full relative">
                      <div className="w-full rounded-t-md bg-gradient-to-t from-green-600/30 to-green-500/60" style={{ height: `${h}%`, minHeight: 4 }} />
                    </div>
                    <div className="text-center">
                      <p className="text-[8px] sm:text-[9px] text-white font-bold">{day.paid || 0}</p>
                      <p className="text-[7px] sm:text-[8px] text-muted">{new Date(day.date).toLocaleDateString("id-ID", { day: "2-digit", month: "short" })}</p>
                    </div>
                  </div>
                );
              })}
            </div>
          ) : <p className="text-center text-muted text-xs py-10">Belum ada data</p>}
        </div>

        {/* Best Sellers */}
        <div className="lg:col-span-2 bg-dark-surface rounded-xl p-4 sm:p-6 border border-dark-border">
          <h3 className="text-sm font-bold text-white mb-4">Best Selling</h3>
          <div className="space-y-3">
            {d.bestSellers.length > 0 ? d.bestSellers.map((p, i) => {
              const paidRatio = p.total_orders > 0 ? Math.round((p.paid_orders / p.total_orders) * 100) : 0;
              return (
                <div key={i} className="flex items-center gap-3 p-2 rounded-lg hover:bg-white/[0.02] transition-colors">
                  <div className="w-8 h-8 rounded-lg bg-white/5 flex items-center justify-center text-[10px] font-bold text-muted shrink-0">
                    {p.icon_url ? (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img src={p.icon_url} alt="" className="w-full h-full rounded-lg object-cover" />
                    ) : (
                      <span>{i + 1}</span>
                    )}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-xs font-bold text-white truncate">{p.game_name}</p>
                    <div className="flex items-center gap-3 text-[10px] text-muted mt-0.5">
                      <span>{p.total_orders} orders</span>
                      <span>{p.paid_orders} paid</span>
                      <span className="text-green-400">{paidRatio}%</span>
                    </div>
                  </div>
                  <p className="text-xs font-bold text-green-400 shrink-0">{fmt(p.net_revenue || 0)}</p>
                </div>
              );
            }) : <p className="text-xs text-muted text-center py-6">Belum ada data</p>}
          </div>
        </div>
      </div>

      <div className="grid grid-cols-4 gap-2 sm:gap-4">
        {[
          { icon: Users, val: d.totalUsers, label: "Users", color: "text-purple-400" },
          { icon: Package, val: d.totalProducts, label: "Produk", color: "text-yellow-400" },
          { icon: Ticket, val: d.activeVouchers, label: "Voucher", color: "text-blue-400" },
          { icon: ShoppingCart, val: d.todayOrders, label: "Hari Ini", color: "text-green-400" },
        ].map((c) => {
          const I = c.icon;
          return (
            <div key={c.label} className="bg-dark-surface rounded-xl p-3 sm:p-4 border border-dark-border text-center">
              <I size={16} className={`mx-auto ${c.color} mb-1.5`} />
              <p className="text-base sm:text-xl font-bold text-white">{c.val}</p>
              <p className="text-[8px] sm:text-[10px] text-muted">{c.label}</p>
            </div>
          );
        })}
      </div>

      {/* Failed Alert */}
      {d.failedOrders > 0 && (
        <div className="bg-red-500/5 border border-red-500/20 rounded-xl p-4 flex items-center gap-4">
          <AlertTriangle size={20} className="text-red-500 shrink-0" />
          <div>
            <p className="text-sm font-bold text-red-400">{d.failedOrders} pesanan gagal</p>
            <p className="text-xs text-muted">Cek tab Pesanan untuk detail dan retry.</p>
          </div>
        </div>
      )}
    </div>
  );
}
