'use client';

import React, { useEffect, useState, Suspense } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import BarcodeGenerator from '@/components/common/BarcodeGenerator';

type OrderLine = {
  id: string;
  boxNumber?: string | null;
  uniqueCode?: string | null;
  quantity: number;
  boxType?: string | null;
  product: {
    code: string;
    name: string;
    boxType?: string | null;
  };
  farm?: {
    name: string;
    ruc?: string | null;
  } | null;
  order: {
    po: string;
    orderNumber: string;
    shippingCustomer?: { businessName: string } | null;
    billingCustomer?: { businessName: string } | null;
    masterCustomer?: { businessName: string } | null;
  };
};

function BatchPrintContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const [lines, setLines] = useState<OrderLine[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function loadLines() {
      const idsParam = searchParams.get('ids');
      if (!idsParam) {
        setLoading(false);
        return;
      }
      const ids = idsParam.split(',').filter(Boolean);
      try {
        const fetchedLines: OrderLine[] = [];
        for (const id of ids) {
          const res = await fetch(`/api/orders/lines/${id}`);
          if (res.ok) {
            const data = await res.json();
            fetchedLines.push(data);
          }
        }
        setLines(fetchedLines);
      } catch (err) {
        console.error('Error fetching batch labels:', err);
      } finally {
        setLoading(false);
      }
    }
    loadLines();
  }, [searchParams]);

  if (loading) return <div style={{ padding: '3rem', textAlign: 'center', fontFamily: 'sans-serif' }}>Cargando etiquetas...</div>;
  if (lines.length === 0) return <div style={{ padding: '3rem', textAlign: 'center', fontFamily: 'sans-serif' }}>No se seleccionaron cajas para imprimir.</div>;

  return (
    <div style={{ background: '#f0f2f5', minHeight: '100vh', padding: '2rem', fontFamily: 'Arial, sans-serif' }}>
      <div className="no-print" style={{ marginBottom: '2rem', display: 'flex', gap: '1rem', justifyContent: 'center', alignItems: 'center' }}>
        <button
          onClick={() => router.back()}
          style={{ padding: '0.6rem 1.4rem', borderRadius: '8px', border: '1px solid #ccc', cursor: 'pointer', background: '#fff', fontWeight: 600 }}
        >
          ← Volver
        </button>
        <div style={{ fontWeight: 700, color: '#333' }}>
          {lines.length} etiqueta{lines.length !== 1 ? 's' : ''} lista{lines.length !== 1 ? 's' : ''} para imprimir
        </div>
        <button
          onClick={() => window.print()}
          style={{ padding: '0.6rem 1.8rem', borderRadius: '8px', border: 'none', background: '#1c5236', color: '#fff', cursor: 'pointer', fontWeight: 700, fontSize: '1rem', boxShadow: '0 4px 12px rgba(28,82,54,0.3)' }}
        >
          🖨️ Imprimir Todas ({lines.length})
        </button>
      </div>

      <div className="print-wrapper">
        <style dangerouslySetInnerHTML={{ __html: `
          @media print {
            @page {
              size: 100mm 145mm;
              margin: 0mm !important;
            }
            html, body {
              background: white !important;
              margin: 0 !important;
              padding: 0 !important;
              -webkit-print-color-adjust: exact;
              print-color-adjust: exact;
            }
            .no-print {
              display: none !important;
            }
            .print-wrapper {
              padding: 0 !important;
              margin: 0 !important;
            }
            .label-card {
              width: 100mm !important;
              height: 142mm !important;
              max-height: 142mm !important;
              box-shadow: none !important;
              border: none !important;
              outline: none !important;
              margin: 0 auto !important;
              padding: 4mm 6mm !important;
              box-sizing: border-box !important;
              overflow: hidden !important;
            }
            .label-card:not(:last-child) {
              page-break-after: always !important;
              break-after: page !important;
            }
            .label-card:last-child {
              page-break-after: avoid !important;
              break-after: avoid !important;
            }
          }
          @media screen {
            .label-card {
              width: 100mm;
              min-height: 145mm;
              margin: 0 auto 2.5rem;
              box-shadow: 0 10px 30px rgba(0,0,0,0.12);
              border: 1px solid #e2e8f0;
              padding: 6mm 7mm;
            }
          }
        `}} />

        {lines.map((line, idx) => {
          const clientName = line.order.masterCustomer?.businessName || line.order.shippingCustomer?.businessName || line.order.billingCustomer?.businessName || 'NEW YORK FLOWERS';
          const poNumber = line.order.po || '505657';
          const itemCode = line.product.code || '1002024';
          const productName = line.product.name || 'Freedom Rose40cm-PK100';
          const boxNumber = line.boxNumber || String(idx + 1).padStart(10, '0');
          const farmRuc = line.farm?.ruc || '1793023088001';
          const barcodeValue = line.uniqueCode || `${farmRuc}-${itemCode}-${boxNumber}`;

          return (
            <div
              key={line.id || idx}
              className="label-card"
              style={{
                position: 'relative',
                background: '#ffffff',
                borderRadius: '4px',
                boxSizing: 'border-box',
                textAlign: 'center',
                color: '#000',
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'space-between'
              }}
            >
              {/* Header with Circular Logo Centered */}
              <div style={{ marginBottom: '0.2rem', textAlign: 'center' }}>
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src="/logo_usflorals_circle.png"
                  alt="US Florals"
                  style={{ width: '42px', height: '42px', margin: '0 auto 0.15rem', display: 'block', objectFit: 'contain' }}
                />
                <div style={{ fontSize: '0.95rem', fontWeight: 900, letterSpacing: '0.12em', color: '#1c3024', lineHeight: 1.1 }}>
                  US FLORALS
                </div>
                <div style={{ fontSize: '0.65rem', fontWeight: 800, textTransform: 'uppercase', letterSpacing: '0.08em', color: '#047857', marginTop: '0.1rem' }}>
                  Freshness Redefined
                </div>
              </div>

              <div style={{ borderTop: '1.5px solid #e5e7eb', margin: '0.15rem 0' }}></div>

              {/* Master Customer Name (Made larger for pallet visibility) */}
              <div style={{ fontSize: '1.75rem', fontWeight: 900, textTransform: 'uppercase', letterSpacing: '0.02em', marginBottom: '0.25rem', color: '#000', lineHeight: 1.15 }}>
                {clientName}
              </div>

              {/* PO Number */}
              <div style={{ fontSize: '1.9rem', fontWeight: 900, letterSpacing: '0.02em', marginBottom: '0.25rem', color: '#000', lineHeight: 1.1 }}>
                PO#{poNumber}
              </div>

              {/* Item Code */}
              <div style={{ fontSize: '1.55rem', fontWeight: 900, letterSpacing: '0.02em', marginBottom: '0.2rem', color: '#111', lineHeight: 1.1 }}>
                ITEM {itemCode}
              </div>

              {/* Product Description */}
              <div style={{ fontSize: '1rem', fontWeight: 700, marginBottom: '0.25rem', color: '#333', lineHeight: 1.2 }}>
                {productName}
              </div>

              {/* Box Number */}
              <div style={{ fontSize: '1.55rem', fontWeight: 900, letterSpacing: '0.04em', marginBottom: '0.25rem', color: '#000', lineHeight: 1.1 }}>
                BOX#{boxNumber}
              </div>

              {/* Barcode (Ruc + Item + Codigo unico de caja) - Altura duplicada (110) para evitar fallas por arrugas */}
              <div style={{ borderTop: '2px dashed #333', paddingTop: '0.25rem', marginTop: '0.15rem', width: '100%', overflow: 'hidden' }}>
                <BarcodeGenerator value={barcodeValue} displayValue={true} width={2.2} height={110} fontSize={12} />
              </div>

              {/* Nombre de la Finca directamente debajo del código de barras */}
              <div style={{ marginTop: '0.25rem', fontSize: '0.85rem', fontWeight: 900, color: '#111', textAlign: 'center', textTransform: 'uppercase' }}>
                FINCA: {line.farm?.name || '—'}
              </div>

              {/* Indicación de pegado debajo de la finca */}
              <div style={{ marginTop: '0.15rem', fontSize: '0.68rem', fontWeight: 700, color: '#444', textAlign: 'center', textTransform: 'uppercase' }}>
                PEGAR EN UN SOLO LADO DE LA CAJA · CAJA {idx + 1} DE {lines.length}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

export default function BatchPrintLabelsPage() {
  return (
    <Suspense fallback={<div style={{ padding: '3rem', textAlign: 'center' }}>Cargando etiquetas...</div>}>
      <BatchPrintContent />
    </Suspense>
  );
}
