'use client';

import OrdenInternaPrint from '@/components/print/OrdenInternaPrint';
import { Button } from '@/components/ui/button';
import { EmptyState } from '@/components/ui/empty-state';
import { getLocalOtByRouteId, putRemoteOtIfNewer, setLocalOtCotizacion } from '@/lib/offline-ots';
import { cotizacionesApi, otsApi } from '@/lib/api';
import { printWhenReady } from '@/lib/print';
import '@/app/print-styles.css';
import { useQuery } from '@tanstack/react-query';
import { ArrowLeft, Loader2, Printer, Wrench } from 'lucide-react';
import { useParams, useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';

async function loadOrdenInternaForPrint(routeId: string) {
  const numericId = Number(routeId);

  if (Number.isFinite(numericId) && numericId > 0 && navigator.onLine) {
    try {
      const remoteOt = await otsApi.get(numericId);
      await putRemoteOtIfNewer(remoteOt);
    } catch (e) {
      console.warn('Using local cache for print', e);
    }
  }

  const ot = await getLocalOtByRouteId(routeId);
  if (!ot) return null;

  if (ot.serverId && navigator.onLine) {
    try {
      const remoteCot = await cotizacionesApi.getByOt(Number(ot.serverId));
      if (remoteCot) {
        await setLocalOtCotizacion(Number(ot.serverId), remoteCot);
      }
    } catch (e) {
      console.warn('Using local cotizacion cache for print', e);
    }
  }

  const freshOt = await getLocalOtByRouteId(routeId);
  const cotizacion = freshOt?.cotizaciones?.[0] || null;

  return { ot: freshOt, cotizacion };
}

export default function ImprimirOrdenInternaPage() {
  const params = useParams();
  const router = useRouter();
  const routeId = String(params.id);
  const [printing, setPrinting] = useState(false);

  const handlePrint = async () => {
    if (printing) return;
    setPrinting(true);
    try {
      await printWhenReady();
    } finally {
      setPrinting(false);
    }
  };

  const { data, isLoading } = useQuery({
    queryKey: ['print', 'orden-interna', routeId],
    queryFn: () => loadOrdenInternaForPrint(routeId),
    enabled: !!routeId,
  });

  useEffect(() => {
    if (data?.ot?.numeroOt) {
      document.title = `MBtaller-OrdenInterna-${data.ot.numeroOt}`;
    }
  }, [data?.ot?.numeroOt]);

  if (isLoading) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-surface">
        <Loader2 className="h-8 w-8 animate-spin text-subtle-foreground" />
      </div>
    );
  }

  if (!data?.ot) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-surface">
        <EmptyState
          icon={Wrench}
          title="No se encontró la orden de trabajo."
          action={
            <Button onClick={() => router.push(`/dashboard/ots/${routeId}`)}>
              Volver
            </Button>
          }
        />
      </div>
    );
  }

  return (
    <div className="print-page-wrapper">
      <div className="print-page-toolbar no-print">
        <Button variant="outline" className="border-border" onClick={() => router.push(`/dashboard/ots/${routeId}`)}>
          <ArrowLeft className="mr-2 h-4 w-4" />Volver al detalle
        </Button>
        <Button disabled={printing} onClick={handlePrint}>
          {printing ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Printer className="mr-2 h-4 w-4" />}
          {printing ? 'Preparando...' : 'Imprimir orden interna'}
        </Button>
      </div>
      <OrdenInternaPrint
        ot={data.ot}
        cotizacion={data.cotizacion}
      />
    </div>
  );
}
