'use client';

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

type LabelData = {
  id: string;
  boxNumber?: string | null;
  uniqueCode?: string | null;
  quantity?: number;
  boxType?: string | null;
  isCancelled?: boolean;
  cancelledAt?: string | null;
  reason?: string | null;
  isQc?: boolean;
  qcReason?: string | null;
  qcComment?: string | null;
  qcPrice?: number;
  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;
  };
};

export default function PrintSingleLabelPage() {
  const { id } = useParams();
  const searchParams = useSearchParams();
  const isCancelledQuery = searchParams.get('cancelled') === 'true';
  const isQcQuery = searchParams.get('type') === 'qc' || searchParams.get('qc') === 'true';
  const router = useRouter();
  const [line, setLine] = useState<LabelData | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function loadLine() {
      try {
        // If QC is specified, try fetching directly from rejections first
        if (isQcQuery) {
          const qcRes = await fetch(`/api/pedidos/rejections/${id}`);
          if (qcRes.ok) {
            const rData = await qcRes.json();
            if (rData.rejection) {
              const rj = rData.rejection;
              setLine({
                id: rj.id,
                boxNumber: rj.boxNumber || '000000',
                uniqueCode: rj.orderLineId ? `${rj.farm?.ruc || '1793023088001'}-${rj.productCode}-${rj.boxNumber}` : undefined,
                quantity: 1,
                boxType: 'EB',
                isCancelled: false,
                isQc: true,
                qcReason: rj.reason,
                qcComment: rj.comment,
                qcPrice: rj.price,
                product: {
                  code: rj.productCode || '—',
                  name: rj.productName || '—'
                },
                farm: {
                  name: rj.farm?.name || '—',
                  ruc: rj.farm?.ruc || '1793023088001'
                },
                order: {
                  po: rj.order?.po || '—',
                  orderNumber: rj.order?.orderNumber || '—',
                  shippingCustomer: rj.order?.shippingCustomer || { businessName: 'US FLORALS' }
                }
              });
              setLoading(false);
              return;
            }
          }
        }

        // If cancelled is specified, try fetching directly from cancelled-labels first
        if (isCancelledQuery) {
          const cancelRes = await fetch(`/api/pedidos/cancelled-labels/${id}`);
          if (cancelRes.ok) {
            const cData = await cancelRes.json();
            if (cData.label) {
              const cl = cData.label;
              setLine({
                id: cl.id,
                boxNumber: cl.boxNumber,
                uniqueCode: cl.uniqueCode,
                quantity: 1,
                boxType: cl.boxType,
                isCancelled: true,
                cancelledAt: cl.cancelledAt,
                reason: cl.reason,
                product: {
                  code: cl.itemCode,
                  name: cl.productName
                },
                farm: {
                  name: cl.farmName || '—',
                  ruc: cl.uniqueCode ? cl.uniqueCode.split('-')[0] : '1793023088001'
                },
                order: {
                  po: cl.po || '—',
                  orderNumber: cl.po || '—',
                  shippingCustomer: { businessName: cl.customerName || 'CLIENTE' }
                }
              });
              setLoading(false);
              return;
            }
          }
        }

        // Try normal line endpoint
        const res = await fetch(`/api/orders/lines/${id}`);
        if (res.ok) {
          const data = await res.json();
          setLine({
            ...data,
            isCancelled: isCancelledQuery || data.status === 'CANCELLED',
            isQc: isQcQuery || Boolean(data.qcRejected),
            qcReason: data.qcReason || null,
            qcComment: data.qcComment || null
          });
        } else {
          // Fallback: check if it's in cancelled labels
          const cancelRes = await fetch(`/api/pedidos/cancelled-labels/${id}`);
          if (cancelRes.ok) {
            const cData = await cancelRes.json();
            if (cData.label) {
              const cl = cData.label;
              setLine({
                id: cl.id,
                boxNumber: cl.boxNumber,
                uniqueCode: cl.uniqueCode,
                quantity: 1,
                boxType: cl.boxType,
                isCancelled: true,
                cancelledAt: cl.cancelledAt,
                reason: cl.reason,
                product: {
                  code: cl.itemCode,
                  name: cl.productName
                },
                farm: {
                  name: cl.farmName || '—',
                  ruc: cl.uniqueCode ? cl.uniqueCode.split('-')[0] : '1793023088001'
                },
                order: {
                  po: cl.po || '—',
                  orderNumber: cl.po || '—',
                  shippingCustomer: { businessName: cl.customerName || 'CLIENTE' }
                }
              });
            }
          }
        }
      } catch (err) {
        console.error('Error fetching order line:', err);
      } finally {
        setLoading(false);
      }
    }
    if (id) loadLine();
  }, [id, isCancelledQuery, isQcQuery]);

  if (loading) return <div style={{ padding: '3rem', textAlign: 'center', fontFamily: 'sans-serif' }}>Cargando etiqueta...</div>;
  if (!line) return <div style={{ padding: '3rem', textAlign: 'center', fontFamily: 'sans-serif' }}>No se encontró la caja o etiqueta solicitada.</div>;

  const clientName = line.order.masterCustomer?.businessName || line.order.shippingCustomer?.businessName || line.order.billingCustomer?.businessName || 'NEW YORK FLOWERS';
  const poNumber = line.order.po || '—';
  const itemCode = line.product.code || '—';
  const productName = line.product.name || '—';
  const boxNumber = line.boxNumber || '000000';
  const farmRuc = line.farm?.ruc || '1793023088001';
  const barcodeValue = line.uniqueCode || `${farmRuc}-${itemCode}-${boxNumber}`;
  const isCancelled = line.isCancelled || false;
  const isQc = line.isQc || false;

  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', flexWrap: 'wrap' }}>
        <button
          onClick={() => router.back()}
          style={{ padding: '0.6rem 1.4rem', borderRadius: '8px', border: '1px solid #ccc', cursor: 'pointer', background: '#fff', fontWeight: 600 }}
        >
          ← Volver
        </button>
        <button
          onClick={() => window.print()}
          style={{ padding: '0.6rem 1.8rem', borderRadius: '8px', border: 'none', background: isCancelled ? '#dc2626' : '#1c5236', color: '#fff', cursor: 'pointer', fontWeight: 700, fontSize: '1rem', boxShadow: '0 4px 12px rgba(0,0,0,0.15)' }}
        >
          🖨️ Imprimir Etiqueta {isCancelled ? '(Cancelada)' : ''}
        </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;
              page-break-after: avoid !important;
              break-after: avoid !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;
            }
          }
          @media screen {
            .label-card {
              width: 100mm;
              min-height: 145mm;
              margin: 0 auto 2rem;
              box-shadow: 0 10px 30px rgba(0,0,0,0.12);
              border: 1px solid #e2e8f0;
              padding: 6mm 7mm;
            }
          }
        `}} />

        {/* Outer label card */}
        <div
          className="label-card"
          style={{
            position: 'relative',
            background: '#ffffff',
            borderRadius: '4px',
            boxSizing: 'border-box',
            textAlign: 'center',
            color: '#000',
            overflow: 'hidden',
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'space-between'
          }}
        >
          {/* Diagonal CANCELADO Watermark Stamp if cancelled */}
          {isCancelled && (
            <div
              style={{
                position: 'absolute',
                top: '52%',
                left: '50%',
                transform: 'translate(-50%, -50%) rotate(-32deg)',
                color: 'rgba(220, 38, 38, 0.42)',
                border: '7px solid rgba(220, 38, 38, 0.55)',
                padding: '0.6rem 1.8rem',
                fontSize: '2.4rem',
                fontWeight: 900,
                textTransform: 'uppercase',
                letterSpacing: '0.12em',
                pointerEvents: 'none',
                borderRadius: '12px',
                whiteSpace: 'nowrap',
                zIndex: 20
              }}
            >
              🚫 CANCELADO 🚫
            </div>
          )}

          {/* Horizontal DEVOLUCIÓN Watermark Stamp if QC Rejected */}
          {isQc && (
            <div
              style={{
                position: 'absolute',
                top: '52%',
                left: '50%',
                transform: 'translate(-50%, -50%)',
                color: 'rgba(185, 28, 28, 0.48)',
                border: '7px solid rgba(185, 28, 28, 0.7)',
                padding: '0.6rem 2.2rem',
                fontSize: '2.5rem',
                fontWeight: 900,
                textTransform: 'uppercase',
                letterSpacing: '0.14em',
                pointerEvents: 'none',
                borderRadius: '12px',
                whiteSpace: 'nowrap',
                zIndex: 20
              }}
            >
              DEVOLUCIÓN
            </div>
          )}

          {/* Cancellation top warning banner */}
          {isCancelled && (
            <div
              style={{
                background: '#dc2626',
                color: '#fff',
                padding: '0.35rem',
                fontWeight: 900,
                fontSize: '0.72rem',
                letterSpacing: '0.08em',
                borderRadius: '3px',
                marginBottom: '0.4rem',
                textTransform: 'uppercase'
              }}
            >
              ⚠️ ETIQUETA CANCELADA - CÓDIGO INHABILITADO ⚠️
            </div>
          )}

          {/* QC Rejection top warning banner */}
          {isQc && (
            <div
              style={{
                background: '#b91c1c',
                color: '#fff',
                padding: '0.4rem',
                fontWeight: 900,
                fontSize: '0.74rem',
                letterSpacing: '0.08em',
                borderRadius: '3px',
                marginBottom: '0.4rem',
                textTransform: 'uppercase'
              }}
            >
              ⚠️ DEVOLUCIÓN POR CONTROL DE CALIDAD ⚠️
            </div>
          )}

          {/* 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: isCancelled || isQc ? '#b91c1c' : '#000', lineHeight: 1.1 }}>
            BOX#{boxNumber} {isCancelled ? '(CANCELADO)' : isQc ? '(DEVOLUCIÓN)' : ''}
          </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', opacity: isCancelled ? 0.65 : 1, 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 {boxNumber}
          </div>

          {isCancelled && line.cancelledAt && (
            <div style={{ marginTop: '0.2rem', fontSize: '0.62rem', color: '#dc2626', fontWeight: 700 }}>
              Cancelada el: {new Date(line.cancelledAt).toLocaleString('es-EC')} {line.reason ? `· ${line.reason}` : ''}
            </div>
          )}

          {isQc && (
            <div style={{ marginTop: '0.3rem', background: '#fef2f2', border: '1.5px solid #f87171', padding: '0.4rem', borderRadius: '4px', textAlign: 'left', fontSize: '0.66rem', color: '#991b1b', lineHeight: 1.3 }}>
              <div><strong>MOTIVO QC:</strong> {line.qcReason || 'Rechazo por Control de Calidad'}</div>
              {line.qcComment && <div><strong>OBSERVACIONES:</strong> {line.qcComment}</div>}
              <div style={{ marginTop: '0.25rem', fontWeight: 900, color: '#b91c1c', fontSize: '0.68rem', textTransform: 'uppercase' }}>
                ⚠️ Notificación a finca: Dispone de 48 horas máximo para retirar la caja de Cuarto Frío antes de su desecho.
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
