"use client";

import { useRouter } from "next/navigation";
import { type SearchHit, type SearchMatchField } from "@/lib/api";
import { sanitizeSnippet } from "@/lib/sanitize";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

function formatBytes(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

const MATCH_FIELD_LABEL: Record<SearchMatchField, string> = {
  subject: "📨 Subject",
  body: "✉️ Body",
  attachment_text: "📄 PDF-Anhang",
  attachment_names: "📎 Dateiname",
  from_addr: "👤 Absender",
  to_addr: "📧 Empfänger",
};

function MatchSourceBadge({ field }: { field: SearchMatchField }) {
  return (
    <span className="inline-flex items-center rounded-full bg-muted px-2 py-0.5 text-[10px] font-medium text-muted-foreground whitespace-nowrap">
      {MATCH_FIELD_LABEL[field]}
    </span>
  );
}

function SnippetLine({ hit }: { hit: SearchHit }) {
  if (!hit.snippet) return null;
  return (
    <div className="mt-1 flex items-start gap-2 text-xs text-muted-foreground font-normal">
      {hit.match_field && <MatchSourceBadge field={hit.match_field} />}
      <span
        className="min-w-0 flex-1 truncate [&_b]:font-semibold [&_b]:text-foreground"
        dangerouslySetInnerHTML={{ __html: sanitizeSnippet(hit.snippet) }}
      />
    </div>
  );
}

interface SearchResultsTableProps {
  results: SearchHit[];
  selected: Set<string>;
  setSelected: React.Dispatch<React.SetStateAction<Set<string>>>;
  total: number;
  page: number;
  totalPages: number;
  onPageChange: (page: number) => void;
}

export function SearchResultsTable({
  results,
  selected,
  setSelected,
  page,
  totalPages,
  onPageChange,
}: SearchResultsTableProps) {
  const router = useRouter();
  const allSelected = results.length > 0 && results.every((h) => selected.has(h.id));

  return (
    <>
      <Card className="overflow-x-auto">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-10">
                <Checkbox
                  checked={allSelected}
                  onCheckedChange={(checked) => {
                    if (checked) setSelected(new Set(results.map((h) => h.id)));
                    else setSelected(new Set());
                  }}
                  aria-label="Alle auswählen"
                />
              </TableHead>
              <TableHead className="w-28 sm:w-32">Datum</TableHead>
              <TableHead className="hidden w-56 md:table-cell">Von</TableHead>
              <TableHead>Betreff</TableHead>
              <TableHead className="hidden w-48 lg:table-cell">An</TableHead>
              <TableHead className="w-8 text-center" title="Anhang">📎</TableHead>
              <TableHead className="hidden w-20 text-right sm:table-cell">Größe</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {results.map((hit) => (
              <TableRow
                key={hit.id}
                className="cursor-pointer hover:bg-muted/50"
                onClick={() => router.push(`/mail/${hit.id}`)}
                role="link"
                tabIndex={0}
                onKeyDown={(e) => {
                  if (e.key === "Enter") router.push(`/mail/${hit.id}`);
                }}
                aria-label={`E-Mail von ${hit.from || "unbekannt"}: ${hit.subject || "Kein Betreff"}`}
              >
                <TableCell onClick={(e) => e.stopPropagation()}>
                  <Checkbox
                    checked={selected.has(hit.id)}
                    onCheckedChange={(checked) => {
                      setSelected((prev) => {
                        const next = new Set(prev);
                        if (checked) next.add(hit.id);
                        else next.delete(hit.id);
                        return next;
                      });
                    }}
                    aria-label="Mail auswählen"
                  />
                </TableCell>
                <TableCell className="whitespace-nowrap text-sm text-muted-foreground">
                  {hit.date
                    ? new Date(hit.date).toLocaleString("de-DE", { dateStyle: "short", timeStyle: "short" })
                    : "-"}
                </TableCell>
                <TableCell className="hidden max-w-[14rem] truncate text-sm md:table-cell">{hit.from || "-"}</TableCell>
                <TableCell className="max-w-[60vw] font-medium sm:max-w-none">
                  <div className="flex items-center gap-2">
                    <span className="truncate">{hit.subject || "(kein Betreff)"}</span>
                    {hit.thread_size && hit.thread_size > 1 && (
                      <span className="inline-flex items-center rounded-full bg-muted px-1.5 py-0.5 text-xs text-muted-foreground font-normal">
                        {hit.thread_size}
                      </span>
                    )}
                  </div>
                  {/* Absender nur auf Mobile, da Spalte "Von" dort ausgeblendet ist */}
                  {hit.from && (
                    <div className="mt-0.5 truncate text-xs text-muted-foreground md:hidden">
                      {hit.from}
                    </div>
                  )}
                  <SnippetLine hit={hit} />
                </TableCell>
                <TableCell className="hidden max-w-[12rem] truncate text-sm text-muted-foreground lg:table-cell">{hit.to || "-"}</TableCell>
                <TableCell className="text-center text-sm">
                  {hit.has_attachments ? "📎" : ""}
                </TableCell>
                <TableCell className="hidden text-right text-xs text-muted-foreground whitespace-nowrap sm:table-cell">
                  {hit.size ? formatBytes(hit.size) : ""}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </Card>

      {totalPages > 1 && (
        <div className="mt-4 flex items-center justify-center gap-2">
          <Button
            variant="outline"
            size="sm"
            disabled={page <= 1}
            onClick={() => onPageChange(page - 1)}
          >
            Zurueck
          </Button>
          <span className="text-sm text-muted-foreground">
            Seite {page} von {totalPages}
          </span>
          <Button
            variant="outline"
            size="sm"
            disabled={page >= totalPages}
            onClick={() => onPageChange(page + 1)}
          >
            Weiter
          </Button>
        </div>
      )}
    </>
  );
}
