"use client";

import { useState } from "react";
import { motion } from "framer-motion";
import {
  Users,
  Search,
  UserCheck,
  UserX,
  Coins,
  ChevronLeft,
  ChevronRight,
  Loader2,
  RefreshCw,
  Shield,
} from "lucide-react";
import {
  useAdminUsers,
  useToggleUserActive,
  useGrantCredits,
} from "@/hooks/use-api";

const fadeUp = {
  hidden: { opacity: 0, y: 14 },
  show: { opacity: 1, y: 0, transition: { duration: 0.4 } },
};

export default function AdminUsersPage() {
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState("");
  const [grantModal, setGrantModal] = useState<{ userId: string; email: string } | null>(null);
  const [creditAmount, setCreditAmount] = useState("10");
  const [creditDesc, setCreditDesc] = useState("Admin tarafından manuel yükleme");

  const { data, isLoading, refetch } = useAdminUsers({ page, limit: 20 });
  const toggleActive = useToggleUserActive();
  const grantCredits = useGrantCredits();

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const response = (data as any)?.data ?? data;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const users = (response?.data ?? []) as any[];
  const meta = response?.meta ?? {};

  const filtered = search
    ? users.filter(
        (u) =>
          u.email?.toLowerCase().includes(search.toLowerCase()) ||
          u.firstName?.toLowerCase().includes(search.toLowerCase()) ||
          u.lastName?.toLowerCase().includes(search.toLowerCase())
      )
    : users;

  return (
    <motion.div
      initial="hidden"
      animate="show"
      variants={{ show: { transition: { staggerChildren: 0.06 } } }}
      className="space-y-5 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 font-bold flex items-center gap-2">
            <Users size={22} className="text-neutral-400" /> Kullanıcı Yönetimi
          </h1>
          <p className="text-sm text-[var(--color-text-muted)] mt-1">
            Toplam {meta.total ?? "—"} kullanıcı
          </p>
        </div>
        <button
          onClick={() => refetch()}
          className="btn-ghost text-sm flex items-center gap-2"
        >
          <RefreshCw size={14} /> Yenile
        </button>
      </motion.div>

      {/* Arama */}
      <motion.div variants={fadeUp} className="relative">
        <Search size={15} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-[var(--color-text-ghost)]" />
        <input
          type="text"
          placeholder="Email, isim veya soyisim ara..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="input pl-10 w-full max-w-md"
        />
      </motion.div>

      {/* Tablo */}
      <motion.div variants={fadeUp} className="card-surface overflow-hidden">
        {isLoading ? (
          <div className="flex justify-center py-16">
            <Loader2 size={28} className="animate-spin text-neutral-400" />
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-[var(--color-border-faint)]">
                  <th className="text-left px-4 py-3 text-xs text-[var(--color-text-muted)] font-medium">Kullanıcı</th>
                  <th className="text-left px-4 py-3 text-xs text-[var(--color-text-muted)] font-medium">Roller</th>
                  <th className="text-left px-4 py-3 text-xs text-[var(--color-text-muted)] font-medium">Durum</th>
                  <th className="text-left px-4 py-3 text-xs text-[var(--color-text-muted)] font-medium">Kayıt</th>
                  <th className="text-right px-4 py-3 text-xs text-[var(--color-text-muted)] font-medium">İşlemler</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((user) => {
                  // eslint-disable-next-line @typescript-eslint/no-explicit-any
                  const roleNames: string[] = (user.roles ?? []).map((r: any) => r?.role?.name ?? r?.name ?? "");
                  return (
                    <tr
                      key={user.id}
                      className="border-b border-[var(--color-border-faint)] last:border-0 hover:bg-[var(--color-bg-elevated)] transition-colors"
                    >
                      <td className="px-4 py-3">
                        <div className="font-medium">
                          {user.firstName || user.lastName
                            ? `${user.firstName ?? ""} ${user.lastName ?? ""}`.trim()
                            : "—"}
                        </div>
                        <div className="text-xs text-[var(--color-text-muted)]">{user.email}</div>
                      </td>
                      <td className="px-4 py-3">
                        <div className="flex flex-wrap gap-1">
                          {roleNames.length > 0 ? (
                            roleNames.map((role) => (
                              <span key={role} className="text-[10px] px-2 py-0.5 rounded-full bg-neutral-500/10 text-neutral-400 border border-neutral-500/20 flex items-center gap-1">
                                <Shield size={8} /> {role}
                              </span>
                            ))
                          ) : (
                            <span className="text-xs text-[var(--color-text-ghost)]">—</span>
                          )}
                        </div>
                      </td>
                      <td className="px-4 py-3">
                        <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>
                      </td>
                      <td className="px-4 py-3 text-xs text-[var(--color-text-muted)]">
                        {new Date(user.createdAt).toLocaleDateString("tr")}
                      </td>
                      <td className="px-4 py-3">
                        <div className="flex items-center justify-end gap-2">
                          <button
                            onClick={() => setGrantModal({ userId: user.id, email: user.email })}
                            className="p-1.5 rounded-lg hover:bg-neutral-500/10 text-neutral-400 transition-colors"
                            title="Kredi Yükle"
                          >
                            <Coins size={14} />
                          </button>
                          <button
                            onClick={() => toggleActive.mutate(user.id)}
                            disabled={toggleActive.isPending}
                            className={`p-1.5 rounded-lg transition-colors hover:bg-neutral-500/10 text-neutral-400`}
                            title={user.isActive ? "Pasif Yap" : "Aktif Yap"}
                          >
                            {user.isActive ? <UserX size={14} /> : <UserCheck size={14} />}
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </motion.div>

      {/* Sayfalama */}
      {meta.totalPages > 1 && (
        <motion.div variants={fadeUp} className="flex items-center justify-center gap-3">
          <button
            onClick={() => setPage((p) => Math.max(1, p - 1))}
            disabled={page === 1}
            className="btn-ghost text-sm flex items-center gap-1 disabled:opacity-40"
          >
            <ChevronLeft size={14} /> Önceki
          </button>
          <span className="text-sm text-[var(--color-text-muted)]">
            {page} / {meta.totalPages}
          </span>
          <button
            onClick={() => setPage((p) => Math.min(meta.totalPages, p + 1))}
            disabled={page === meta.totalPages}
            className="btn-ghost text-sm flex items-center gap-1 disabled:opacity-40"
          >
            Sonraki <ChevronRight size={14} />
          </button>
        </motion.div>
      )}

      {/* Kredi Yükleme Modal */}
      {grantModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
          <motion.div
            initial={{ scale: 0.95, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            className="card-surface p-6 w-full max-w-sm mx-4 space-y-4"
          >
            <h3 className="font-semibold text-lg">Kredi Yükle</h3>
            <p className="text-sm text-[var(--color-text-muted)]">{grantModal.email}</p>

            <div className="space-y-3">
              <div>
                <label className="text-xs text-[var(--color-text-muted)] mb-1 block">Miktar</label>
                <input
                  type="number"
                  value={creditAmount}
                  onChange={(e) => setCreditAmount(e.target.value)}
                  className="input w-full"
                  min="1"
                  max="1000"
                />
              </div>
              <div>
                <label className="text-xs text-[var(--color-text-muted)] mb-1 block">Açıklama</label>
                <input
                  type="text"
                  value={creditDesc}
                  onChange={(e) => setCreditDesc(e.target.value)}
                  className="input w-full"
                />
              </div>
            </div>

            <div className="flex gap-3">
              <button
                onClick={() => setGrantModal(null)}
                className="btn-ghost flex-1"
              >
                İptal
              </button>
              <button
                onClick={() => {
                  grantCredits.mutate(
                    { userId: grantModal.userId, amount: Number(creditAmount), description: creditDesc },
                    { onSuccess: () => { setGrantModal(null); refetch(); } }
                  );
                }}
                disabled={grantCredits.isPending}
                className="btn-primary flex-1 flex items-center justify-center gap-2"
              >
                {grantCredits.isPending ? <Loader2 size={14} className="animate-spin" /> : <Coins size={14} />}
                Yükle
              </button>
            </div>
          </motion.div>
        </div>
      )}
    </motion.div>
  );
}
