"use client";

import { useActionState, useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { ArrowRight, CheckCircle2, Download, Eye, XCircle } from "lucide-react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { initialState } from "@/server/actions/action-state";
import type { ActionState } from "@/server/actions/action-state";
import { rejectDocumentoPendienteAction, validateDocumentoPendienteAction } from "@/server/actions/documentos";
import { badgeClassForEstadoDocumento } from "@/lib/state-variants";
import { labelEstadoDocumento, labelTipoDocumento } from "@/lib/documentos";
import { formatDateTimeCL } from "@/lib/date-format";
import type { DocumentoPendienteRow } from "@/server/queries/documentos";
import type { ReactNode } from "react";

export function DocumentosPendientesBoard({
  documentos,
  canReview,
}: {
  documentos: DocumentoPendienteRow[];
  canReview: boolean;
}) {
  return (
    <Card className="border-border shadow-sm">
      <CardContent className="p-0">
        <div className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Ficha / Código</TableHead>
                <TableHead>Manzana</TableHead>
                <TableHead>Lote</TableHead>
                <TableHead>Dirección</TableHead>
                <TableHead>Ocupante responsable</TableHead>
                <TableHead>Tipo de documento</TableHead>
                <TableHead>Nombre archivo</TableHead>
                <TableHead>Fecha subida</TableHead>
                <TableHead>Usuario que subió</TableHead>
                <TableHead>Estado</TableHead>
                <TableHead className="text-right">Acciones</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {documentos.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={11} className="py-10 text-center text-sm text-muted-foreground">
                    No hay documentos para mostrar con los filtros actuales.
                  </TableCell>
                </TableRow>
              ) : (
                documentos.map((documento) => (
                  <TableRow key={documento.id} className="align-top">
                    <TableCell className="whitespace-nowrap font-medium">
                      <div className="space-y-1">
                        <Link href={`/fichas/${documento.ficha.id}/ver`} className="font-semibold text-foreground hover:underline">
                          {documento.ficha.codigo}
                        </Link>
                      </div>
                    </TableCell>
                    <TableCell className="whitespace-nowrap">{documento.ficha.lote?.manzana ?? "-"}</TableCell>
                    <TableCell className="whitespace-nowrap">{documento.ficha.lote?.lote ?? "-"}</TableCell>
                    <TableCell className="min-w-52 max-w-64 truncate" title={documento.ficha.lote?.direccionLote ?? "-"}>
                      {documento.ficha.lote?.direccionLote ?? "-"}
                    </TableCell>
                    <TableCell className="min-w-48">
                      <div className="space-y-1">
                        <p className="font-medium text-foreground">{documento.ficha.ocupante?.nombre ?? "-"}</p>
                        <p className="text-xs text-muted-foreground">{documento.ficha.ocupante?.rut ?? "-"}</p>
                      </div>
                    </TableCell>
                    <TableCell className="min-w-44">{labelTipoDocumento(documento.tipo)}</TableCell>
                    <TableCell className="min-w-56 max-w-72 truncate" title={documento.nombreArchivo}>
                      {documento.nombreArchivo}
                    </TableCell>
                    <TableCell className="whitespace-nowrap">{formatDateTimeCL(documento.createdAt)}</TableCell>
                    <TableCell className="min-w-44">
                      <div className="space-y-1">
                        <p className="font-medium text-foreground">{documento.uploadedBy.name}</p>
                        <p className="text-xs text-muted-foreground">{documento.uploadedBy.email}</p>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge className={badgeClassForEstadoDocumento(documento.estado)}>
                        {labelEstadoDocumento(documento.estado)}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-right">
                      <DocumentActions documento={documento} canReview={canReview} />
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </CardContent>
    </Card>
  );
}

function DocumentActions({ documento, canReview }: { documento: DocumentoPendienteRow; canReview: boolean }) {
  const actions: Array<{ key: string; node: ReactNode }> = [
    {
      key: "view",
      node: (
        <Button asChild size="sm" variant="outline" className="h-8 gap-2">
          <Link href={`/api/documentos/${documento.id}/view`} target="_blank" rel="noopener noreferrer">
            <Eye className="h-4 w-4" />
            Ver
          </Link>
        </Button>
      ),
    },
    {
      key: "download",
      node: (
        <Button asChild size="sm" variant="outline" className="h-8 gap-2">
          <Link href={`/api/documentos/${documento.id}/download`}>
            <Download className="h-4 w-4" />
            Descargar
          </Link>
        </Button>
      ),
    },
    {
      key: "ficha",
      node: (
        <Button asChild size="sm" variant="secondary" className="h-8 gap-2">
          <Link href={`/fichas/${documento.fichaId}/ver`}>
            <ArrowRight className="h-4 w-4" />
            Ir a ficha
          </Link>
        </Button>
      ),
    },
  ];

  if (canReview) {
    actions.splice(
      2,
      0,
      {
        key: "validate",
        node: (
          <DocumentoReviewDialog
            documento={documento}
            mode="validate"
            label="Validar"
            action={validateDocumentoPendienteAction}
            triggerClassName="h-8 gap-2"
          >
            <CheckCircle2 className="h-4 w-4" />
            Validar
          </DocumentoReviewDialog>
        ),
      },
      {
        key: "reject",
        node: (
          <DocumentoReviewDialog
            documento={documento}
            mode="reject"
            label="Rechazar"
            action={rejectDocumentoPendienteAction}
            triggerClassName="h-8 gap-2 text-destructive hover:bg-danger-subtle"
            triggerVariant="outline"
          >
            <XCircle className="h-4 w-4" />
            Rechazar
          </DocumentoReviewDialog>
        ),
      },
    );
  }

  return <div className="flex flex-wrap justify-end gap-2">{actions.map((action) => <div key={action.key}>{action.node}</div>)}</div>;
}

function DocumentoReviewDialog({
  documento,
  mode,
  label,
  action,
  triggerClassName,
  triggerVariant = "default",
  children,
}: {
  documento: DocumentoPendienteRow;
  mode: "validate" | "reject";
  label: string;
  action: (documentoId: string, state: ActionState, formData: FormData) => Promise<ActionState>;
  triggerClassName?: string;
  triggerVariant?: "default" | "outline";
  children: ReactNode;
}) {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [state, formAction] = useActionState(action.bind(null, documento.id), initialState);

  useEffect(() => {
    if (!state.message) return;
    if (state.success) {
      toast.success(state.message);
      window.setTimeout(() => {
        setOpen(false);
        router.refresh();
      }, 0);
    } else {
      toast.error(state.message);
    }
  }, [router, state.message, state.success]);

  const errorMessage = mode === "reject" ? state.errors?.motivo?.[0] : state.errors?.observacion?.[0];
  const defaultValue =
    mode === "reject"
      ? (typeof state.formValues?.motivo === "string" ? state.formValues.motivo : "")
      : (typeof state.formValues?.observacion === "string" ? state.formValues.observacion : "");

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button type="button" size="sm" variant={triggerVariant} className={triggerClassName}>
          {children}
        </Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle>
            {label} documento
          </DialogTitle>
          <DialogDescription>
            {mode === "validate"
              ? "Puedes agregar una observación opcional antes de validar este documento."
              : "Indica el motivo del rechazo antes de confirmar."}
          </DialogDescription>
        </DialogHeader>
        <form action={formAction} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor={`${mode}-${documento.id}`}>{mode === "validate" ? "Observación" : "Motivo"}</Label>
            <Textarea
              id={`${mode}-${documento.id}`}
              name={mode === "validate" ? "observacion" : "motivo"}
              defaultValue={defaultValue}
              placeholder={mode === "validate" ? "Observación opcional" : "Motivo obligatorio"}
            />
            {errorMessage ? <p className="text-sm text-destructive">{errorMessage}</p> : null}
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setOpen(false)}>
              Cancelar
            </Button>
            <Button type="submit" variant={mode === "reject" ? "destructive" : "default"}>
              {label}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
