import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft, FileText, History, Pencil } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { labelEstadoFicha } from "@/lib/estado-ficha";
import { labelTramoRsh } from "@/lib/tramo-rsh";
import { can } from "@/lib/permissions";
import { requireUser } from "@/lib/session";
import { formatDateCL, formatDateTimeCL } from "@/lib/date-format";
import { getFichaById } from "@/server/queries/fichas";

export const dynamic = "force-dynamic";

export default async function VerFichaPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const user = await requireUser();
  if (!can(user.role, "ficha:read")) notFound();

  const ficha = await getFichaById(id);
  if (!ficha) notFound();

  const historialReciente = ficha.auditLogs.slice(0, 10);

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <Button asChild variant="ghost" size="sm" className="mb-2 px-0">
            <Link href="/fichas">
              <ArrowLeft className="h-4 w-4" />
              Volver a fichas
            </Link>
          </Button>
          <div className="flex flex-wrap items-center gap-2">
            <h2 className="text-2xl font-semibold tracking-tight">Ficha {ficha.codigo}</h2>
            <Badge variant="secondary">{labelEstadoFicha(ficha.estadoFicha)}</Badge>
          </div>
          <p className="text-sm text-muted-foreground">
            Vista solo lectura · Creada por {ficha.createdBy.name} el {formatDateCL(ficha.createdAt)}
          </p>
        </div>
        <div className="flex flex-wrap gap-2">
          {can(user.role, "ficha:update") ? (
            <Button asChild variant="outline">
              <Link href={`/fichas/${ficha.id}`}>
                <Pencil className="h-4 w-4" />
                Editar
              </Link>
            </Button>
          ) : null}
          <Button asChild variant="outline">
            <Link href={`/api/fichas/${ficha.id}/pdf`} target="_blank" rel="noopener noreferrer">
              <FileText className="h-4 w-4" />
              Descargar PDF
            </Link>
          </Button>
        </div>
      </div>

      <div className="grid gap-4 xl:grid-cols-2">
        <ReadOnlyCard
          title="Antecedentes del lote"
          items={[
            ["Número de lote", ficha.lote?.lote],
            ["Manzana", ficha.lote?.manzana],
            ["Dirección del lote", ficha.lote?.direccionLote],
            ["Nombre asociado al lote", ficha.lote?.nombreAsociado],
            ["Resolución", ficha.lote?.resolucion],
            ["Fojas", ficha.lote?.fojas],
            ["Número", ficha.lote?.numero],
            ["Año", ficha.lote?.anio?.toString()],
            ["Rol", ficha.lote?.rol],
            ["Situación del lote", labelSituacionLote(ficha.lote?.situacionLote)],
            ["Dueño / asignatario", ficha.lote?.duenoAsignatario],
            ["RUT dueño / asignatario", ficha.lote?.rutDuenoAsignatario],
            ["Contribuciones", labelContribuciones(ficha.lote?.contribuciones)],
            ["Estado de habitabilidad", labelHabitabilidad(ficha.lote?.estadoHabitabilidad)],
          ]}
        />
        <ReadOnlyCard
          title="Ocupante responsable"
          items={[
            ["Estado de ficha", labelEstadoFicha(ficha.estadoFicha)],
            ["Nombre", ficha.ocupante?.nombre],
            ["RUT", ficha.ocupante?.rut],
            ["Correo", ficha.ocupante?.correoElectronico],
            ["Teléfono", ficha.ocupante?.telefono],
              ["Fecha de nacimiento", formatDateCL(ficha.ocupante?.fechaNacimiento)],
              ["Estado civil", labelEstadoCivil(ficha.ocupante?.estadoCivil)],
              ["Situación laboral", labelSituacionLaboral(ficha.ocupante?.situacionLaboral)],
              ["Tramo % RSH", labelTramoRsh(ficha.ocupante?.tramoRsh)],
              ["Año que llegó al sector", ficha.ocupante?.anioLlegadaSector?.toString()],
              ["Cantidad de personas viviendo en el lote", ficha.ocupante?.cantidadPersonasLote?.toString()],
              ["Observaciones del ocupante", ficha.ocupante?.observaciones],
            ]}
          />
        <ReadOnlyCard
          title="Situación vivienda"
          items={[
            ["Tipo de vivienda", labelTipoVivienda(ficha.situacionVivienda?.tipoVivienda)],
            ["Estado constructivo", labelEstadoConstructivo(ficha.situacionVivienda?.estadoConstructivo)],
            ["Material predominante", labelMaterial(ficha.situacionVivienda?.materialPredominante)],
            ["Cuenta con luz", labelCuentaConLuz(ficha.situacionVivienda?.cuentaConLuz)],
            [
              "Abastecimiento de agua potable",
              labelAbastecimientoAgua(ficha.situacionVivienda?.abastecimientoAguaPotable),
            ],
            [
              "Sistema de evacuación y tratamiento de aguas servidas",
              labelSistemaEvacuacion(ficha.situacionVivienda?.sistemaEvacuacionAguas),
            ],
            ["Cantidad de viviendas en el lote", ficha.situacionVivienda?.cantidadViviendasLote?.toString()],
            ["Observaciones sociales", ficha.situacionVivienda?.observacionesSociales],
            ["Observaciones territoriales", ficha.situacionVivienda?.observacionesTerritoriales],
          ]}
        />
        <ReadOnlyCard
          title="Deslindes"
          items={[
            ["Norte", ficha.deslinde?.norte],
            ["Sur", ficha.deslinde?.sur],
            ["Este", ficha.deslinde?.este],
            ["Oeste", ficha.deslinde?.oeste],
            ["Comentarios de deslindes", ficha.deslinde?.comentarios],
          ]}
        />
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Ocupantes actuales</CardTitle>
        </CardHeader>
        <CardContent>
          {ficha.ocupantesActuales.length === 0 ? (
            <p className="text-sm text-muted-foreground">Sin ocupantes registrados.</p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="border-b bg-muted text-muted-foreground">
                  <tr>
                    <th className="px-3 py-2 text-left font-medium">Nombre</th>
                    <th className="px-3 py-2 text-left font-medium">RUT</th>
                    <th className="px-3 py-2 text-left font-medium">Edad</th>
                    <th className="px-3 py-2 text-left font-medium">Parentesco</th>
                  </tr>
                </thead>
                <tbody>
                  {ficha.ocupantesActuales.map((ocupante) => (
                    <tr key={ocupante.id} className="border-b last:border-0">
                      <td className="px-3 py-2">{display(ocupante.nombreCompleto)}</td>
                      <td className="px-3 py-2">{display(ocupante.rut)}</td>
                      <td className="px-3 py-2">{display(ocupante.edad?.toString())}</td>
                      <td className="px-3 py-2">{display(labelParentesco(ocupante.parentesco))}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Documentos</CardTitle>
        </CardHeader>
        <CardContent>
          {ficha.documentos.length === 0 ? (
            <p className="text-sm text-muted-foreground">Sin documentos registrados.</p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="border-b bg-muted text-muted-foreground">
                  <tr>
                    <th className="px-3 py-2 text-left font-medium">Nombre del archivo</th>
                    <th className="px-3 py-2 text-left font-medium">Tipo</th>
                    <th className="px-3 py-2 text-left font-medium">Estado</th>
                    <th className="px-3 py-2 text-left font-medium">Fecha subida</th>
                    <th className="px-3 py-2 text-left font-medium">Subido por</th>
                    <th className="px-3 py-2 text-left font-medium">Validador</th>
                    <th className="px-3 py-2 text-left font-medium">Validación</th>
                    <th className="px-3 py-2 text-left font-medium">Observación</th>
                    <th className="px-3 py-2 text-right font-medium">Acciones</th>
                  </tr>
                </thead>
                <tbody>
                  {ficha.documentos.map((documento) => (
                    <tr key={documento.id} className="border-b last:border-0 align-top">
                      <td className="px-3 py-2">
                        <p className="max-w-[220px] truncate font-medium" title={documento.nombreArchivo}>
                          {documento.nombreArchivo}
                        </p>
                      </td>
                      <td className="px-3 py-2">{labelDocumento(documento.tipo)}</td>
                      <td className="px-3 py-2">
                        <Badge variant={estadoDocumentoVariant(documento.estado)} className="whitespace-nowrap">
                          {labelEstadoDocumento(documento.estado)}
                        </Badge>
                      </td>
                      <td className="px-3 py-2">{formatDateCL(documento.createdAt)}</td>
                      <td className="px-3 py-2">{documento.uploadedBy.name ?? documento.uploadedBy.email}</td>
                      <td className="px-3 py-2">{documento.validatedBy?.name ?? documento.validatedBy?.email ?? "-"}</td>
                      <td className="px-3 py-2">{documento.validatedAt ? formatDateTimeCL(documento.validatedAt) : "-"}</td>
                      <td className="px-3 py-2">
                        <p className="max-w-[260px] whitespace-normal break-words text-muted-foreground">
                          {documento.observacionValidador || "-"}
                        </p>
                      </td>
                      <td className="px-3 py-2">
                        <div className="flex justify-end gap-2">
                          <Button asChild size="sm" variant="secondary">
                            <Link href={`/api/documentos/${documento.id}/view`} target="_blank" rel="noopener noreferrer">
                              Ver documento
                            </Link>
                          </Button>
                          <Button asChild size="sm" variant="outline">
                            <Link href={`/api/documentos/${documento.id}/download`} target="_blank" rel="noopener noreferrer">
                              Descargar
                            </Link>
                          </Button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Observaciones y comentarios</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <ReadOnlyCard
            title="Observaciones relevantes"
            items={[["Texto", ficha.observacionesRelevantes]]}
          />
          {ficha.comentarios.length === 0 ? (
            <p className="text-sm text-muted-foreground">Sin comentarios registrados.</p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="border-b bg-muted text-muted-foreground">
                  <tr>
                    <th className="px-3 py-2 text-left font-medium">Fecha</th>
                    <th className="px-3 py-2 text-left font-medium">Usuario</th>
                    <th className="px-3 py-2 text-left font-medium">Comentario</th>
                  </tr>
                </thead>
                <tbody>
                  {ficha.comentarios.map((comentario) => (
                    <tr key={comentario.id} className="border-b last:border-0 align-top">
                      <td className="px-3 py-2">{formatDateTimeCL(comentario.createdAt)}</td>
                      <td className="px-3 py-2">{comentario.user.name ?? comentario.user.email ?? "-"}</td>
                      <td className="px-3 py-2">
                        <p className="whitespace-pre-wrap break-words">{display(comentario.contenido)}</p>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between gap-3">
          <CardTitle>Historial</CardTitle>
          <Button asChild variant="outline" size="sm">
            <Link href={`/fichas/${ficha.id}?historialPage=1`} className="inline-flex items-center gap-2">
              <History className="h-4 w-4" />
              Ver historial completo
            </Link>
          </Button>
        </CardHeader>
        <CardContent>
          {historialReciente.length === 0 ? (
            <p className="text-sm text-muted-foreground">Sin historial registrado.</p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="border-b bg-muted text-muted-foreground">
                  <tr>
                    <th className="px-3 py-2 text-left font-medium">Fecha</th>
                    <th className="px-3 py-2 text-left font-medium">Usuario</th>
                    <th className="px-3 py-2 text-left font-medium">Sección</th>
                    <th className="px-3 py-2 text-left font-medium">Acción</th>
                    <th className="px-3 py-2 text-left font-medium">Detalle</th>
                  </tr>
                </thead>
                <tbody>
                  {historialReciente.map((log) => (
                    <tr key={log.id} className="border-b last:border-0 align-top">
                      <td className="px-3 py-2">{formatDateTimeCL(log.createdAt)}</td>
                      <td className="px-3 py-2">{log.user?.name ?? log.user?.email ?? "Sistema"}</td>
                      <td className="px-3 py-2">
                        <Badge variant="secondary" className="whitespace-nowrap">
                          {sectionLabel(log.entity)}
                        </Badge>
                      </td>
                      <td className="px-3 py-2 font-medium">{actionLabel(log.action)}</td>
                      <td className="px-3 py-2 text-muted-foreground">{detailText(log.metadata)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}

function ReadOnlyCard({ title, items }: { title: string; items: [string, string | null | undefined][] }) {
  return (
    <Card>
      <CardHeader>
        <CardTitle>{title}</CardTitle>
      </CardHeader>
      <CardContent className="grid gap-3 sm:grid-cols-2">
        {items.map(([label, value]) => (
          <div key={label} className="rounded-md border border-border bg-muted px-3 py-2">
            <p className="text-xs font-medium text-muted-foreground">{label}</p>
            <p className="mt-1 text-sm font-medium text-foreground">{display(value)}</p>
          </div>
        ))}
      </CardContent>
    </Card>
  );
}

function display(value: string | null | undefined) {
  return value?.trim() ? value : "-";
}

function labelFromMap(value: string | null | undefined, labels: Record<string, string>) {
  return value ? labels[value] ?? value : "-";
}

function labelSituacionLote(value: string | null | undefined) {
  return labelFromMap(value, {
    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",
  });
}

function labelContribuciones(value: string | null | undefined) {
  if (!value) return "-";
  if (value === "SI") return "Sí";
  if (value === "EXENTO") return "Exento";
  return value;
}

function labelHabitabilidad(value: string | null | undefined) {
  return labelFromMap(value, { HABITADO: "Habitado", DESHABITADO: "Deshabitado" });
}

function labelEstadoCivil(value: string | null | undefined) {
  return labelFromMap(value, {
    CASADO: "Casado(a)",
    VIUDO: "Viudo(a)",
    DIVORCIADO: "Divorciado(a)",
    SOLTERO: "Soltero(a)",
  });
}

function labelSituacionLaboral(value: string | null | undefined) {
  return labelFromMap(value, {
    INDEPENDIENTE: "Independiente",
    DEPENDIENTE: "Dependiente",
    PENSIONADO: "Pensionado",
    JUBILADO: "Jubilado",
    CESANTE: "Cesante",
  });
}

function labelTipoVivienda(value: string | null | undefined) {
  return labelFromMap(value, {
    VIVIENDA_1_PISO: "Vivienda de 1 piso",
    VIVIENDA_2_PISOS: "Vivienda de 2 pisos",
    VIVIENDA_PRECARIA: "Vivienda precaria",
  });
}

function labelEstadoConstructivo(value: string | null | undefined) {
  return labelFromMap(value, { BUENA: "Buena", MALA: "Mala", ACEPTABLE: "Aceptable" });
}

function labelMaterial(value: string | null | undefined) {
  return labelFromMap(value, { LIGERA: "Ligera", SOLIDA: "Sólida", MIXTO: "Mixto" });
}

function labelCuentaConLuz(value: string | null | undefined) {
  return labelFromMap(value, {
    MEDIDOR_PROPIO: "Medidor propio",
    CEDIDA_VECINOS: "Cedida por vecinos",
    CONEXION_IRREGULAR_RED_PUBLICA: "Conexión irregular a red pública",
  });
}

function labelAbastecimientoAgua(value: string | null | undefined) {
  return labelFromMap(value, {
    ALJIBE_MUNICIPAL_GOBERNACION: "Aljibe municipal / Gobernación",
    ALJIBE_PARTICULAR: "Aljibe particular",
    POZO_PROPIO: "Pozo propio",
  });
}

function labelSistemaEvacuacion(value: string | null | undefined) {
  return labelFromMap(value, {
    FOSA_SEPTICA: "Fosa séptica",
    POZO_NEGRO: "Pozo negro",
    DERIVACION_CURSO_AGUA_SUPERFICIAL: "Derivación a curso de agua superficial",
  });
}

function labelDocumento(value: string | null | undefined) {
  return labelFromMap(value, {
    RSH: "Registro Social de Hogares",
    CUENTA_LUZ: "Cuenta de luz",
    CEDULA_IDENTIDAD: "Cédula de identidad",
    ESCRITURA: "Escritura",
    RESOLUCION: "Resolución",
    CERTIFICADO: "Certificado",
    FOTO_VIVIENDA: "Fotografía vivienda",
    FOTO_TERRENO: "Fotografía terreno",
    OTRO: "Otro documento",
  });
}

function labelEstadoDocumento(value: string | null | undefined) {
  return labelFromMap(value, {
    PENDIENTE: "Pendiente",
    VALIDADO: "Validado",
    RECHAZADO: "Rechazado",
  });
}

function estadoDocumentoVariant(value: string | null | undefined) {
  if (value === "VALIDADO") return "default";
  if (value === "RECHAZADO") return "destructive";
  return "secondary";
}

function labelParentesco(value: string | null | undefined) {
  return labelFromMap(value, {
    HIJO: "Hijo(a)",
    CONYUGE: "Cónyuge",
    ESPOSO: "Esposo(a)",
    PADRE: "Padre",
    MADRE: "Madre",
    ABUELO: "Abuelo(a)",
    TIO: "Tío(a)",
    SOBRINO: "Sobrino(a)",
    NIETO: "Nieto(a)",
    OTRO: "Otro",
  });
}

function actionLabel(action: string) {
  const labels: Record<string, string> = {
    CREATE: "Creó ficha",
    UPDATE: "Actualizó ficha",
    UPDATE_OCUPANTE: "Actualizó ocupante responsable",
    UPDATE_STATUS: "Actualizó estado de ficha",
    UPDATE_LOTE: "Actualizó antecedentes del lote",
    UPDATE_VIVIENDA: "Actualizó situación vivienda",
    UPDATE_DESLINDE: "Actualizó deslindes",
    UPDATE_OBSERVACIONES: "Actualizó observaciones",
    ADD_CURRENT_OCCUPANTS: "Agregó ocupante actual",
    REMOVE_CURRENT_OCCUPANTS: "Eliminó ocupante actual",
    UPLOAD_DOCUMENT: "Subió documento",
    VIEW_DOCUMENT: "Visualizó documento",
    DOWNLOAD_DOCUMENT: "Descargó documento",
    VALIDATE_DOCUMENT: "Validó documento",
    REJECT_DOCUMENT: "Rechazó documento",
    DELETE_DOCUMENT: "Eliminó documento",
    ADD_COMMENT: "Agregó comentario",
    SOFT_DELETE: "Eliminó ficha",
  };
  return labels[action] ?? action;
}

function sectionLabel(entity: string) {
  const labels: Record<string, string> = {
    EmpadronamientoFicha: "Ficha",
    Ocupante: "Ocupante responsable",
    OcupanteActualLote: "Ocupantes actuales",
    Lote: "Antecedentes del lote",
    SituacionVivienda: "Situación vivienda",
    Deslinde: "Deslindes",
    Documento: "Documentos",
    Comentario: "Observaciones",
  };
  return labels[entity] ?? entity;
}

function detailText(metadata: unknown) {
  if (!metadata || typeof metadata !== "object") return "-";
  const value = metadata as Record<string, unknown>;
  if (typeof value.observacion === "string" && value.observacion) return value.observacion;
  if (typeof value.estadoAnterior === "string" && typeof value.estadoNuevo === "string") {
    return `${labelEstadoFicha(value.estadoAnterior)} → ${labelEstadoFicha(value.estadoNuevo)}`;
  }
  if (typeof value.tramoRshAnterior === "string" || value.tramoRshAnterior === null || typeof value.tramoRshNuevo === "string" || value.tramoRshNuevo === null) {
    const anterior = labelTramoRsh(typeof value.tramoRshAnterior === "string" ? value.tramoRshAnterior : null) || "-";
    const nuevo = labelTramoRsh(typeof value.tramoRshNuevo === "string" ? value.tramoRshNuevo : null) || "-";
    if (anterior !== "-" || nuevo !== "-") return `Tramo % RSH: ${anterior} → ${nuevo}`;
  }
  if (typeof value.nombreArchivo === "string" && value.nombreArchivo) return value.nombreArchivo;
  if (typeof value.cantidad === "number") return `Cantidad: ${value.cantidad}`;
  if (typeof value.codigo === "string" && value.codigo) return `Código: ${value.codigo}`;
  return "-";
}


