import Link from "next/link";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  JOB_STATUS_LABELS,
  PROSTHETIC_TYPE_LABELS,
} from "@/lib/appwrite/job-types";
import type { JobWithCounterpart } from "@/lib/appwrite/job-queries";
import type { JobStatus } from "@/lib/appwrite/schema";

const dateFormatter = new Intl.DateTimeFormat("tr-TR", {
  day: "2-digit",
  month: "2-digit",
  year: "numeric",
});

function statusVariant(status: JobStatus): "default" | "secondary" | "outline" | "destructive" {
  switch (status) {
    case "delivered":
      return "default";
    case "sent":
      return "secondary";
    case "in_progress":
      return "secondary";
    case "cancelled":
      return "destructive";
    default:
      return "outline";
  }
}

export function JobsTable({
  rows,
  counterpartLabel,
  emptyMessage,
}: {
  rows: JobWithCounterpart[];
  counterpartLabel: string;
  emptyMessage: string;
}) {
  if (rows.length === 0) {
    return (
      <p className="text-muted-foreground py-6 text-center text-sm">{emptyMessage}</p>
    );
  }

  return (
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead>{counterpartLabel}</TableHead>
          <TableHead>Hasta Kodu</TableHead>
          <TableHead>Üye</TableHead>
          <TableHead>Renk</TableHead>
          <TableHead>Tür</TableHead>
          <TableHead>Durum</TableHead>
          <TableHead>Tarih</TableHead>
          <TableHead className="text-right">İşlem</TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {rows.map((j) => (
          <TableRow key={j.$id}>
            <TableCell className="font-medium">{j.counterpart?.companyName ?? "—"}</TableCell>
            <TableCell className="font-mono text-xs">{j.patientCode}</TableCell>
            <TableCell className="tabular-nums">{j.memberCount}</TableCell>
            <TableCell className="text-muted-foreground">{j.color || "—"}</TableCell>
            <TableCell className="text-muted-foreground">
              {PROSTHETIC_TYPE_LABELS[j.prostheticType] ?? j.prostheticType}
            </TableCell>
            <TableCell>
              <Badge variant={statusVariant(j.status)}>{JOB_STATUS_LABELS[j.status]}</Badge>
            </TableCell>
            <TableCell className="text-muted-foreground text-xs">
              {dateFormatter.format(new Date(j.$createdAt))}
            </TableCell>
            <TableCell className="text-right">
              <Button asChild size="sm" variant="outline">
                <Link href={`/jobs/${j.$id}`}>Detay</Link>
              </Button>
            </TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  );
}
