"use client";

import { useState } from "react";
import { motion } from "framer-motion";
import {
  Cpu,
  RefreshCw,
  Loader2,
  CheckCircle2,
  XCircle,
  Clock,
  AlertTriangle,
  ChevronLeft,
  ChevronRight,
} from "lucide-react";
import { useAdminRenderJobs } from "@/hooks/use-api";

const STATUS_CONFIG: Record<string, { label: string; color: string; icon: React.ElementType }> = {
  QUEUED: { label: "Beklemede", color: "text-neutral-400 bg-neutral-500/10 border border-neutral-500/20", icon: Clock },
  PROCESSING: { label: "İşleniyor", color: "text-neutral-400 bg-neutral-500/10 border border-neutral-500/20", icon: Loader2 },
  COMPLETED: { label: "Tamamlandı", color: "text-neutral-400 bg-neutral-500/10 border border-neutral-500/20", icon: CheckCircle2 },
  FAILED: { label: "Başarısız", color: "text-neutral-400 bg-neutral-500/10 border border-neutral-500/20", icon: XCircle },
  CANCELLED: { label: "İptal", color: "text-[var(--color-text-ghost)] bg-[var(--color-bg-surface)] border border-[var(--color-border-faint)]", icon: AlertTriangle },
};

function formatMs(ms?: number) {
  if (!ms) return "—";
  const s = Math.floor(ms / 1000);
  if (s < 60) return `${s}s`;
  const m = Math.floor(s / 60);
  return `${m}d ${s % 60}s`;
}

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

export default function AdminRenderJobsPage() {
  const [page, setPage] = useState(1);
  const [statusFilter, setStatusFilter] = useState("");

  const { data, isLoading, refetch } = useAdminRenderJobs({
    page,
    limit: 25,
    status: statusFilter || undefined,
  });

  // 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 jobs = (response?.data ?? []) as any[];
  const meta = response?.meta ?? {};

  return (
    <motion.div
      initial="hidden"
      animate="show"
      variants={{ show: { transition: { staggerChildren: 0.06 } } }}
      className="space-y-5 max-w-7xl mx-auto"
    >
      <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">
            <Cpu size={22} className="text-neutral-400" /> Render İş Takibi
          </h1>
          <p className="text-sm text-[var(--color-text-muted)] mt-1">
            Toplam {meta.total ?? "—"} render işi (15 saniyede bir güncellenir)
          </p>
        </div>
        <button onClick={() => refetch()} className="btn-ghost text-sm flex items-center gap-2">
          <RefreshCw size={14} /> Yenile
        </button>
      </motion.div>

      {/* Durum Filtresi */}
      <motion.div variants={fadeUp} className="flex gap-2 flex-wrap">
        {[{ value: "", label: "Tümü" }, ...Object.entries(STATUS_CONFIG).map(([k, v]) => ({ value: k, label: v.label }))].map(({ value, label }) => (
          <button
            key={value}
            onClick={() => { setStatusFilter(value); setPage(1); }}
            className={`text-xs px-3 py-1.5 rounded-full transition-colors border ${
              statusFilter === value
                ? "border-neutral-500 bg-[var(--color-bg-inverted)] text-[var(--color-text-inverted)]"
                : "border-[var(--color-border-faint)] text-[var(--color-text-muted)] hover:border-neutral-500/40"
            }`}
          >
            {label}
          </button>
        ))}
      </motion.div>

      <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">Job ID</th>
                  <th className="text-left px-4 py-3 text-xs text-[var(--color-text-muted)] font-medium">Proje</th>
                  <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">Durum</th>
                  <th className="text-left px-4 py-3 text-xs text-[var(--color-text-muted)] font-medium">Aşama</th>
                  <th className="text-left px-4 py-3 text-xs text-[var(--color-text-muted)] font-medium">Deneme</th>
                  <th className="text-left px-4 py-3 text-xs text-[var(--color-text-muted)] font-medium">Süre</th>
                  <th className="text-left px-4 py-3 text-xs text-[var(--color-text-muted)] font-medium">Tarih</th>
                </tr>
              </thead>
              <tbody>
                {jobs.map((job) => {
                  const cfg = STATUS_CONFIG[job.status] ?? { label: job.status, color: "text-gray-400 bg-gray-500/10", icon: AlertTriangle };
                  const Icon = cfg.icon;
                  return (
                    <tr
                      key={job.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 font-mono text-[10px] text-[var(--color-text-ghost)]">
                        {job.id.slice(0, 8)}…
                      </td>
                      <td className="px-4 py-3">
                        <div className="font-medium max-w-[160px] truncate">{job.project?.title ?? "—"}</div>
                      </td>
                      <td className="px-4 py-3 text-xs text-[var(--color-text-muted)]">
                        {job.project?.user?.email ?? "—"}
                      </td>
                      <td className="px-4 py-3">
                        <span className={`text-[10px] px-2 py-0.5 rounded-full ${cfg.color} flex items-center gap-1 w-fit`}>
                          <Icon size={10} className={job.status === "PROCESSING" ? "animate-spin" : ""} />
                          {cfg.label}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-[10px] text-[var(--color-text-ghost)] capitalize">
                        {job.currentStage?.toLowerCase().replace("_", " ") ?? "—"}
                      </td>
                      <td className="px-4 py-3 text-xs text-center">{job.attemptNumber}</td>
                      <td className="px-4 py-3 text-xs font-mono">{formatMs(job.processingTimeMs)}</td>
                      <td className="px-4 py-3 text-xs text-[var(--color-text-muted)]">
                        {new Date(job.createdAt).toLocaleDateString("tr")}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </motion.div>

      {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>
      )}
    </motion.div>
  );
}
