"use client";

import { motion } from "framer-motion";
import {
  Users,
  FolderOpen,
  Cpu,
  Coins,
  LayoutGrid,
  ArrowUpRight,
  TrendingUp,
  ShieldAlert,
  CheckCircle2,
  Clock,
  XCircle,
  Loader2,
} from "lucide-react";
import Link from "next/link";
import { useAdminStats } from "@/hooks/use-api";

const stagger = {
  hidden: { opacity: 0 },
  show: { opacity: 1, transition: { staggerChildren: 0.07 } },
};
const fadeUp = {
  hidden: { opacity: 0, y: 14 },
  show: { opacity: 1, y: 0, transition: { duration: 0.45 } },
};

const navLinks = [
  { href: "/dashboard/admin/users", label: "Kullanıcılar", icon: Users, color: "violet" },
  { href: "/dashboard/admin/projects", label: "Projeler", icon: FolderOpen, color: "cyan" },
  { href: "/dashboard/admin/render-jobs", label: "Render İşler", icon: Cpu, color: "emerald" },
  { href: "/dashboard/admin/plans", label: "Planlar", icon: LayoutGrid, color: "amber" },
];

function colorClass(color: string, type: "bg" | "text" | "icon") {
  const map: Record<string, Record<string, string>> = {
    violet: { bg: "from-neutral-500/12 to-neutral-600/5", text: "text-neutral-400", icon: "bg-neutral-500/12" },
    cyan: { bg: "from-neutral-500/12 to-neutral-600/5", text: "text-neutral-400", icon: "bg-neutral-500/12" },
    emerald: { bg: "from-neutral-500/12 to-neutral-600/5", text: "text-neutral-400", icon: "bg-neutral-500/12" },
    amber: { bg: "from-neutral-500/12 to-neutral-600/5", text: "text-neutral-400", icon: "bg-neutral-500/12" },
    rose: { bg: "from-neutral-500/12 to-neutral-600/5", text: "text-neutral-400", icon: "bg-neutral-500/12" },
  };
  return map[color]?.[type] ?? "";
}

export default function AdminPage() {
  const { data: statsData, isLoading } = useAdminStats();
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const stats = (statsData as any)?.data ?? statsData;

  const projectsByStatus = stats?.projects?.byStatus ?? {};
  const renderByStatus = stats?.renderJobs?.byStatus ?? {};

  const statCards = [
    {
      label: "Toplam Kullanıcı",
      value: stats?.users?.total ?? "—",
      sub: `${stats?.users?.active ?? 0} aktif`,
      icon: Users,
      color: "violet",
    },
    {
      label: "Toplam Proje",
      value: stats?.projects?.total ?? "—",
      sub: `${projectsByStatus["COMPLETED"] ?? 0} tamamlandı`,
      icon: FolderOpen,
      color: "cyan",
    },
    {
      label: "Aktif Render",
      value: (renderByStatus["QUEUED"] ?? 0) + (renderByStatus["PROCESSING"] ?? 0),
      sub: `${renderByStatus["COMPLETED"] ?? 0} tamamlandı`,
      icon: Cpu,
      color: "emerald",
    },
    {
      label: "Kredi Verildi",
      value: stats?.credits?.totalGranted ?? "—",
      sub: `${stats?.credits?.totalUsed ?? 0} kullanıldı`,
      icon: Coins,
      color: "amber",
    },
    {
      label: "Başarısız Job",
      value: renderByStatus["FAILED"] ?? 0,
      sub: "Müdahale gerekiyor",
      icon: ShieldAlert,
      color: "rose",
    },
    {
      label: "Şablon Sayısı",
      value: stats?.templates?.total ?? "—",
      sub: "Yayında",
      icon: LayoutGrid,
      color: "violet",
    },
  ];

  return (
    <motion.div variants={stagger} initial="hidden" animate="show" className="space-y-6 max-w-7xl mx-auto">
      {/* Başlık */}
      <motion.div variants={fadeUp} className="flex items-center justify-between">
        <div>
          <h1 className="font-[family-name:var(--font-display)] text-2xl md:text-3xl font-bold tracking-tight">
            Admin Paneli
          </h1>
          <p className="text-sm text-[var(--color-text-muted)] mt-1">
            Sistem genelinde yönetim ve izleme
          </p>
        </div>
        <span className="bg-[var(--color-bg-inverted)] text-[var(--color-text-inverted)] rounded-md text-xs px-3 py-1 font-medium">Süper Yönetici</span>
      </motion.div>

      {/* İstatistik Kartları */}
      <motion.div variants={fadeUp} className="grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-3">
        {isLoading ? (
          <div className="col-span-6 flex justify-center py-12">
            <Loader2 size={28} className="animate-spin text-neutral-400" />
          </div>
        ) : (
          statCards.map((card) => {
            const Icon = card.icon;
            return (
              <div
                key={card.label}
                className={`card-surface p-4 bg-gradient-to-br ${colorClass(card.color, "bg")}`}
              >
                <div className="flex items-center justify-between mb-3">
                  <div className={`w-8 h-8 rounded-xl ${colorClass(card.color, "icon")} flex items-center justify-center`}>
                    <Icon size={16} className={colorClass(card.color, "text")} />
                  </div>
                  <ArrowUpRight size={12} className="text-[var(--color-text-ghost)]" />
                </div>
                <div className="font-[family-name:var(--font-display)] text-2xl font-bold">
                  {String(card.value)}
                </div>
                <div className="flex flex-col mt-1 gap-0.5">
                  <span className="text-[10px] text-[var(--color-text-muted)]">{card.label}</span>
                  <span className="text-[9px] text-[var(--color-text-ghost)]">{card.sub}</span>
                </div>
              </div>
            );
          })
        )}
      </motion.div>

      {/* Hızlı Yönetim Linkleri */}
      <motion.div variants={fadeUp} className="grid grid-cols-2 lg:grid-cols-4 gap-3">
        {navLinks.map((link) => {
          const Icon = link.icon;
          return (
            <Link
              key={link.href}
              href={link.href}
              className="group card-surface p-5 flex items-center gap-4 hover:border-neutral-500/30 transition-colors"
            >
              <div className={`w-11 h-11 rounded-xl bg-[var(--color-bg-inverted)] flex items-center justify-center shadow-lg`}>
                <Icon size={20} className="text-[var(--color-text-inverted)]" />
              </div>
              <div>
                <h3 className="text-sm font-semibold">{link.label}</h3>
                <p className="text-xs text-[var(--color-text-muted)] mt-0.5">Yönet →</p>
              </div>
            </Link>
          );
        })}
      </motion.div>

      {/* Proje Durum Özeti */}
      {!isLoading && stats && (
        <motion.div variants={fadeUp} className="grid grid-cols-1 lg:grid-cols-2 gap-4">
          <div className="card-surface p-5">
            <h2 className="text-sm font-semibold mb-4 flex items-center gap-2">
              <TrendingUp size={14} className="text-neutral-400" /> Proje Durumları
            </h2>
            <div className="space-y-2">
              {Object.entries(projectsByStatus as Record<string, number>).map(([status, count]) => (
                <div key={status} className="flex items-center justify-between text-sm">
                  <span className="text-[var(--color-text-muted)] capitalize">{status.replace("_", " ")}</span>
                  <span className="font-semibold">{count}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="card-surface p-5">
            <h2 className="text-sm font-semibold mb-4 flex items-center gap-2">
              <Cpu size={14} className="text-neutral-400" /> Render Job Durumları
            </h2>
            <div className="space-y-2">
              {[
                { key: "QUEUED", icon: Clock, color: "text-neutral-400", label: "Beklemede" },
                { key: "PROCESSING", icon: Loader2, color: "text-neutral-400", label: "İşleniyor" },
                { key: "COMPLETED", icon: CheckCircle2, color: "text-neutral-400", label: "Tamamlandı" },
                { key: "FAILED", icon: XCircle, color: "text-neutral-400", label: "Başarısız" },
              ].map(({ key, icon: Icon, color, label }) => (
                <div key={key} className="flex items-center justify-between text-sm">
                  <span className={`flex items-center gap-2 ${color}`}>
                    <Icon size={12} />
                    <span className="text-[var(--color-text-muted)]">{label}</span>
                  </span>
                  <span className="font-semibold">{renderByStatus[key] ?? 0}</span>
                </div>
              ))}
            </div>
          </div>
        </motion.div>
      )}

      {/* Son Kayıt Kullanıcılar */}
      {!isLoading && stats?.recentUsers?.length > 0 && (
        <motion.div variants={fadeUp} className="card-surface p-5">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-sm font-semibold flex items-center gap-2">
              <Users size={14} className="text-neutral-400" /> Son Kayıt Kullanıcılar
            </h2>
            <Link href="/dashboard/admin/users" className="text-xs text-neutral-400 hover:underline">
              Tümünü Gör
            </Link>
          </div>
          <div className="space-y-2">
            {/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
            {stats.recentUsers.map((user: any) => (
              <div key={user.id} className="flex items-center justify-between py-2 border-b border-[var(--color-border-faint)] last:border-0">
                <div>
                  <p className="text-sm font-medium">
                    {user.firstName || user.lastName ? `${user.firstName ?? ""} ${user.lastName ?? ""}`.trim() : user.email}
                  </p>
                  <p className="text-xs text-[var(--color-text-muted)]">{user.email}</p>
                </div>
                <div className="flex items-center gap-2">
                  <span className={`text-xs px-2 py-0.5 rounded-full border ${user.isActive ? "bg-neutral-500/10 text-neutral-300 border-neutral-500/20" : "bg-[var(--color-bg-surface)] text-[var(--color-text-ghost)] border-[var(--color-border-faint)]"}`}>
                    {user.isActive ? "Aktif" : "Pasif"}
                  </span>
                  <span className="text-xs text-[var(--color-text-ghost)]">
                    {new Date(user.createdAt).toLocaleDateString("tr")}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </motion.div>
      )}
    </motion.div>
  );
}
