'use client';

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

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

export default function ColdRoomPrintLabelsPage() {
  const { id } = useParams();
  const router = useRouter();
  const [line, setLine] = useState<ColdRoomLine | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function loadLine() {
      try {
        const res = await fetch(`/api/cold-room/${id}`);
        if (res.ok) {
          const data = await res.json();
          setLine(data);
        }
      } catch (err) {
        console.error(err);
      } finally {
        setLoading(false);
      }
    }
    if (id) loadLine();
  }, [id]);

  if (loading) return <div style={{ padding: '2rem', textAlign: 'center' }}>Cargando etiquetas...</div>;
  if (!line) return <div style={{ padding: '2rem', textAlign: 'center' }}>No se encontró la caja.</div>;

  const clientName = line.order?.masterCustomer?.businessName || line.order?.shippingCustomer?.businessName || "NEW YORK FLOWERS";
  const boxNumber = line.boxNumber || line.id.slice(-6);
  const farmRuc = line.farm?.ruc || '1793023088001';
  const barcodeValue = line.uniqueCode || `${farmRuc}-${line.product.code}-${boxNumber}`;
  
  // Generate labels based on quantity
  const labels: { index: number, total: number }[] = [];
  const qty = line.quantity || 1;
  for (let i = 1; i <= qty; i++) {
    labels.push({ index: i, total: qty });
  }

  return (
    <div style={{ background: '#f0f0f0', minHeight: '100vh', padding: '2rem' }}>
      <div className="no-print" style={{ marginBottom: '2rem', display: 'flex', gap: '1rem', justifyContent: 'center' }}>
        <button onClick={() => router.back()} style={{ padding: '0.5rem 1rem', borderRadius: '4px', border: '1px solid #ccc', cursor: 'pointer', background: '#fff' }}>Volver</button>
        <button onClick={() => window.print()} style={{ padding: '0.5rem 1.4rem', borderRadius: '4px', border: 'none', background: '#1c5236', color: '#fff', cursor: 'pointer', fontWeight: 700 }}>🖨️ Imprimir Etiquetas Zebra (10x14.5 cm)</button>
      </div>

      <div className="print-container">
        <style dangerouslySetInnerHTML={{__html: `
          @media print {
            @page {
              size: 100mm 145mm;
              margin: 0;
            }
            body {
              background: white !important;
              margin: 0 !important;
              padding: 0 !important;
            }
            .no-print {
              display: none !important;
            }
            .print-container {
              padding: 0 !important;
              margin: 0 !important;
            }
            .label-card {
              width: 100mm !important;
              height: 145mm !important;
              max-height: 145mm !important;
              page-break-after: always;
              break-after: page;
              box-shadow: none !important;
              border: 2px solid #000 !important;
              margin: 0 auto !important;
              padding: 5mm 6mm !important;
              box-sizing: border-box !important;
            }
          }
          @media screen {
            .label-card {
              width: 100mm;
              min-height: 145mm;
              margin: 0 auto 2rem;
              box-shadow: 0 10px 30px rgba(0,0,0,0.12);
              padding: 6mm 7mm;
              background: #fff;
            }
          }
        `}} />

        {labels.map((label, idx) => (
          <div
            key={`${line.id}-${idx}`}
            className="label-card"
            style={{
              position: 'relative',
              background: '#ffffff',
              border: '2px solid #1a1a1a',
              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 */}
            <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#{line.order.po}
            </div>

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

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

            {/* Box Number */}
            <div style={{ fontSize: '1.55rem', fontWeight: 900, letterSpacing: '0.04em', marginBottom: '0.25rem', color: '#000', lineHeight: 1.1 }}>
              BOX#{boxNumber} ({label.index} de {label.total})
            </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 {label.index} DE {label.total}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
