import Link from "next/link";
import type { ReactNode } from "react";
import { Eye, FileText, Pencil, Phone } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { FichaDeleteDialog } from "@/components/fichas/ficha-delete-dialog";
import { badgeClassForEstadoFicha } from "@/lib/state-variants";
import type { FichaListResult } from "@/server/queries/fichas";

export function FichasTable({
  result,
  canEdit,
  canDelete,
}: {
  result: FichaListResult;
  canEdit: boolean;
  canDelete: boolean;
}) {
  return (
    <div className="overflow-hidden rounded-lg border border-border bg-card">
      <Table>
        <TableHeader>
            <TableRow className="bg-muted">
              <TableHead className="w-[120px] px-3 py-3">Código</TableHead>
              <TableHead className="w-[80px] px-3 py-3">Manzana</TableHead>
              <TableHead className="w-[80px] px-3 py-3">Lote</TableHead>
              <TableHead className="w-[180px] px-3 py-3">Dirección</TableHead>
              <TableHead className="min-w-[180px] px-3 py-3">Ocupante</TableHead>
              <TableHead className="w-[128px] px-3 py-3">Teléfono</TableHead>
              <TableHead className="w-[120px] px-3 py-3">RUT</TableHead>
              <TableHead className="w-[160px] px-3 py-3">Situación</TableHead>
              <TableHead className="w-[130px] px-3 py-3">Estado</TableHead>
              <TableHead className="w-[72px] px-3 py-3 text-center">Docs</TableHead>
              <TableHead className="w-[160px] px-3 py-3 text-right">Acciones</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {result.items.length === 0 ? (
            <TableRow>
              <TableCell colSpan={11} className="h-24 text-center text-muted-foreground">
                No hay fichas para los filtros seleccionados.
              </TableCell>
            </TableRow>
          ) : (
            result.items.map((ficha) => (
              <TableRow key={ficha.id} className="text-sm">
                <TableCell className="px-3 py-2">
                  <span
                    title={ficha.codigo}
                    className="block max-w-[105px] truncate font-mono text-xs font-medium text-foreground"
                  >
                    {compactCode(ficha.codigo)}
                  </span>
                </TableCell>
                <TableCell className="px-3 py-2 font-medium">{ficha.lote?.manzana ?? "-"}</TableCell>
                <TableCell className="px-3 py-2 font-medium">{ficha.lote?.lote ?? "-"}</TableCell>
                <TableCell className="max-w-[180px] truncate px-3 py-2" title={ficha.lote?.direccionLote ?? ""}>
                  {ficha.lote?.direccionLote ?? "-"}
                </TableCell>
                <TableCell className="max-w-[240px] truncate px-3 py-2" title={ficha.ocupante?.nombre ?? ""}>
                  {ficha.ocupante?.nombre ?? "-"}
                </TableCell>
                <TableCell className="whitespace-nowrap px-3 py-2">
                  <span className="inline-flex items-center gap-1.5">
                    {ficha.ocupante?.telefono ? <Phone className="h-3.5 w-3.5 text-muted-foreground" /> : null}
                    {displayPhone(ficha.ocupante?.telefono)}
                  </span>
                </TableCell>
                <TableCell className="whitespace-nowrap px-3 py-2">{ficha.ocupante?.rut ?? "-"}</TableCell>
                <TableCell className="px-3 py-2">
                  <Badge variant="outline" className="whitespace-nowrap">
                    {labelSituacionLote(ficha.lote?.situacionLote)}
                  </Badge>
                </TableCell>
                <TableCell className="px-3 py-2">
                  <Badge className={badgeClassForEstadoFicha(ficha.estadoFicha)}>
                    {labelEstadoFicha(ficha.estadoFicha)}
                  </Badge>
                </TableCell>
                <TableCell className="px-3 py-2 text-center">{ficha._count.documentos}</TableCell>
                <TableCell className="px-3 py-2">
                  <div className="flex justify-end gap-1.5">
                    <IconAction href={`/fichas/${ficha.id}/ver`} title="Ver ficha">
                      <Eye className="h-4 w-4" />
                    </IconAction>
                    {canEdit ? (
                      <IconAction href={`/fichas/${ficha.id}`} title="Editar ficha">
                        <Pencil className="h-4 w-4" />
                      </IconAction>
                    ) : null}
                    <IconAction href={`/api/fichas/${ficha.id}/pdf`} title="Descargar PDF" target="_blank">
                      <FileText className="h-4 w-4" />
                    </IconAction>
                    {canDelete ? <FichaDeleteDialog fichaId={ficha.id} /> : null}
                  </div>
                </TableCell>
              </TableRow>
            ))
          )}
        </TableBody>
      </Table>
    </div>
  );
}

function displayPhone(value: string | null | undefined) {
  const phone = value?.trim();
  return phone ? phone : "-";
}

function IconAction({
  href,
  title,
  target,
  children,
}: {
  href: string;
  title: string;
  target?: string;
  children: ReactNode;
}) {
  return (
    <Button asChild size="icon" variant="ghost" className="h-8 w-8" title={title} aria-label={title}>
      <Link href={href} target={target} rel={target === "_blank" ? "noopener noreferrer" : undefined}>
        {children}
      </Link>
    </Button>
  );
}

function compactCode(value: string) {
  const parts = value.split("-");
  if (parts.length < 3 || value.length <= 14) return value;
  return `${parts[0]}-...-${parts.at(-1)}`;
}

function labelSituacionLote(value: string | null | undefined) {
  const labels: Record<string, string> = {
    CON_DUENO: "Con dueño",
    CON_RESOLUCION: "Con resolución",
    SIN_RESOLUCION: "Sin resolución",
    SIN_OCUPANTE: "Sin ocupante",
    INHABILITADO_SERVIU: "Inhabilitado por SERVIU",
    SEDE_SOCIAL: "Sede social",
    OTRO: "Otro",
  };
  return value ? labels[value] ?? value : "-";
}

function labelEstadoFicha(value: string) {
  const labels: Record<string, string> = {
    BORRADOR: "Borrador",
    COMPLETA: "Completa",
    INCOMPLETA: "Incompleta",
    EN_REVISION: "En revisión",
    ARCHIVADA: "Archivada",
  };
  return labels[value] ?? value;
}


