/**
 * app/dashboard/page.tsx
 * Main dashboard page — stats overview, quick links.
 * Institutional black & white professional theme.
 */

"use client";

import { useState, useEffect } from "react";

import { useAuth } from "@/hooks/useAuth";
import { StatsCard } from "@/components/dashboard/StatsCard";
import AssociateRegistrationForm from "@/components/auth/AssociateRegistrationForm";
import { 
  Users, TrendingUp, ShoppingBag, Percent, ArrowRight, 
  Copy, ShieldCheck, User as UserIcon, Wallet, Building2, Network
} from "lucide-react";
import toast from "react-hot-toast";
import Link from "next/link";

export default function DashboardPage() {
  const { user } = useAuth();
  const [totalSales, setTotalSales] = useState<number | null>(null);
  const [totalTeamSize, setTotalTeamSize] = useState<number | null>(null);

  useEffect(() => {
    fetch("/api/users/my-sales")
      .then((r) => r.json())
      .then((d) => {
        if (d.success) setTotalSales(d.data.totalSales);
      })
      .catch(() => {});

    fetch("/api/users/my-team-size")
      .then((r) => r.json())
      .then((d) => {
        if (d.success) setTotalTeamSize(d.data.totalTeamSize);
      })
      .catch(() => {});
  }, []);

  if (!user) return null;

  const copyReferralCode = () => {
    navigator.clipboard.writeText(user.referralCode);
    toast.success("Referral code copied!");
  };

  return (
    <div className="space-y-10 md:space-y-12">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-6">
        <div className="flex-1">
          <div className="flex items-center gap-3 mb-2">
            <p className="text-[10px] font-black text-slate-400 uppercase tracking-[0.3em]">
              Overview
            </p>
            {user.role === "admin" && (
              <Link
                href="/admin"
                className="flex items-center gap-2 px-3 py-1 rounded-full bg-indigo-600/10 text-indigo-600 text-[9px] font-black uppercase tracking-widest border border-indigo-600/20 hover:bg-indigo-600 hover:text-white transition-all shadow-sm active:scale-95"
              >
                <ShieldCheck className="h-3 w-3" />
                Switch to Admin
              </Link>
            )}
            <Link
              href="/profile"
              className="flex items-center gap-2 px-3 py-1 rounded-full bg-slate-100 text-slate-500 text-[9px] font-black uppercase tracking-widest border border-slate-200 hover:bg-slate-200 hover:text-slate-900 transition-all shadow-sm active:scale-95"
            >
              <UserIcon className="h-3 w-3" />
              Manage Profile
            </Link>
          </div>
          <h1 className="text-3xl md:text-5xl font-jakarta font-black text-black tracking-tighter leading-none">
            Welcome back, <br />
            {user.name.split(" ")[0]}.
          </h1>
        </div>

        {/* Referral code widget */}
        <div className="flex items-center gap-4 rounded-[1.5rem] bg-white border border-slate-100 shadow-xl shadow-black/[0.02] px-6 py-4">
          <div className="flex-1">
            <p className="text-[9px] text-slate-300 uppercase tracking-[0.2em] font-black mb-1">
              Access Token
            </p>
            <p className="text-sm font-black text-black tracking-widest font-jakarta uppercase">
              {user.referralCode}
            </p>
          </div>
          <button
            id="copy-referral-btn"
            onClick={copyReferralCode}
            className="p-3.5 rounded-2xl bg-black hover:bg-slate-800 text-white transition-all active:scale-95 shadow-lg shadow-black/20"
            aria-label="Copy referral code"
          >
            <Copy className="h-4 w-4" />
          </button>
        </div>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-2 lg:grid-cols-5 gap-4 md:gap-6">
        <StatsCard
          title="LIQUID BALANCE"
          value={`₹${user.wallet.toLocaleString("en-IN")}`}
          icon={Wallet}
          variant="dark"
        />
        <StatsCard
          title="GROSS EARNINGS"
          value={`₹${user.totalEarnings.toLocaleString("en-IN")}`}
          icon={TrendingUp}
        />
        <StatsCard
          title="TOTAL SALES"
          value={
            totalSales !== null ? `₹${totalSales.toLocaleString("en-IN")}` : "—"
          }
          icon={ShoppingBag}
        />
        <StatsCard
          title="DIRECT TEAM"
          value={user.downline?.length ?? 0}
          icon={Users}
        />
        <StatsCard
          title="TOTAL TEAM"
          value={totalTeamSize !== null ? totalTeamSize : "—"}
          icon={Network}
        />
      </div>

      {/* Quick Action & Info */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2 grid grid-cols-1 md:grid-cols-2 gap-6">
          <div className="rounded-[2.5rem] bg-slate-900 p-8 group hover:-translate-y-1 transition-all duration-300 shadow-2xl shadow-indigo-500/10">
            <div className="flex flex-col h-full justify-between">
              <div className="h-12 w-12 rounded-2xl bg-white/10 flex items-center justify-center mb-10">
                <Building2 className="h-6 w-6 text-white" />
              </div>
              <div>
                <h3 className="text-xl font-jakarta font-black text-white mb-2 uppercase tracking-tight">
                  Property Asset
                </h3>
                <p className="text-sm text-slate-400 mb-6 font-medium leading-relaxed">
                  Submit high-yield real estate listings to the team
                  inventory.
                </p>
                <Link
                  href="/properties"
                  className="inline-flex items-center gap-3 text-[10px] font-black uppercase tracking-widest text-white hover:opacity-70 transition-all"
                >
                  GO TO INVENTORY <ArrowRight className="h-3 w-3" />
                </Link>
              </div>
            </div>
          </div>

          <div className="rounded-[2.5rem] bg-white border border-slate-100 p-8 group hover:-translate-y-1 transition-all duration-300 shadow-xl shadow-black/[0.02]">
            <div className="flex flex-col h-full justify-between">
              <div className="h-12 w-12 rounded-2xl bg-slate-50 flex items-center justify-center mb-10 border border-slate-100">
                <Users className="h-6 w-6 text-black" />
              </div>
              <div>
                <h3 className="text-xl font-jakarta font-black text-black mb-2 uppercase tracking-tight">
                  Team Expansion
                </h3>
                <p className="text-sm text-slate-500 mb-6 font-medium leading-relaxed text-balance">
                  Scale your revenue by onboarding professional agents.
                </p>
                <Link
                  href="/network"
                  className="inline-flex items-center gap-3 text-[10px] font-black uppercase tracking-widest text-black hover:opacity-50 transition-all"
                >
                  MANAGE TEAM <ArrowRight className="h-3 w-3" />
                </Link>
              </div>
            </div>
          </div>
        </div>

        {/* Security / Info */}
        <div className="rounded-[2.5rem] border-2 border-slate-50 p-8 flex flex-col justify-between bg-slate-50/50">
          <div className="space-y-6">
            <div className="flex items-center gap-3">
              <ShieldCheck className="h-5 w-5 text-black" />
              <span className="text-[10px] font-black tracking-widest uppercase text-black">
                Security Protocol
              </span>
            </div>
            <p className="text-xs text-slate-500 leading-relaxed font-medium">
              Your account is protected by enterprise-grade encryption. Every
              transaction is logged and verified by the central administrator.
            </p>
          </div>
          <div className="pt-8 border-t border-slate-100">
            <p className="text-[9px] font-black text-slate-300 uppercase tracking-widest">
              Server Status
            </p>
            <div className="flex items-center gap-2 mt-2">
              <span className="h-1.5 w-1.5 rounded-full bg-emerald-500 animate-pulse" />
              <span className="text-[10px] font-bold text-black">
                Operational
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* Registration section */}
      <div className="grid grid-cols-1 xl:grid-cols-[1.1fr_0.9fr] gap-6">
        <div className="rounded-[2.5rem] border border-slate-200 bg-white p-8 shadow-xl shadow-slate-200/60">
          <div className="mb-6">
            <p className="text-[10px] font-black text-slate-400 uppercase tracking-[0.3em] mb-2">
              Associate Onboarding
            </p>
            <h3 className="text-2xl font-jakarta font-black text-black uppercase tracking-tight">
              Add a new associate in minutes.
            </h3>
            <p className="mt-3 text-sm text-slate-500 leading-relaxed">
              Create a new agent account directly from your dashboard and place them under your team.
            </p>
          </div>
          <div className="space-y-4">
            {[
              "Quick setup with email and password",
              "Optional referral code for sponsor placement",
              "Instant access to the same dashboard experience",
            ].map((item) => (
              <div key={item} className="flex items-center gap-3 rounded-2xl bg-slate-50 px-4 py-3">
                <div className="h-2.5 w-2.5 rounded-full bg-indigo-600" />
                <span className="text-sm text-slate-600">{item}</span>
              </div>
            ))}
          </div>
        </div>
        <AssociateRegistrationForm />
      </div>

      {/* Commission Structure Preview */}
      <div className="rounded-[3rem] bg-white border border-slate-100 shadow-xl shadow-black/[0.02] p-10">
        <div className="flex items-center justify-between mb-10">
          <div>
            <p className="text-[10px] font-black text-slate-400 uppercase tracking-[0.3em] mb-2">
              Revenue Model
            </p>
            <h3 className="text-2xl font-jakarta font-black text-black uppercase tracking-tight">
              Commission Split.
            </h3>
          </div>
          <span className="text-[10px] text-black bg-slate-50 border border-slate-100 px-4 py-2 rounded-full uppercase tracking-widest font-black">
            20-Level Network
          </span>
        </div>

        <div className="grid md:grid-cols-2 gap-6">
          <div className="p-8 rounded-[2rem] bg-slate-900 group overflow-hidden relative">
            <div className="relative z-10">
              <p className="text-[10px] font-black text-indigo-400 uppercase tracking-widest mb-4">
                Direct Earnings
              </p>
              <div className="flex items-end gap-2 mb-2">
                <span className="text-5xl font-jakarta font-black text-white leading-none">
                  15
                </span>
                <span className="text-xl font-black text-slate-600 mb-1">
                  %
                </span>
              </div>
              <p className="text-xs text-slate-400 font-medium">
                Base commission on all personal acquisitions.
              </p>
            </div>
            <div className="absolute top-0 right-0 p-6 opacity-10">
              <TrendingUp className="h-12 w-12 text-white" />
            </div>
          </div>

          <div className="p-8 rounded-[2rem] bg-slate-50 border border-slate-100 group overflow-hidden relative">
            <div className="relative z-10">
              <p className="text-[10px] font-black text-slate-300 uppercase tracking-widest mb-4">
                Network Revenue
              </p>
              <div className="flex items-end gap-2 mb-2">
                <span className="text-5xl font-jakarta font-black text-black leading-none">
                  20
                </span>
                <span className="text-xl font-black text-slate-200 mb-1">
                  %
                </span>
              </div>
              <p className="text-xs text-slate-500 font-medium">
                Override calculated from direct downline volume.
              </p>
            </div>
            <div className="absolute top-0 right-0 p-6 opacity-10">
              <Network className="h-12 w-12 text-black" />
            </div>
          </div>
        </div>

        <div className="mt-10 p-6 rounded-2xl border border-dashed border-slate-200 bg-slate-50/50">
          <p className="text-[10px] text-slate-400 leading-relaxed font-medium uppercase tracking-tight">
            * Important: All settlements are processed in real-time. Contact the
            treasury for large volume withdrawls.
          </p>
        </div>
      </div>
    </div>
  );
}
