"use client";

import { useLocale, useTranslations } from "next-intl";

import { GradeBadge } from "@/components/dashboard/grade-badge";
import { QuickTestBar } from "@/components/dashboard/quick-test-bar";
import { Card, CardContent } from "@/components/ui/card";
import { useTestsListQuery } from "@/data/speed/tests-list-query";
import { Link } from "@/i18n/navigation";
import { calculatePerformanceScore, formatMetricValue, scoreToGrade } from "@/lib/scoring";

export default function TestsListPage() {
  const t = useTranslations("Tests");
  const locale = useLocale();
  const dateLocale = locale === "fr" ? "fr-FR" : locale === "es" ? "es-ES" : "en-US";
  const { data: tests, isLoading } = useTestsListQuery();

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">{t("title")}</h1>
      </div>

      <Card>
        <CardContent className="pt-6">
          <QuickTestBar />
        </CardContent>
      </Card>

      {isLoading ? (
        <p className="text-muted-foreground">{t("loading")}</p>
      ) : !tests || tests.length === 0 ? (
        <Card>
          <CardContent className="py-12 text-center text-muted-foreground">
            {t("empty")}
          </CardContent>
        </Card>
      ) : (
        <div className="overflow-x-auto rounded-lg border">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b bg-muted/50">
                <th className="px-4 py-3 text-left font-medium">{t("columns.url")}</th>
                <th className="px-4 py-3 text-center font-medium">{t("columns.score")}</th>
                <th className="px-4 py-3 text-center font-medium">{t("columns.lcp")}</th>
                <th className="px-4 py-3 text-center font-medium">{t("columns.tbt")}</th>
                <th className="px-4 py-3 text-center font-medium">{t("columns.cls")}</th>
                <th className="px-4 py-3 text-center font-medium">{t("columns.status")}</th>
                <th className="px-4 py-3 text-left font-medium">{t("columns.date")}</th>
              </tr>
            </thead>
            <tbody>
              {tests.map((test) => {
                const score = test.metrics ? calculatePerformanceScore(test.metrics) : null;
                const grade = score !== null ? scoreToGrade(score) : null;

                return (
                  <tr key={test.id} className="border-b transition-colors hover:bg-muted/30">
                    <td className="max-w-xs truncate px-4 py-3">
                      <Link
                        href={`/dashboard/tests/${test.id}`}
                        className="font-medium hover:underline"
                      >
                        {test.url}
                      </Link>
                    </td>
                    <td className="px-4 py-3 text-center">
                      {grade ? (
                        <GradeBadge grade={grade} size="sm" />
                      ) : (
                        <span className="text-muted-foreground">--</span>
                      )}
                    </td>
                    <td className="px-4 py-3 text-center">
                      {test.metrics?.largestContentfulPaint
                        ? formatMetricValue("lcp", test.metrics.largestContentfulPaint)
                        : "--"}
                    </td>
                    <td className="px-4 py-3 text-center">
                      {test.metrics?.totalBlockingTime != null
                        ? formatMetricValue("tbt", test.metrics.totalBlockingTime)
                        : "--"}
                    </td>
                    <td className="px-4 py-3 text-center">
                      {test.metrics?.cumulativeLayoutShift != null
                        ? formatMetricValue("cls", test.metrics.cumulativeLayoutShift)
                        : "--"}
                    </td>
                    <td className="px-4 py-3 text-center">
                      {t(`status.${test.status as "queued" | "running" | "completed" | "failed"}`)}
                    </td>
                    <td className="px-4 py-3 text-muted-foreground">
                      {new Date(test.createdAt).toLocaleDateString(dateLocale)}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
