"use client";

import Link from "next/link";
import { formatDuration } from "@/lib/utils/analytics-format";
import type { RespondentSummary } from "@/types/analytics";
import { RespondentStatusPill } from "./RespondentStatusPill";

interface RespondentsTableProps {
  surveyId: string;
  respondents: RespondentSummary[];
}

export function RespondentsTable({
  surveyId,
  respondents,
}: RespondentsTableProps) {
  if (respondents.length === 0) {
    return (
      <p className="py-8 text-center text-sm text-muted">
        No respondents match the current filters.
      </p>
    );
  }

  return (
    <div className="overflow-x-auto">
      <table className="w-full min-w-[520px] text-left text-sm">
        <thead>
          <tr className="border-b border-border text-xs font-semibold text-muted">
            <th className="px-3 py-2.5">Started</th>
            <th className="px-3 py-2.5">Status</th>
            <th className="px-3 py-2.5">Duration</th>
            <th className="px-3 py-2.5 text-right">View</th>
          </tr>
        </thead>
        <tbody>
          {respondents.slice(0, 50).map((r) => (
            <tr key={r.id} className="border-b border-border/60 hover:bg-bg/60">
              <td className="px-3 py-2.5">
                {r.startedAt.toLocaleString("en-US", {
                  month: "short",
                  day: "numeric",
                  hour: "numeric",
                  minute: "2-digit",
                })}
              </td>
              <td className="px-3 py-2.5">
                <RespondentStatusPill status={r.status} />
              </td>
              <td className="px-3 py-2.5 font-mono text-xs text-muted">
                {r.timeToCompleteSeconds != null
                  ? formatDuration(r.timeToCompleteSeconds)
                  : "—"}
              </td>
              <td className="px-3 py-2.5 text-right">
                <Link
                  href={`/app/surveys/${surveyId}/results/respondent/${r.id}`}
                  className="text-xs font-semibold text-primary hover:underline"
                >
                  Details →
                </Link>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      {respondents.length > 50 && (
        <p className="mt-2 px-3 text-xs text-muted">
          Showing 50 of {respondents.length} respondents. Export CSV for full
          data.
        </p>
      )}
    </div>
  );
}
