"use client";

import { useState, useEffect } from "react";
import { useAuth } from "@/lib/auth";
import { Shield, Settings, Clock, BarChart3, Loader2, ArrowRight } from "lucide-react";
import Link from "next/link";
import { format } from "date-fns";
import { id } from "date-fns/locale";

interface Order {
  id: number;
  invoice_no: string;
  invoice_id?: string;
  game_name: string;
  product?: { product_name: string };
  total_price?: number;
  price?: number;
  fulfill_status: string;
  created_at: string;
}

interface Stats {
  total: number;
  todayCount: number;
  pending: number;
  processing: number;
  success: number;
  failed: number;
  xcredits: number;
}

export default function DashboardPage() {
  const { user, token } = useAuth();
  const [stats, setStats] = useState<Stats | null>(null);
  const [recentOrders, setRecentOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!token) return;
    const fetchDashboardData = async () => {
      try {
        const headers = { Authorization: `Bearer ${token}` };
        const [dashRes, trxRes] = await Promise.all([
          fetch(`${process.env.NEXT_PUBLIC_API_URL }/api/user/dashboard`, { headers }).then(r => r.json()),
          fetch(`${process.env.NEXT_PUBLIC_API_URL }/api/user/transactions?limit=5`, { headers }).then(r => r.json()),
        ]);
        
        if (dashRes.success) setStats(dashRes.data);
        if (trxRes.success) setRecentOrders(trxRes.data || []);
      } catch (err) {
        console.error("Failed to fetch dashboard data", err);
      } finally {
        setLoading(false);
      }
    };
    fetchDashboardData();
  }, [token]);

  const getStatusColor = (status: string) => {
    switch (status.toLowerCase()) {
      case "success": return "bg-green-500/10 text-green-400 border border-green-500/20";
      case "pending": return "bg-yellow-500/10 text-yellow-400 border border-yellow-500/20";
      case "processing": return "bg-blue-500/10 text-blue-400 border border-blue-500/20";
      case "failed": return "bg-red-500/10 text-red-400 border border-red-500/20";
      default: return "bg-white/5 text-white border border-white/10";
    }
  };

  const getStatusText = (status: string) => {
    switch (status.toLowerCase()) {
      case "success": return "Sukses";
      case "pending": return "Menunggu";
      case "processing": return "Proses";
      case "failed": return "Gagal";
      default: return status;
    }
  };

  if (!user) return null;

  return (
    <div className="space-y-5">
      
      {/* Top Banner */}
      {!user.two_factor_enabled && (
        <div className="bg-blue-500/10 border border-blue-500/20 rounded-xl p-4 flex items-start sm:items-center justify-between gap-3">
          <div className="min-w-0">
            <h3 className="text-blue-400 font-bold text-sm mb-1">Tingkatkan keamanan!</h3>
            <p className="text-white/80 text-[11px] leading-relaxed">Gunakan fitur 2FA agar akun kamu lebih aman. Klik <Link href="/dashboard/settings" className="underline font-medium text-white hover:text-blue-400">disini</Link> untuk pengaturan!</p>
          </div>
          <div className="w-8 h-8 rounded-full bg-blue-500/20 flex items-center justify-center shrink-0">
            <Shield className="text-blue-400" size={14} />
          </div>
        </div>
      )}

      {/* User & XCredits Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* Profile Card */}
        <div className="bg-dark-surface rounded-xl p-4 flex items-center justify-between border border-dark-border">
          <div className="flex items-center gap-3 min-w-0">
            <div className="w-12 h-12 rounded-full overflow-hidden bg-white/5 flex items-center justify-center text-lg font-bold text-white shrink-0 border border-dark-border">
              {user.avatar ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img src={user.avatar} alt={user.username} className="w-full h-full object-cover" referrerPolicy="no-referrer" />
              ) : (
                user.username.charAt(0).toUpperCase()
              )}
            </div>
            <div className="min-w-0">
              <h2 className="text-white font-bold text-base truncate">{user.username}</h2>
              <span className="inline-block mt-1 px-2.5 py-0.5 rounded-full bg-primary/10 text-primary text-[10px] font-bold border border-primary/20">
                Member
              </span>
            </div>
          </div>
          <Link href="/dashboard/settings" className="p-2.5 rounded-lg bg-white/5 text-muted hover:text-white hover:bg-white/10 transition-colors shrink-0">
            <Settings size={18} />
          </Link>
        </div>

        {/* XCredits Card */}
        <div className="bg-dark-surface rounded-xl p-4 border border-dark-border flex flex-col justify-center">
          <div className="flex items-center justify-between gap-3">
            <div className="min-w-0">
              <div className="flex items-center gap-1.5 mb-1.5">
                <div className="w-5 h-5 rounded-full bg-primary/20 flex items-center justify-center">
                  <span className="text-primary text-[10px] font-bold">X</span>
                </div>
                <span className="text-xs font-semibold text-muted">Saldo XCredits</span>
              </div>
              <div className="flex items-baseline gap-1">
                <span className="text-primary font-black text-2xl">{user.xcredits?.toLocaleString("id-ID") || "0"}</span>
                <span className="text-white font-bold text-sm">XC</span>
              </div>
            </div>
            <div className="flex flex-col gap-2 shrink-0">
              <button className="px-4 py-1.5 rounded-lg bg-primary hover:bg-primary-hover text-dark font-bold text-xs transition-colors text-center w-20">
                Top Up
              </button>
              <button className="px-4 py-1.5 rounded-lg bg-white/5 hover:bg-white/10 text-white font-bold text-xs transition-colors border border-dark-border text-center w-20">
                Redeem
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Transaksi Hari Ini Section */}
      <div>
        <h3 className="text-white font-semibold text-sm mb-3">Transaksi Hari Ini</h3>
        
        {/* Top Stats */}
        <div className="grid grid-cols-2 gap-3 mb-3">
          <div className="bg-dark-surface rounded-xl p-4 sm:p-5 text-center border border-dark-border">
            <p className="text-xl sm:text-3xl font-black text-white mb-1">{stats?.total || 0}</p>
            <p className="text-[10px] sm:text-xs text-muted font-medium">Total Transaksi</p>
          </div>
          <div className="bg-dark-surface rounded-xl p-4 sm:p-5 text-center border border-dark-border">
            <p className="text-xl sm:text-3xl font-black text-white mb-1">{stats?.todayCount || 0}</p>
            <p className="text-[10px] sm:text-xs text-muted font-medium">Total Penjualan</p>
          </div>
        </div>

        {/* 4 Status Cards */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
          {[
            { label: "Menunggu", val: stats?.pending || 0, color: "text-yellow-400", bg: "bg-yellow-500/5", border: "border-yellow-500/20" },
            { label: "Proses", val: stats?.processing || 0, color: "text-blue-400", bg: "bg-blue-500/5", border: "border-blue-500/20" },
            { label: "Sukses", val: stats?.success || 0, color: "text-green-400", bg: "bg-green-500/5", border: "border-green-500/20" },
            { label: "Gagal", val: stats?.failed || 0, color: "text-red-400", bg: "bg-red-500/5", border: "border-red-500/20" },
          ].map((s) => (
            <div key={s.label} className={`${s.bg} rounded-xl p-3 sm:p-4 text-center border ${s.border}`}>
              <p className={`text-lg sm:text-2xl font-black ${s.color} mb-0.5`}>{s.val}</p>
              <p className="text-[10px] sm:text-[11px] text-muted font-medium">{s.label}</p>
            </div>
          ))}
        </div>
      </div>

      {/* Riwayat Transaksi Terbaru — Mobile card view */}
      <div>
        <h3 className="text-white font-semibold text-sm mb-3">Riwayat Transaksi Terbaru</h3>
        
        <div className="bg-dark-surface rounded-xl border border-dark-border overflow-hidden">
          {/* Desktop Table */}
          <div className="hidden md:block overflow-x-auto">
            <table className="w-full text-left text-sm">
              <thead className="bg-white/[0.02] text-xs text-muted font-medium border-b border-dark-border">
                <tr>
                  <th className="px-4 py-3 font-medium">Invoice</th>
                  <th className="px-4 py-3 font-medium">Item</th>
                  <th className="px-4 py-3 font-medium">Harga</th>
                  <th className="px-4 py-3 font-medium">Tanggal</th>
                  <th className="px-4 py-3 font-medium text-center">Status</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-dark-border">
                {loading ? (
                  <tr>
                    <td colSpan={5} className="px-4 py-12 text-center text-muted">
                      <Loader2 size={24} className="mx-auto animate-spin mb-2 text-muted/50" />
                      <p className="text-xs">Memuat data...</p>
                    </td>
                  </tr>
                ) : recentOrders.length === 0 ? (
                  <tr>
                    <td colSpan={5} className="px-4 py-12 text-center">
                      <BarChart3 size={32} className="mx-auto mb-2 opacity-20 text-muted" />
                      <p className="text-xs font-medium text-white mb-0.5">Data tidak ditemukan!</p>
                      <p className="text-[10px] text-muted">Tidak ada aktifitas data.</p>
                    </td>
                  </tr>
                ) : (
                  recentOrders.map((order) => {
                    const d = new Date(order.created_at);
                    const dateStr = !isNaN(d.getTime()) ? format(d, "dd/MM/yyyy HH:mm", { locale: id }) : "-";
                    const invoice = order.invoice_no || order.invoice_id || "-";
                    const price = order.price || order.total_price || 0;
                    return (
                      <tr key={order.id} className="hover:bg-white/[0.02] transition-colors">
                        <td className="px-4 py-3 text-white text-xs font-medium">{invoice}</td>
                        <td className="px-4 py-3 text-white text-xs">{order.product?.product_name || order.game_name || "-"}</td>
                        <td className="px-4 py-3 text-white text-xs">Rp {price.toLocaleString("id-ID")}</td>
                        <td className="px-4 py-3 text-muted text-xs">{dateStr}</td>
                        <td className="px-4 py-3 text-center">
                          <span className={`inline-block px-2.5 py-0.5 rounded text-[10px] font-bold ${getStatusColor(order.fulfill_status)}`}>
                            {getStatusText(order.fulfill_status)}
                          </span>
                        </td>
                      </tr>
                    );
                  })
                )}
              </tbody>
            </table>
          </div>

          {/* Mobile Card View */}
          <div className="md:hidden divide-y divide-dark-border">
            {loading ? (
              <div className="px-4 py-12 text-center text-muted">
                <Loader2 size={24} className="mx-auto animate-spin mb-2 text-muted/50" />
                <p className="text-xs">Memuat data...</p>
              </div>
            ) : recentOrders.length === 0 ? (
              <div className="px-4 py-12 text-center">
                <BarChart3 size={32} className="mx-auto mb-2 opacity-20 text-muted" />
                <p className="text-xs font-medium text-white mb-0.5">Data tidak ditemukan!</p>
                <p className="text-[10px] text-muted">Tidak ada aktifitas data.</p>
              </div>
            ) : (
              recentOrders.map((order) => {
                const d = new Date(order.created_at);
                const dateStr = !isNaN(d.getTime()) ? format(d, "dd MMM yyyy, HH:mm", { locale: id }) : "-";
                const invoice = order.invoice_no || order.invoice_id || "-";
                const price = order.price || order.total_price || 0;
                return (
                  <div key={order.id} className="px-4 py-3 flex items-center justify-between gap-3">
                    <div className="min-w-0 flex-1">
                      <div className="flex items-center gap-2 mb-0.5">
                        <p className="text-xs font-bold text-white truncate">{invoice}</p>
                        <span className={`inline-block px-2 py-0.5 rounded text-[8px] font-bold shrink-0 ${getStatusColor(order.fulfill_status)}`}>
                          {getStatusText(order.fulfill_status)}
                        </span>
                      </div>
                      <p className="text-[10px] text-muted truncate">{order.product?.product_name || order.game_name || "-"}</p>
                      <p className="text-[10px] text-muted/60">{dateStr}</p>
                    </div>
                    <p className="text-xs font-bold text-white shrink-0">Rp{price.toLocaleString("id-ID")}</p>
                  </div>
                );
              })
            )}
          </div>
        </div>
      </div>

    </div>
  );
}
