'use client';

import { DashboardEmptyState, DashboardListRow, DashboardPageIntro, DashboardSection } from '@/components/dashboard-page';
import { Badge, type EstadoOT } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { ErrorState } from '@/components/ui/error-state';
import { Skeleton, SkeletonListRow } from '@/components/ui/skeleton';
import { useAuth } from '@/components/providers';
import { useFlagsConfiguracion } from '@/hooks/use-flags-configuracion';
import { otsApi } from '@/lib/api';
import { cacheRemoteOtList, getLocalOtList } from '@/lib/offline-ots';
import { formatDate, getEstadoLabel } from '@/lib/utils';
import { useQuery } from '@tanstack/react-query';
import {
  AlertCircle,
  Camera,
  Car,
  CheckCircle2,
  ChevronRight,
  ClipboardList,
  Clock,
  Fuel,
  Gauge,
  PenTool,
  Plus,
  Receipt,
  RefreshCw,
  UserRound,
  Wrench,
} from 'lucide-react';
import Link from 'next/link';
import { useMemo } from 'react';

function FuelGauge({ level }: { level: number }) {
  const value = Math.max(0, Math.min(100, level));
  const color = value <= 20 ? 'bg-destructive' : value <= 50 ? 'bg-warning' : 'bg-success';

  return (
    <div className="flex items-center gap-2">
      <Fuel className="h-4 w-4 text-subtle-foreground" />
      <div className="h-2 w-20 overflow-hidden rounded-full bg-border">
        <div className={`h-full rounded-full ${color}`} style={{ width: `${value}%` }} />
      </div>
      <span className="text-sm font-semibold text-foreground">{value}%</span>
    </div>
  );
}

function EvidenceBadges({ ot }: { ot: any }) {
  const flags = useFlagsConfiguracion();
  const usaFirmas = flags.usaFirmaCliente || flags.usaFirmaRecepcion;
  const fotoCount = ot.fotos?.length || 0;
  const danoCount = ot.danos?.length || 0;
  const hasFirma = Boolean(ot.firma?.firmaCliente || ot.firma?.firmaRecepcion);
  const hasCotizacion = ot.cotizaciones?.length > 0;

  return (
    <div className="flex flex-wrap gap-2">
      {flags.usaFotos ? (
        <Badge variant={fotoCount ? 'primary' : 'warning'}>
          <Camera className="h-3.5 w-3.5" />
          {fotoCount ? `${fotoCount} fotos` : 'Sin fotos'}
        </Badge>
      ) : null}
      {usaFirmas ? (
        <Badge variant={hasFirma ? 'success' : 'warning'}>
          <PenTool className="h-3.5 w-3.5" />
          {hasFirma ? 'Firmada' : 'Sin firma'}
        </Badge>
      ) : null}
      <Badge variant={hasCotizacion ? 'neutral' : 'outline'}>
        <Receipt className="h-3.5 w-3.5" />
        {hasCotizacion ? 'Cotizada' : 'Sin cotizar'}
      </Badge>
      {flags.usaDanos && danoCount ? (
        <Badge variant="destructive">
          <AlertCircle className="h-3.5 w-3.5" />
          {danoCount} daño{danoCount > 1 ? 's' : ''}
        </Badge>
      ) : null}
    </div>
  );
}

/*
 * Esqueleto de una tarjeta "en taller": calca el layout real (placa + badge,
 * modelo, metadatos, medidor de gasolina, chips de evidencia) para que la
 * carga no salte cuando llegan los datos. No existe una primitiva genérica
 * para esta forma específica en `ui/skeleton.tsx` porque es propia de esta
 * pantalla; se compone con los mismos bloques `Skeleton` que usan las demás.
 */
function VehiculoCardSkeleton() {
  return (
    <Card className="p-4">
      <div className="flex items-start justify-between gap-3">
        <div className="min-w-0 flex-1 space-y-2">
          <Skeleton className="h-6 w-24" />
          <Skeleton className="h-4 w-32" />
        </div>
        <Skeleton className="h-5 w-5 shrink-0 rounded-full" />
      </div>
      <div className="mt-4 flex items-center gap-4 border-t border-border pt-4">
        <Skeleton className="h-4 w-20" />
        <Skeleton className="h-4 w-24" />
      </div>
      <div className="mt-3 flex gap-2">
        <Skeleton className="h-6 w-20 rounded-full" />
        <Skeleton className="h-6 w-20 rounded-full" />
      </div>
    </Card>
  );
}

export default function DashboardPage() {
  const { canRead } = useAuth();
  const flags = useFlagsConfiguracion();

  const { data: otsData, isLoading, isError, refetch, isFetching } = useQuery({
    queryKey: ['ots', 'dashboard'],
    queryFn: async () => {
      if (navigator.onLine) {
        try {
          const remote = await otsApi.list({ page: 1, limit: 1000 });
          const remoteRows = remote?.data || [];
          if (Array.isArray(remoteRows)) {
            await cacheRemoteOtList(remoteRows);
          }
        } catch (error) {
          console.warn('Using local OT cache for dashboard', error);
        }
      }

      return getLocalOtList({ page: 1, limit: 200 });
    },
    staleTime: 30000,
  });

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

  const vehiculosEnTaller = useMemo(() => {
    const rows = otsData?.data || [];
    return rows.filter((ot: any) => ot.estado !== 'entregada' && ot.estado !== 'terminada' && ot.estado !== 'facturada');
  }, [otsData]);

  const activas = Number(otsData?.byEstado?.en_proceso || 0) + Number(otsData?.byEstado?.aprobada || 0);
  const entregadas = Number(otsData?.byEstado?.entregada || 0);
  const recientes = otsData?.data?.slice(0, 5) || [];

  const statValue = (value: number) => (isLoading ? <Skeleton className="h-7 w-10" /> : value);

  return (
    <div className="min-h-full pb-16 md:pb-10">
      <main className="mx-auto flex max-w-7xl flex-col gap-5">
        <DashboardPageIntro
          title="Taller"
          icon={Wrench}
          tone="slate"
          actions={
            <div className="grid w-full grid-cols-1 gap-2 sm:w-auto sm:grid-cols-2">
              <Link href="/dashboard/ots/nueva" className="w-full">
                <Button size="xl" className="w-full">
                  <Plus className="mr-2 h-6 w-6" />
                  Recibir vehículo
                </Button>
              </Link>
              <Button variant="outline" size="xl" className="w-full" onClick={() => refetch()}>
                <RefreshCw className={`mr-2 h-5 w-5 ${isFetching ? 'animate-spin' : ''}`} />
                Actualizar
              </Button>
            </div>
          }
          stats={[
            { label: 'En taller', value: statValue(vehiculosEnTaller.length), icon: Car, href: '/dashboard/ots?estado=en_proceso' },
            { label: 'Activas', value: statValue(activas), icon: Wrench, href: '/dashboard/ots?estado=aprobada' },
            { label: 'Entregadas', value: statValue(entregadas), icon: CheckCircle2, href: '/dashboard/ots?estado=entregada' },
            { label: 'Total', value: statValue(totalOts), icon: ClipboardList, href: '/dashboard/ots' },
          ]}
        />

        <DashboardSection title="Acciones">
          <div className="grid gap-3 md:grid-cols-4">
            {[
              { href: '/dashboard/ots/nueva', icon: Plus, label: 'Recibir vehículo', primary: true },
              { href: '/dashboard/ots', icon: ClipboardList, label: 'Ver recepciones' },
              { href: '/dashboard/clientes', icon: UserRound, label: 'Clientes' },
              { href: '/dashboard/vehiculos', icon: Car, label: 'Vehículos' },
            ].map((item) => (
              <Link key={item.href} href={item.href}>
                <Card
                  className={`hover-lift flex min-h-24 items-center gap-4 p-4 active:scale-[0.98] ${item.primary ? 'border-primary bg-primary text-primary-foreground' : 'text-foreground'}`}
                >
                  <span className={`flex h-12 w-12 shrink-0 items-center justify-center rounded-xl ${item.primary ? 'bg-primary-foreground/15 text-primary-foreground' : 'bg-muted text-muted-foreground'}`}>
                    <item.icon className="h-6 w-6" />
                  </span>
                  <span className="text-lg font-bold leading-tight">{item.label}</span>
                </Card>
              </Link>
            ))}
          </div>
        </DashboardSection>

        {isError ? (
          <ErrorState onRetry={() => refetch()} description="No se pudieron cargar las recepciones. Revisá tu conexión e intentá de nuevo." />
        ) : (
          <>
            {isLoading ? (
              <DashboardSection title="En taller">
                <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
                  {Array.from({ length: 3 }).map((_, index) => (
                    <VehiculoCardSkeleton key={index} />
                  ))}
                </div>
              </DashboardSection>
            ) : vehiculosEnTaller.length > 0 ? (
              <DashboardSection title={`En taller (${vehiculosEnTaller.length})`}>
                <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
                  {vehiculosEnTaller.slice(0, 9).map((ot: any) => (
                    <Link key={ot.id} href={`/dashboard/ots/${ot.id}`}>
                      <Card className="hover-lift h-full p-4 active:scale-[0.98]">
                        <div className="flex items-start justify-between gap-3">
                          <div className="min-w-0">
                            <div className="flex flex-wrap items-center gap-2">
                              <span className="text-2xl font-bold uppercase tracking-wide text-foreground">{ot.vehiculo?.placa || 'Sin placa'}</span>
                              <Badge variant="estado" estado={ot.estado as EstadoOT}>
                                {getEstadoLabel(ot.estado)}
                              </Badge>
                            </div>
                            <p className="mt-1 text-base font-semibold text-foreground">
                              {ot.vehiculo?.marca || ''} {ot.vehiculo?.modelo || ''}
                            </p>
                            <p className="mt-1 text-sm text-muted-foreground">{ot.numeroOt} | {formatDate(ot.fechaEntrada)}</p>
                          </div>
                          <ChevronRight className="mt-1 h-6 w-6 shrink-0 text-subtle-foreground" />
                        </div>

                        <div className="mt-4 flex flex-wrap items-center gap-4 border-t border-border pt-4">
                          <div className="flex items-center gap-2 text-sm font-semibold text-foreground">
                            <Gauge className="h-4 w-4 text-subtle-foreground" />
                            {Number(ot.km || 0).toLocaleString()} km
                          </div>
                          <FuelGauge level={Number(ot.nivelGasolina || 0)} />
                        </div>

                        <div className="mt-3">
                          <EvidenceBadges ot={ot} />
                        </div>
                      </Card>
                    </Link>
                  ))}
                </div>
              </DashboardSection>
            ) : (
              <DashboardEmptyState
                title="No hay vehículos en taller"
                description="Usa Recibir vehículo para empezar."
                icon={Car}
                action={
                  <Link href="/dashboard/ots/nueva">
                    <Button>
                      <Plus className="mr-2 h-5 w-5" />
                      Recibir vehículo
                    </Button>
                  </Link>
                }
              />
            )}

            <div className="grid gap-5 xl:grid-cols-[1.2fr_0.8fr]">
              <DashboardSection title="Últimas recepciones">
                {isLoading ? (
                  <div className="-m-4 md:-m-5">
                    {Array.from({ length: 4 }).map((_, index) => (
                      <SkeletonListRow key={index} />
                    ))}
                  </div>
                ) : recientes.length === 0 ? (
                  <DashboardEmptyState title="No hay recepciones" description="Crea la primera recepción." icon={ClipboardList} />
                ) : (
                  <div className="-m-4 md:-m-5">
                    {recientes.map((ot: any) => (
                      <DashboardListRow
                        key={ot.id}
                        href={`/dashboard/ots/${ot.id}`}
                        icon={<Car className="h-5 w-5" />}
                        title={
                          <span className="flex flex-wrap items-center gap-2">
                            <span className="uppercase">{ot.vehiculo?.placa || 'Sin placa'}</span>
                            <Badge variant="estado" estado={ot.estado as EstadoOT}>
                              {getEstadoLabel(ot.estado)}
                            </Badge>
                          </span>
                        }
                        meta={`${ot.numeroOt} | ${formatDate(ot.fechaEntrada)}`}
                        actions={<ChevronRight className="h-5 w-5 text-subtle-foreground" />}
                      />
                    ))}
                  </div>
                )}
              </DashboardSection>

              <DashboardSection title="Más opciones">
                <div className="-m-4 md:-m-5">
                  {[
                    ...(flags.usaHistorial ? [{ href: '/dashboard/historial', icon: Clock, label: 'Historial' }] : []),
                    { href: '/dashboard/catalogos', icon: Wrench, label: 'Catálogos' },
                    ...(canRead('reportes') && flags.usaReportes ? [{ href: '/dashboard/reportes', icon: ClipboardList, label: 'Reportes' }] : []),
                  ].map((item) => (
                    <DashboardListRow
                      key={item.href}
                      href={item.href}
                      icon={<item.icon className="h-5 w-5" />}
                      title={item.label}
                      actions={<ChevronRight className="h-5 w-5 text-subtle-foreground" />}
                    />
                  ))}
                </div>
              </DashboardSection>
            </div>
          </>
        )}
      </main>
    </div>
  );
}
