'use client';

import { DashboardEmptyState, DashboardListRow, DashboardPageIntro, DashboardSection, DashboardToolbar } from '@/components/dashboard-page';
import { DataRefreshControl } from '@/components/data-refresh-control';
import { PaginatedListFooter } from '@/components/paginated-list-footer';
import { Badge, type EstadoOT } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { ErrorState } from '@/components/ui/error-state';
import { SkeletonListRow } from '@/components/ui/skeleton';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { useFlagsConfiguracion } from '@/hooks/use-flags-configuracion';
import { useToast } from '@/hooks/use-toast';
import { otsApi } from '@/lib/api';
import { cacheRemoteOtList, getLocalOtList } from '@/lib/offline-ots';
import { formatDate, getEstadoLabel } from '@/lib/utils';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { AlertCircle, Camera, Car, ClipboardList, Fuel, PenTool, Plus, Receipt } from 'lucide-react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useMemo, useRef, useState } from 'react';

const ESTADOS_OT: readonly EstadoOT[] = ['borrador', 'en_proceso', 'cotizada', 'aprobada', 'terminada', 'facturada', 'entregada'];

function isEstadoOT(value: string): value is EstadoOT {
  return (ESTADOS_OT as readonly string[]).includes(value);
}

function EstadoOtBadge({ estado }: { estado: string }) {
  if (isEstadoOT(estado)) {
    return (
      <Badge variant="estado" estado={estado}>
        {getEstadoLabel(estado)}
      </Badge>
    );
  }
  return <Badge variant="outline">{getEstadoLabel(estado)}</Badge>;
}

const estados = [
  { value: '', label: 'Todos' },
  { value: 'borrador', label: 'Nuevo' },
  { value: 'en_proceso', label: 'En taller' },
  { value: 'cotizada', label: 'Cotizada' },
  { value: 'aprobada', label: 'Aprobada' },
  { value: 'terminada', label: 'Lista' },
  { value: 'facturada', label: 'Facturada' },
  { value: 'entregada', label: 'Entregada' },
];

const REMOTE_SYNC_THROTTLE_MS = 10000;

export default function OTsListPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const flags = useFlagsConfiguracion();
  const usaFirmas = flags.usaFirmaCliente || flags.usaFirmaRecepcion;
  const [search, setSearch] = useState(searchParams.get('search') || '');
  const [estado, setEstado] = useState(searchParams.get('estado') || '');
  const [page, setPage] = useState(1);
  const lastSyncAt = useRef(0);
  const hasShownSyncError = useRef(false);

  const { data, dataUpdatedAt, isFetching, isLoading, isError, refetch } = useQuery({
    queryKey: ['ots', 'list', estado, page, search],
    queryFn: async () => {
      const now = Date.now();

      // The remote fetch always warms the full local cache (it isn't
      // filtered by search/estado), so it shouldn't re-run on every
      // keystroke — only throttled in the background.
      if (navigator.onLine && now - lastSyncAt.current > REMOTE_SYNC_THROTTLE_MS) {
        lastSyncAt.current = now;

        void (async () => {
          try {
            const remote = await otsApi.list({ page: 1, limit: 1000 });
            const remoteRows = remote?.data || [];
            if (Array.isArray(remoteRows)) {
              await cacheRemoteOtList(remoteRows);
            }
            hasShownSyncError.current = false;
            await queryClient.invalidateQueries({ queryKey: ['ots', 'list'] });
          } catch (error) {
            console.warn('Falling back to local OT cache', error);
            if (!hasShownSyncError.current) {
              hasShownSyncError.current = true;
              toast({
                variant: 'destructive',
                title: 'No se pudo actualizar',
                description: 'Mostrando recepciones guardadas en este dispositivo. Revisa la conexión con el servidor.',
              });
            }
          }
        })();
      }

      return getLocalOtList({ estado, page, limit: 20, search });
    },
    refetchInterval: 15000,
    refetchOnReconnect: true,
    refetchOnWindowFocus: true,
  });

  const totalOts = useMemo(() => {
    const byEstado = data?.byEstado || {};
    return Object.values(byEstado).reduce<number>((acc, current) => acc + Number(current || 0), 0);
  }, [data]);

  const statusCounts: Record<string, number> = data?.byEstado || {};
  const estadosVisibles = estados.filter(
    (item) => item.value !== 'facturada' || flags.usaFacturacion || Number(statusCounts.facturada || 0) > 0 || estado === 'facturada',
  );
  const rows = data?.data || [];
  const currentPageValue = data?.page || page;
  const currentTotal = data?.total || 0;
  const currentTotalPages = data?.totalPages || 1;
  const hasSearch = search.trim().length > 0;
  const hasFilters = hasSearch || Boolean(estado);

  return (
    <div className="min-h-full pb-16 md:pb-10">
      <main className="mx-auto flex max-w-6xl flex-col gap-5">
        <DashboardPageIntro
          title="Recepciones"
          description="Órdenes de trabajo activas y su avance, con búsqueda y filtro por estado."
          icon={ClipboardList}
          tone="slate"
          onBack={() => router.push('/dashboard')}
          actions={
            <div className="flex flex-wrap items-center gap-2">
              <DataRefreshControl updatedAt={dataUpdatedAt} isFetching={isFetching} onRefresh={() => void refetch()} />
              <Link href="/dashboard/ots/nueva">
                <Button className="w-full sm:w-auto">
                  <Plus className="mr-2 h-4 w-4" />
                  Recibir vehículo
                </Button>
              </Link>
            </div>
          }
          stats={[
            { label: 'Total', value: totalOts, icon: ClipboardList, href: '/dashboard/ots' },
            { label: 'En taller', value: Number(statusCounts.en_proceso || 0) + Number(statusCounts.aprobada || 0), icon: Car, href: '/dashboard/ots?estado=en_proceso' },
            { label: 'Listas', value: Number(statusCounts.terminada || 0), icon: ClipboardList, href: '/dashboard/ots?estado=terminada' },
            { label: 'Entregadas', value: Number(statusCounts.entregada || 0), icon: ClipboardList, href: '/dashboard/ots?estado=entregada' },
          ]}
          filters={
            <DashboardToolbar
              searchValue={search}
              onSearchChange={(value) => {
                setSearch(value);
                setPage(1);
              }}
              searchPlaceholder="Placa, cliente o número de recepción"
              filters={
                <div className="flex w-full snap-x gap-2 overflow-x-auto pb-1 [-webkit-overflow-scrolling:touch] sm:w-auto">
                  {estadosVisibles.map((item) => {
                    const count = item.value ? Number(statusCounts[item.value] || 0) : totalOts;
                    const isActive = estado === item.value;

                    return (
                      <button
                        key={item.value}
                        type="button"
                        onClick={() => {
                          setEstado(item.value);
                          setPage(1);
                        }}
                        className={`flex shrink-0 snap-start items-center gap-1.5 rounded-md px-3 py-2 text-sm font-semibold transition-colors duration-150 ease-out ${
                          isActive ? 'bg-foreground text-background' : 'bg-muted text-muted-foreground [@media(hover:hover)]:hover:bg-border'
                        }`}
                      >
                        {item.label}
                        <span className={`rounded-full px-1.5 py-0.5 text-xs ${isActive ? 'bg-background/20 text-background' : 'bg-surface text-subtle-foreground'}`}>
                          {count}
                        </span>
                      </button>
                    );
                  })}
                </div>
              }
            />
          }
        />

        {isLoading ? (
          <DashboardSection title="Listado" description="Cargando recepciones disponibles.">
            <div className="hidden divide-y divide-border md:block">
              {Array.from({ length: 5 }).map((_, index) => (
                <SkeletonListRow key={index} />
              ))}
            </div>
            <div className="space-y-3 md:hidden">
              {Array.from({ length: 5 }).map((_, index) => (
                <SkeletonListRow key={index} />
              ))}
            </div>
          </DashboardSection>
        ) : isError ? (
          <DashboardSection title="Listado" description="No se pudo cargar el listado de recepciones.">
            <ErrorState onRetry={() => refetch()} description="No se pudo cargar la lista de recepciones guardada en este dispositivo." />
          </DashboardSection>
        ) : rows.length === 0 ? (
          <DashboardEmptyState
            title={hasFilters ? 'No se encontraron recepciones' : 'No hay recepciones'}
            description={hasFilters ? 'Prueba con otra búsqueda o quita el filtro de estado.' : 'Recibe el primer vehículo para empezar a trabajar la orden.'}
            icon={ClipboardList}
            action={
              <Link href="/dashboard/ots/nueva">
                <Button>
                  <Plus className="mr-2 h-4 w-4" />
                  Recibir vehículo
                </Button>
              </Link>
            }
          />
        ) : (
          <DashboardSection title="Listado de recepciones" description="Toca una fila para abrir el detalle completo de la orden.">
            <div className="space-y-4">
              <PaginatedListFooter
                page={currentPageValue}
                limit={20}
                total={currentTotal}
                totalPages={currentTotalPages}
                itemLabel="recepciones"
                onPageChange={setPage}
              />

              {/* Mobile: filas táctiles de 64px. Desktop: tabla real, las columnas
                  (vehículo, estado, indicadores, combustible) caben sin apretarse. */}
              <div className="overflow-hidden rounded-xl border border-border md:hidden">
                {rows.map((ot: any) => {
                  const fotoCount = ot.fotos?.length || 0;
                  const danoCount = ot.danos?.length || 0;
                  const hasFirma = Boolean(ot.firma?.firmaCliente || ot.firma?.firmaRecepcion);

                  return (
                    <DashboardListRow
                      key={ot.id}
                      icon={<Car className="h-4 w-4" />}
                      href={`/dashboard/ots/${ot.id}`}
                      title={
                        <span className="flex min-w-0 items-center gap-2">
                          <span className="truncate uppercase tracking-wide">{ot.vehiculo?.placa || 'Sin placa'}</span>
                          <EstadoOtBadge estado={ot.estado} />
                        </span>
                      }
                      meta={[
                        ot.numeroOt,
                        formatDate(ot.fechaEntrada),
                        flags.usaFotos ? `${fotoCount} foto${fotoCount === 1 ? '' : 's'}` : null,
                        flags.usaDanos ? `${danoCount} daño${danoCount === 1 ? '' : 's'}` : null,
                        usaFirmas ? (hasFirma ? 'Firmada' : 'Sin firma') : null,
                      ]
                        .filter(Boolean)
                        .join(' · ')}
                    />
                  );
                })}
              </div>

              <div className="hidden md:block">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Vehículo</TableHead>
                      <TableHead>Estado</TableHead>
                      <TableHead>Recepción</TableHead>
                      <TableHead>Indicadores</TableHead>
                      <TableHead>Combustible</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {rows.map((ot: any) => {
                      const fotoCount = ot.fotos?.length || 0;
                      const hasFirma = Boolean(ot.firma?.firmaCliente || ot.firma?.firmaRecepcion);
                      const danoCount = ot.danos?.length || 0;
                      const hasCotizacion = ot.cotizaciones?.length > 0;
                      const fuelLevel = Math.max(0, Math.min(100, Number(ot.nivelGasolina || 0)));
                      const fuelTone = fuelLevel <= 20 ? 'bg-destructive' : fuelLevel <= 50 ? 'bg-warning' : 'bg-success';

                      return (
                        <TableRow
                          key={ot.id}
                          className="cursor-pointer"
                          role="link"
                          tabIndex={0}
                          aria-label={`Ver OT ${ot.numeroOt}`}
                          onClick={() => router.push(`/dashboard/ots/${ot.id}`)}
                          onKeyDown={(event) => {
                            if (event.key === 'Enter' || event.key === ' ') {
                              event.preventDefault();
                              router.push(`/dashboard/ots/${ot.id}`);
                            }
                          }}
                        >
                          <TableCell>
                            <p className="font-semibold uppercase tracking-wide text-foreground">{ot.vehiculo?.placa || 'Sin placa'}</p>
                            <p className="mt-0.5 text-xs text-muted-foreground">{ot.vehiculo?.marca || ''} {ot.vehiculo?.modelo || ''}</p>
                          </TableCell>
                          <TableCell>
                            <EstadoOtBadge estado={ot.estado} />
                          </TableCell>
                          <TableCell className="text-muted-foreground">
                            <p className="text-foreground">{ot.numeroOt}</p>
                            <p className="mt-0.5 text-xs">{formatDate(ot.fechaEntrada)}</p>
                          </TableCell>
                          <TableCell>
                            <div className="flex flex-wrap gap-1.5">
                              {flags.usaFotos ? (
                                <Badge variant={fotoCount ? 'primary' : 'warning'}>
                                  <Camera className="h-3 w-3" /> {fotoCount ? `${fotoCount} fotos` : 'Sin fotos'}
                                </Badge>
                              ) : null}
                              {flags.usaDanos && danoCount ? (
                                <Badge variant="warning">
                                  <AlertCircle className="h-3 w-3" /> {danoCount} daño{danoCount > 1 ? 's' : ''}
                                </Badge>
                              ) : null}
                              {usaFirmas ? (
                                <Badge variant={hasFirma ? 'success' : 'warning'}>
                                  <PenTool className="h-3 w-3" /> {hasFirma ? 'Firmada' : 'Sin firma'}
                                </Badge>
                              ) : null}
                              <Badge variant={hasCotizacion ? 'success' : 'neutral'}>
                                <Receipt className="h-3 w-3" /> {hasCotizacion ? 'Cotizada' : 'Sin cotizar'}
                              </Badge>
                            </div>
                          </TableCell>
                          <TableCell>
                            <div className="flex items-center gap-2">
                              <Fuel className="h-3.5 w-3.5 shrink-0 text-subtle-foreground" />
                              <span className="h-2 w-16 overflow-hidden rounded-full bg-border">
                                <span className={`block h-full rounded-full ${fuelTone}`} style={{ width: `${fuelLevel}%` }} />
                              </span>
                              <span className="text-xs font-medium text-muted-foreground">{fuelLevel}%</span>
                            </div>
                          </TableCell>
                        </TableRow>
                      );
                    })}
                  </TableBody>
                </Table>
              </div>

              {currentTotalPages > 1 ? (
                <PaginatedListFooter
                  page={currentPageValue}
                  limit={20}
                  total={currentTotal}
                  totalPages={currentTotalPages}
                  itemLabel="recepciones"
                  onPageChange={setPage}
                />
              ) : null}
            </div>
          </DashboardSection>
        )}
      </main>
    </div>
  );
}
