"use client";

import { useConfirm } from "@/components/confirm-provider";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { ErrorState } from "@/components/ui/error-state";
import { Input } from "@/components/ui/input";
import { Skeleton, SkeletonDetailHeader } from "@/components/ui/skeleton";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/hooks/use-toast";
import { publicCotizacionesApi } from "@/lib/api";
import { formatCurrency, formatDate } from "@/lib/utils";
import { nombreVisibleParaCliente } from "@/lib/print";
import { useResponsiveSignaturePad } from "@/lib/signature-pad";
import { useMutation, useQuery } from "@tanstack/react-query";
import {
  CheckCircle2,
  Loader2,
  LockKeyhole,
  Receipt,
  RotateCcw,
  XCircle,
} from "lucide-react";
import { useParams } from "next/navigation";
import { useRef, useState } from "react";
import SignatureCanvas from "react-signature-canvas";

export default function PublicCotizacionPage() {
  const params = useParams();
  const token = String(params.token || "");
  const { toast } = useToast();
  const confirm = useConfirm();
  const signatureRef = useRef<SignatureCanvas | null>(null);
  const signaturePadContainerRef = useRef<HTMLDivElement | null>(null);
  const isDrawingRef = useRef(false);
  const [nombre, setNombre] = useState("");
  const [motivo, setMotivo] = useState("");

  // El canvas de react-signature-canvas dibuja sobre un buffer de pixeles
  // fijo (300x150 por defecto) que el CSS solo estira si no se ajusta a
  // mano; en un celular eso distorsiona la firma del cliente justo en la
  // pantalla donde firma algo con validez legal.
  useResponsiveSignaturePad(signatureRef, signaturePadContainerRef, isDrawingRef);

  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ["public-cotizacion", token],
    queryFn: () => publicCotizacionesApi.get(token),
    enabled: Boolean(token),
    retry: false,
  });

  const decisionMutation = useMutation({
    mutationFn: async (decision: "aceptar" | "rechazar") => {
      const cleanName = nombre.trim();
      const cleanMotivo = motivo.trim();

      if (!cleanName) {
        throw new Error("Escribe tu nombre para firmar.");
      }

      if (!signatureRef.current || signatureRef.current.isEmpty()) {
        throw new Error("Dibuja tu firma antes de continuar.");
      }

      if (decision === "rechazar" && !cleanMotivo) {
        throw new Error("Indica el motivo del rechazo.");
      }

      return publicCotizacionesApi.decide(token, {
        decision,
        nombre: cleanName,
        firma: signatureRef.current.toDataURL("image/png"),
        motivo: cleanMotivo || undefined,
      });
    },
    onSuccess: async () => {
      await refetch();
      toast({
        variant: "success",
        title: "Respuesta registrada",
        description: "Gracias. Tu respuesta quedó guardada.",
      });
    },
    onError: (error: any) =>
      toast({
        variant: "destructive",
        title: "No se pudo registrar",
        description: error.message || "Intenta de nuevo.",
      }),
  });

  if (isLoading) {
    return (
      <main className="min-h-screen bg-muted p-3 sm:p-6">
        <div className="mx-auto max-w-5xl space-y-4">
          <Card>
            <CardContent className="space-y-5 p-5 sm:p-7">
              <SkeletonDetailHeader />
              <div className="grid gap-3 lg:grid-cols-3">
                <Skeleton className="h-24 rounded-lg" />
                <Skeleton className="h-24 rounded-lg" />
                <Skeleton className="h-24 rounded-lg" />
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-0">
              <div className="space-y-3 p-5">
                <Skeleton className="h-4 w-1/3" />
                <Skeleton className="h-4 w-2/3" />
                <Skeleton className="h-4 w-1/2" />
              </div>
            </CardContent>
          </Card>
        </div>
      </main>
    );
  }

  if (!data || isError) {
    return (
      <main className="flex min-h-screen items-center justify-center bg-muted p-4">
        <Card className="w-full max-w-lg">
          <CardContent className="p-2">
            <ErrorState
              icon={Receipt}
              title="Cotización no disponible"
              description="El enlace no existe o ya expiró. Si crees que es un error, pídele al taller que te reenvíe el link."
              onRetry={() => refetch()}
            />
          </CardContent>
        </Card>
      </main>
    );
  }

  const closed = data.estado === "aprobada" || data.estado === "rechazada";
  const observaciones = String(
    data.ot?.observaciones || data.ot?.requerimientoCliente || "",
  ).trim();
  const estadoBadgeVariant =
    data.estado === "aprobada"
      ? "success"
      : data.estado === "rechazada"
        ? "destructive"
        : "warning";

  return (
    <main className="min-h-screen bg-muted p-3 sm:p-6">
      <div className="mx-auto max-w-5xl space-y-6">
        <Card className="overflow-hidden">
          <CardContent className="space-y-5 p-5 sm:p-7">
            <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
              <div>
                <p className="text-xs font-semibold uppercase tracking-wider text-subtle-foreground">
                  MBTaller
                </p>
                <h1 className="mt-1 text-2xl font-bold tracking-tight text-foreground">
                  Cotización {data.numeroCotizacion}
                </h1>
                <p className="mt-2 text-sm text-muted-foreground">
                  OT {data.ot?.numeroOt || "-"} ·{" "}
                  {data.ot?.vehiculo?.placa || "Sin placa"} ·{" "}
                  {data.ot?.fechaEntrada
                    ? formatDate(data.ot.fechaEntrada)
                    : "-"}
                </p>
                <p className="mt-1 text-sm font-medium text-foreground">
                  {data.ot?.vehiculo?.marca || ""}{" "}
                  {data.ot?.vehiculo?.modelo || ""}{" "}
                  {data.ot?.vehiculo?.anio ? `(${data.ot.vehiculo.anio})` : ""}
                </p>
              </div>
              <Badge variant={estadoBadgeVariant} className="uppercase">
                {data.estado}
              </Badge>
            </div>

            <div className="grid gap-3 lg:grid-cols-3">
              <div className="rounded-lg border border-border bg-muted p-4">
                <p className="text-xs font-semibold uppercase tracking-wider text-subtle-foreground">
                  Asesor
                </p>
                <p className="mt-1 text-base font-semibold text-foreground">
                  {nombreVisibleParaCliente(data.asesorNombre) || "-"}
                </p>
              </div>
              <div className="rounded-lg border border-border bg-muted p-4">
                <p className="text-xs font-semibold uppercase tracking-wider text-subtle-foreground">
                  Mecánico asignado
                </p>
                <p className="mt-1 text-base font-semibold text-foreground">
                  {data.ot?.mecanico?.nombre || "Pendiente"}
                </p>
                {data.ot?.mecanico?.especialidad ? (
                  <p className="mt-1 text-sm text-muted-foreground">
                    {data.ot.mecanico.especialidad}
                  </p>
                ) : null}
              </div>
              <div className="rounded-lg border border-border bg-foreground p-4 text-background">
                <p className="text-xs font-semibold uppercase tracking-wider text-background/70">
                  Total
                </p>
                <p className="mt-1 text-xl font-bold">
                  {formatCurrency(Number(data.total || 0))}
                </p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-0">
            <div className="border-b border-border p-5">
              <h2 className="text-base font-semibold text-foreground">
                Detalle
              </h2>
            </div>
            <div className="divide-y divide-border">
              {(data.lineas || []).length > 0 ? (
                (data.lineas || []).map((linea: any) => (
                  <div
                    key={linea.id}
                    className="grid gap-2 p-5 sm:grid-cols-[1fr_110px_140px] sm:items-center"
                  >
                    <div>
                      <p className="font-medium text-foreground">
                        {linea.descripcion}
                      </p>
                      <p className="mt-1 text-xs font-medium uppercase tracking-wider text-subtle-foreground">
                        {linea.plu}
                      </p>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      Cant. {Number(linea.cantidad || 0).toLocaleString()}
                    </p>
                    <p className="text-right text-sm font-semibold text-foreground">
                      {formatCurrency(Number(linea.total || 0))}
                    </p>
                  </div>
                ))
              ) : (
                <div className="p-5">
                  <p className="text-sm text-muted-foreground">
                    Todavía no hay productos ni servicios en esta cotización. El
                    taller los agregará antes de solicitar tu aprobación.
                  </p>
                </div>
              )}
            </div>
          </CardContent>
        </Card>

        {observaciones ? (
          <Card>
            <CardContent className="p-5 sm:p-7">
              <p className="text-xs font-semibold uppercase tracking-wider text-subtle-foreground">
                Solicitud de Cliente
              </p>
              <p className="mt-2 whitespace-pre-wrap text-sm leading-6 text-foreground">
                {observaciones}
              </p>
            </CardContent>
          </Card>
        ) : null}

        <Card>
          <CardContent className="space-y-4 p-5 sm:p-7">
            {closed ? (
              <div className="rounded-lg border border-border bg-muted p-5 text-center">
                <CheckCircle2 className="mx-auto h-10 w-10 text-success" />
                <h2 className="mt-3 text-base font-semibold text-foreground">
                  Respuesta ya registrada
                </h2>
                <p className="mt-1 text-sm text-muted-foreground">
                  {data.decisionClienteNombre
                    ? `${data.decisionClienteNombre} respondió esta cotización.`
                    : "Esta cotización ya fue respondida."}
                </p>
              </div>
            ) : (
              <>
                <div>
                  <label htmlFor="firma-cliente-nombre" className="text-sm font-medium text-foreground">
                    Nombre de quien firma
                  </label>
                  <Input
                    id="firma-cliente-nombre"
                    maxLength={255}
                    value={nombre}
                    onChange={(event) => setNombre(event.target.value)}
                    className="mt-2 h-12"
                  />
                </div>
                <div>
                  <label className="text-sm font-medium text-foreground">
                    Firma
                  </label>
                  <div
                    ref={signaturePadContainerRef}
                    className="mt-2 h-48 touch-none overflow-hidden rounded-md border border-border bg-surface"
                  >
                    <SignatureCanvas
                      ref={signatureRef}
                      penColor="#0f172a"
                      onBegin={() => { isDrawingRef.current = true; }}
                      onEnd={() => { isDrawingRef.current = false; }}
                      canvasProps={{
                        className: "h-full w-full bg-surface",
                        style: { touchAction: "none" },
                        "aria-label": "Área para dibujar la firma con el dedo o lápiz",
                      }}
                    />
                  </div>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    className="mt-2"
                    onClick={() => signatureRef.current?.clear()}
                  >
                    <RotateCcw className="mr-2 h-4 w-4" />
                    Limpiar firma
                  </Button>
                </div>
                <div>
                  <label htmlFor="cotizacion-motivo-rechazo" className="text-sm font-medium text-foreground">
                    Motivo si rechaza
                  </label>
                  <Textarea
                    id="cotizacion-motivo-rechazo"
                    maxLength={1000}
                    value={motivo}
                    onChange={(event) => setMotivo(event.target.value)}
                    className="mt-2 min-h-24"
                    placeholder="Obligatorio solo si vas a rechazar la cotización"
                  />
                </div>
                <div className="grid gap-3 sm:grid-cols-2">
                  <Button
                    className="h-12"
                    disabled={decisionMutation.isPending}
                    onClick={async () => {
                      const confirmed = await confirm({
                        title: "¿Aceptar esta cotización?",
                        description: "Quedará firmada con tu nombre y no se puede deshacer desde aquí.",
                        confirmLabel: "Sí, aceptar",
                      });
                      if (confirmed) decisionMutation.mutate("aceptar");
                    }}
                  >
                    {decisionMutation.isPending ? (
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    ) : (
                      <CheckCircle2 className="mr-2 h-4 w-4" />
                    )}
                    Aceptar cotización
                  </Button>
                  <Button
                    variant="outline"
                    className="h-12 text-destructive hover:bg-destructive-soft"
                    disabled={decisionMutation.isPending}
                    onClick={async () => {
                      const confirmed = await confirm({
                        title: "¿Rechazar esta cotización?",
                        description: "Quedará firmada con tu nombre como rechazo y no se puede deshacer desde aquí.",
                        confirmLabel: "Sí, rechazar",
                        tone: "destructive",
                      });
                      if (confirmed) decisionMutation.mutate("rechazar");
                    }}
                  >
                    <XCircle className="mr-2 h-4 w-4" />
                    Rechazar
                  </Button>
                </div>
              </>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardContent className="flex flex-col gap-3 p-5 text-sm text-muted-foreground sm:flex-row sm:items-center">
            <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground">
              <LockKeyhole className="h-5 w-5" />
            </span>
            <p>
              Esta cotización solo puede responderse desde este link privado. Tu
              nombre, firma y decisión quedarán registrados en el historial de
              la orden.
            </p>
          </CardContent>
        </Card>
      </div>
    </main>
  );
}
