"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { apiFetch } from "@/lib/api/fetch";
import type { V2RenderJob } from "@/app/[locale]/admin/renders/page";

const STEP_COLORS: Record<string, string> = {
  Queued:       "bg-gray-500/20 text-gray-400 border-gray-500/30",
  Preparing:    "bg-blue-500/20 text-blue-300 border-blue-500/30",
  TemplateCache:"bg-blue-500/20 text-blue-300 border-blue-500/30",
  JsxGen:       "bg-blue-500/20 text-blue-300 border-blue-500/30",
  Music:        "bg-purple-500/20 text-purple-300 border-purple-500/30",
  Rendering:    "bg-indigo-500/20 text-indigo-300 border-indigo-500/30",
  Validating:   "bg-cyan-500/20 text-cyan-300 border-cyan-500/30",
  Repairing:    "bg-yellow-500/20 text-yellow-300 border-yellow-500/30",
  Optimisation: "bg-teal-500/20 text-teal-300 border-teal-500/30",
  Video:        "bg-indigo-500/20 text-indigo-300 border-indigo-500/30",
  Mixing:       "bg-purple-500/20 text-purple-300 border-purple-500/30",
  Final:        "bg-teal-500/20 text-teal-300 border-teal-500/30",
  Uploading:    "bg-sky-500/20 text-sky-300 border-sky-500/30",
  Done:         "bg-emerald-500/20 text-emerald-300 border-emerald-500/30",
  Failed:       "bg-red-500/20 text-red-300 border-red-500/30",
  Cancelled:    "bg-gray-500/20 text-gray-500 border-gray-500/20",
};

function relativeTime(iso: string): string {
  const diff = Math.floor((Date.now() - new Date(iso).getTime()) / 1000);
  if (diff < 60) return `${diff}s ago`;
  if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
  if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
  return `${Math.floor(diff / 86400)}d ago`;
}

export function RenderQueueTable({ jobs }: { jobs: V2RenderJob[] }) {
  const t = useTranslations("auto.componentsAdminRenderQueueTable");
  const router = useRouter();
  const [loading, setLoading] = useState<Record<string, boolean>>({});

  const retryJob = async (jobId: string) => {
    setLoading((p) => ({ ...p, [jobId]: true }));
    try {
      await apiFetch(`/api/admin/renders/${jobId}/retry`, { method: "POST" });
      router.refresh();
    } finally {
      setLoading((p) => ({ ...p, [jobId]: false }));
    }
  };

  const stopJob = async (jobId: string) => {
    if (!confirm("این رندر متوقف شود؟")) return;
    setLoading((p) => ({ ...p, [jobId]: true }));
    try {
      // Admin stop — cancels any user's job (not just the caller's) and frees the node.
      await apiFetch(`/api/admin/renders/${jobId}/stop`, { method: "POST" });
      router.refresh();
    } finally {
      setLoading((p) => ({ ...p, [jobId]: false }));
    }
  };

  if (jobs.length === 0) {
    return (
      <div className="rounded-xl border border-[#1e2235] bg-[#0f1120] px-6 py-16 text-center text-sm text-gray-500">
        {t("emptyState")}
      </div>
    );
  }

  return (
    <div className="overflow-hidden rounded-xl border border-[#1e2235]">
      <table className="w-full text-sm">
        <thead>
          <tr className="border-b border-[#1e2235] bg-[#0f1120] text-left text-xs font-medium uppercase tracking-wider text-gray-500">
            <th className="px-4 py-3">{t("colJobId")}</th>
            <th className="px-4 py-3">{t("colProject")}</th>
            <th className="px-4 py-3">{t("colStep")}</th>
            <th className="px-4 py-3">{t("colProgress")}</th>
            <th className="px-4 py-3">{t("colQuality")}</th>
            <th className="px-4 py-3">{t("colNode")}</th>
            <th className="px-4 py-3">{t("colCreated")}</th>
            <th className="px-4 py-3">{t("colActions")}</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-[#1e2235] bg-[#0c0e1a]">
          {jobs.map((job) => {
            const stepColor = STEP_COLORS[job.step] ?? STEP_COLORS.Queued;
            const canRetry = job.step === "Failed" || job.step === "Cancelled";
            const canCancel = !["Done", "Failed", "Cancelled"].includes(job.step);

            return (
              <tr key={job.id} className="hover:bg-[#0f1120]/60 transition-colors">
                <td className="px-4 py-3 font-mono text-[11px] text-gray-400">
                  {job.id.slice(0, 12)}…
                </td>
                <td className="px-4 py-3 font-mono text-[11px] text-gray-500">
                  {job.saved_project_id.slice(0, 12)}…
                </td>
                <td className="px-4 py-3">
                  <span className={`inline-flex items-center rounded-full border px-2 py-0.5 text-[11px] font-medium ${stepColor}`}>
                    {job.step}
                  </span>
                </td>
                <td className="px-4 py-3">
                  <div className="flex items-center gap-2">
                    <div className="h-1.5 w-20 overflow-hidden rounded-full bg-[#1e2235]">
                      <div
                        className="h-full rounded-full bg-primary-600"
                        style={{ width: `${job.progress}%` }}
                      />
                    </div>
                    <span className="tabular-nums text-[11px] text-gray-500">
                      {job.progress}%
                    </span>
                  </div>
                  {job.error_message && (
                    <p className="mt-0.5 text-[10px] text-red-400 max-w-[200px] truncate" title={job.error_message}>
                      {job.error_message}
                    </p>
                  )}
                </td>
                <td className="px-4 py-3 text-gray-400 text-xs">
                  {job.quality} / {job.resolution}
                </td>
                <td className="px-4 py-3 font-mono text-[11px] text-gray-500">
                  {job.node_id ? job.node_id.slice(0, 8) + "…" : "—"}
                </td>
                <td className="px-4 py-3 text-gray-500 text-xs">
                  {relativeTime(job.created_at)}
                </td>
                <td className="px-4 py-3">
                  <div className="flex gap-2">
                    {canRetry && (
                      <button
                        onClick={() => retryJob(job.id)}
                        disabled={loading[job.id]}
                        className="rounded px-2.5 py-1 text-xs text-emerald-300 border border-emerald-500/30 hover:bg-emerald-500/10 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
                      >
                        {t("actionRetry")}
                      </button>
                    )}
                    {canCancel && (
                      <button
                        onClick={() => stopJob(job.id)}
                        disabled={loading[job.id]}
                        className="rounded px-2.5 py-1 text-xs text-red-300 border border-red-500/30 hover:bg-red-500/10 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
                      >
                        {t("actionStop")}
                      </button>
                    )}
                  </div>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}
