"use client";

import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
import { ErrorState } from "@/components/ui/error-state";
import { Skeleton, SkeletonDetailHeader } from "@/components/ui/skeleton";
import { publicOtsApi } from "@/lib/api";
import { formatCurrency, formatDate, formatDateTime } from "@/lib/utils";
import { useQuery } from "@tanstack/react-query";
import {
  Car,
  CheckCircle2,
  Clock,
  LockKeyhole,
  Receipt,
  Store,
} from "lucide-react";
import { useParams } from "next/navigation";

const steps = [
  {
    id: "borrador",
    label: "Recibido",
    description:
      "Ya recibimos tu vehículo y registramos la información inicial de la orden.",
  },
  {
    id: "cotizada",
    label: "Cotizado",
    description:
      "El taller preparó la cotización para que puedas revisarla y aprobarla.",
  },
  {
    id: "aprobada",
    label: "Aprobado",
    description:
      "La cotización fue aprobada. El taller ya puede programar o iniciar el trabajo.",
  },
  {
    id: "en_proceso",
    label: "En taller",
    description: "Tu vehículo está siendo trabajado por el equipo del taller.",
  },
  {
    id: "terminada",
    label: "Terminado",
    description:
      "El trabajo fue terminado y el vehículo está pendiente de entrega.",
  },
  {
    id: "entregada",
    label: "Entregado",
    description: "La orden fue cerrada y el vehículo fue entregado al cliente.",
  },
] as const;

export default function PublicOtStatusPage() {
  const params = useParams();
  const token = String(params.token || "");

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

  if (isLoading) {
    return (
      <main className="min-h-screen bg-muted p-3 sm:p-6">
        <div className="mx-auto max-w-4xl space-y-4">
          <Card>
            <CardContent className="space-y-5 p-5 sm:p-7">
              <SkeletonDetailHeader />
              <div className="grid gap-3 sm: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="space-y-3 p-5 sm:p-7">
              {Array.from({ length: 4 }).map((_, index) => (
                <Skeleton key={index} className="h-16 rounded-lg" />
              ))}
            </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={Clock}
              title="Estado 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 currentIndex = Math.max(
    0,
    steps.findIndex((step) => step.id === data.estado),
  );

  return (
    <main className="min-h-screen bg-muted p-3 sm:p-6">
      <div className="mx-auto max-w-4xl 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">
                  Estado de tu vehículo
                </h1>
                <p className="mt-2 text-sm text-muted-foreground">
                  OT {data.numeroOt} ·{" "}
                  {data.fechaEntrada ? formatDate(data.fechaEntrada) : "-"}
                </p>
              </div>
              {steps.some((step) => step.id === data.estado) ? (
                <Badge variant="estado" estado={data.estado} className="uppercase">
                  {data.estadoLabel}
                </Badge>
              ) : (
                <Badge variant="primary" className="uppercase">
                  {data.estadoLabel}
                </Badge>
              )}
            </div>

            <div className="grid gap-3 sm:grid-cols-3">
              <div className="rounded-lg border border-border bg-muted p-4">
                <div className="flex items-center gap-2 text-foreground">
                  <Car className="h-4 w-4" />
                  <span className="text-sm font-medium">Vehículo</span>
                </div>
                <p className="mt-2 text-base font-semibold text-foreground">
                  {data.vehiculo?.placa || "Sin placa"}
                </p>
                <p className="mt-1 text-sm text-muted-foreground">
                  {data.vehiculo?.marca || ""} {data.vehiculo?.modelo || ""}{" "}
                  {data.vehiculo?.anio ? `(${data.vehiculo.anio})` : ""}
                </p>
              </div>

              <div className="rounded-lg border border-border bg-muted p-4">
                <p className="text-sm font-medium text-foreground">Cliente</p>
                <p className="mt-2 text-base font-semibold text-foreground">
                  {data.cliente?.nombre || "Cliente"}
                </p>
                <p className="mt-1 text-sm text-muted-foreground">
                  Última actualización:{" "}
                  {data.updatedAt ? formatDateTime(data.updatedAt) : "-"}
                </p>
              </div>

              <div className="rounded-lg border border-border bg-foreground p-4 text-background">
                <div className="flex items-center gap-2 text-background/70">
                  <Store className="h-4 w-4" />
                  <span className="text-sm font-medium">Taller</span>
                </div>
                <p className="mt-2 text-base font-semibold">
                  {data.tienda?.nombre || "MBTaller"}
                </p>
                <p className="mt-1 text-sm text-background/70">
                  Seguimiento actualizado por el taller.
                </p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-5 sm:p-7">
            <h2 className="text-base font-semibold text-foreground">
              Seguimiento
            </h2>
            <p className="mt-2 text-sm text-muted-foreground">
              Aquí puedes ver en qué punto va tu vehículo. Las etapas en verde
              ya fueron completadas y la etapa marcada en azul es el estado
              actual.
            </p>
            <div className="mt-5 space-y-3">
              {steps.map((step, index) => {
                const done = index <= currentIndex;
                const current = index === currentIndex;
                return (
                  <div
                    key={step.id}
                    className={`flex items-center gap-3 rounded-lg border p-4 ${
                      current
                        ? "border-primary/30 bg-primary-soft"
                        : done
                          ? "border-success/20 bg-success-soft"
                          : "border-border bg-muted"
                    }`}
                  >
                    <span
                      className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-sm font-semibold ${
                        done
                          ? "bg-success text-success-foreground"
                          : "bg-surface text-subtle-foreground"
                      }`}
                    >
                      {done ? <CheckCircle2 className="h-5 w-5" /> : index + 1}
                    </span>
                    <div>
                      <p className="text-sm font-semibold text-foreground">
                        {step.label}
                      </p>
                      <p className="mt-1 text-sm text-muted-foreground">
                        {current
                          ? `Estado actual: ${step.description}`
                          : step.description}
                      </p>
                    </div>
                  </div>
                );
              })}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-5 sm:p-7">
            <div className="flex items-start gap-3">
              <span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-muted text-foreground">
                <Receipt className="h-5 w-5" />
              </span>
              <div>
                <h2 className="text-base font-semibold text-foreground">
                  Cotización
                </h2>
                {data.cotizacion ? (
                  <>
                    <p className="mt-1 text-sm text-muted-foreground">
                      {data.cotizacion.numeroCotizacion || "Cotización"} ·
                      Estado: {data.cotizacion.estado}
                    </p>
                    <p className="mt-3 text-xl font-bold text-foreground">
                      {formatCurrency(Number(data.cotizacion.total || 0))}
                    </p>
                  </>
                ) : (
                  <p className="mt-1 text-sm text-muted-foreground">
                    Todavía no hay una cotización para esta orden. El taller te
                    avisará cuando esté lista para tu revisión.
                  </p>
                )}
              </div>
            </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>
              Este link es privado para consultar el seguimiento de la orden. Si
              tienes dudas, responde al WhatsApp desde donde recibiste el
              enlace.
            </p>
          </CardContent>
        </Card>
      </div>
    </main>
  );
}
