'use client';

import React, { useState, useEffect } from 'react';
import * as XLSX from 'xlsx';
import ModalPortal from '@/components/common/ModalPortal';

type Props = {
  awb: string;
  agency?: string;
  onClose: () => void;
};

export default function MasterAwbReportModal({ awb, agency, onClose }: Props) {
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState<any>(null);
  const [error, setError] = useState('');
  const [viewMode, setViewMode] = useState<'FARM' | 'ITEM'>('FARM');

  useEffect(() => {
    const fetchReport = async () => {
      setLoading(true);
      setError('');
      try {
        const res = await fetch(`/api/reports/awb?awb=${encodeURIComponent(awb)}`);
        const json = await res.json();
        if (!res.ok) throw new Error(json.error || 'Error al obtener reporte');
        setData(json);
      } catch (err: any) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };
    if (awb) fetchReport();
  }, [awb]);

  const exportExcel = () => {
    if (!data) return;

    const wb = XLSX.utils.book_new();

    // Sheet 1: Totalizado por Finca
    const farmRows: any[] = [];
    data.farmsSummary.forEach((f: any) => {
      farmRows.push({
        'ITEM': `FINCA: ${f.farmName}`,
        'PRODUCT NAME': '',
        'PACK': '',
        'Stems/Bunch': '',
        'Stems/Box': '',
        'Weight Kg': '',
        'ST': '',
        'EB': '',
        'QB': '',
        'HB': '',
        'TOTAL STEMS': '',
        'TOTAL Kg': ''
      });

      f.rows.forEach((r: any) => {
        farmRows.push({
          'ITEM': r.item,
          'PRODUCT NAME': r.productName,
          'PACK': r.pack,
          'Stems/Bunch': r.stemsPerBunch,
          'Stems/Box': r.stemsPerBox,
          'Weight Kg': r.weightKg,
          'ST': r.st || 0,
          'EB': r.eb || 0,
          'QB': r.qb || 0,
          'HB': r.hb || 0,
          'TOTAL STEMS': r.totalStems,
          'TOTAL Kg': r.totalKg
        });
      });

      farmRows.push({
        'ITEM': `SUBTOTAL ${f.farmName}`,
        'PRODUCT NAME': '',
        'PACK': '',
        'Stems/Bunch': '',
        'Stems/Box': '',
        'Weight Kg': '',
        'ST': f.subtotals.st,
        'EB': f.subtotals.eb,
        'QB': f.subtotals.qb,
        'HB': f.subtotals.hb,
        'TOTAL STEMS': f.subtotals.totalStems,
        'TOTAL Kg': f.subtotals.totalKg
      });
      farmRows.push({}); // Empty row separator
    });

    // Grand total row
    farmRows.push({
      'ITEM': 'GRAN TOTAL',
      'PRODUCT NAME': `TOTAL PIEZAS: ${data.grandTotals.totalPieces}`,
      'PACK': '',
      'Stems/Bunch': '',
      'Stems/Box': '',
      'Weight Kg': '',
      'ST': data.grandTotals.st,
      'EB': data.grandTotals.eb,
      'QB': data.grandTotals.qb,
      'HB': data.grandTotals.hb,
      'TOTAL STEMS': data.grandTotals.totalStems,
      'TOTAL Kg': data.grandTotals.totalRealWeight
    });

    const wsFarms = XLSX.utils.json_to_sheet(farmRows);
    XLSX.utils.book_append_sheet(wb, wsFarms, 'Por Finca');

    // Sheet 2: Totalizado por Ítem
    const itemRows = data.itemsSummary.map((r: any) => ({
      'ITEM': r.item,
      'PRODUCT NAME': r.productName,
      'PACK': r.pack,
      'Stems/Bunch': r.stemsPerBunch,
      'Stems/Box': r.stemsPerBox,
      'Weight Kg': r.weightKg,
      'ST': r.st || 0,
      'EB': r.eb || 0,
      'QB': r.qb || 0,
      'HB': r.hb || 0,
      'TOTAL STEMS': r.totalStems,
      'TOTAL Kg': r.totalKg
    }));

    itemRows.push({
      'ITEM': 'TOTAL GENERAL',
      'PRODUCT NAME': `TOTAL PIEZAS: ${data.grandTotals.totalPieces}`,
      'PACK': '',
      'Stems/Bunch': '',
      'Stems/Box': '',
      'Weight Kg': '',
      'ST': data.grandTotals.st,
      'EB': data.grandTotals.eb,
      'QB': data.grandTotals.qb,
      'HB': data.grandTotals.hb,
      'TOTAL STEMS': data.grandTotals.totalStems,
      'TOTAL Kg': data.grandTotals.totalRealWeight
    });

    const wsItems = XLSX.utils.json_to_sheet(itemRows);
    XLSX.utils.book_append_sheet(wb, wsItems, 'Por Item');

    XLSX.writeFile(wb, `Reporte_Master_AWB_${awb.replace(/\s+/g, '_')}_${new Date().toISOString().split('T')[0]}.xlsx`);
  };

  const handlePrint = () => {
    window.print();
  };

  const tdStyle: React.CSSProperties = {
    padding: '0.45rem 0.6rem',
    borderBottom: '1px solid #e2e8f0',
    fontSize: '0.78rem'
  };
  const thStyle: React.CSSProperties = {
    padding: '0.6rem 0.6rem',
    background: '#1c5236',
    color: '#fff',
    fontWeight: 700,
    fontSize: '0.75rem',
    textTransform: 'uppercase',
    letterSpacing: '0.04em'
  };

  return (
    <ModalPortal>
      <div style={{
        position: 'fixed',
        inset: 0,
        zIndex: 9999,
        background: 'rgba(15, 23, 42, 0.75)',
        backdropFilter: 'blur(4px)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '1rem'
      }}>
        <div className="printable-report" style={{
          background: '#fff',
          borderRadius: '16px',
          width: '1200px',
          maxWidth: '96vw',
          maxHeight: '92vh',
          display: 'flex',
          flexDirection: 'column',
          boxShadow: '0 25px 50px -12px rgba(0,0,0,0.3)',
          overflow: 'hidden'
        }}>
          {/* Header */}
          <div style={{
            padding: '1.25rem 1.75rem',
            borderBottom: '1px solid #e2e8f0',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            flexWrap: 'wrap',
            gap: '1rem',
            background: '#f8fafc'
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
              <img
                src="/logo_usflorals_circle.png"
                alt="US Florals"
                style={{ width: '48px', height: '48px', objectFit: 'contain' }}
              />
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
                  <h2 style={{ margin: 0, fontSize: '1.25rem', fontWeight: 800, color: '#0f172a' }}>
                    Reporte Máster Guía Aérea
                  </h2>
                  <span style={{ fontFamily: 'monospace', fontWeight: 800, fontSize: '0.95rem', background: '#ecfdf5', color: '#059669', padding: '0.2rem 0.6rem', borderRadius: '6px', border: '1px solid #a7f3d0' }}>
                    AWB: {awb}
                  </span>
                  <span style={{ fontWeight: 700, fontSize: '0.78rem', background: '#e0f2fe', color: '#0369a1', padding: '0.2rem 0.5rem', borderRadius: '6px' }}>
                    {data?.agency || agency || 'FEDEX'}
                  </span>
                </div>
                <p style={{ margin: '0.2rem 0 0', fontSize: '0.78rem', color: '#64748b' }}>
                  US FLORALS LLC &bull; Desglose Consolidado de Cajas, Variedades, Tallos y Pesos
                </p>
              </div>
            </div>

            <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
              {/* Toggle view mode */}
              <div style={{ display: 'flex', background: '#e2e8f0', padding: '0.25rem', borderRadius: '8px' }}>
                <button
                  type="button"
                  onClick={() => setViewMode('FARM')}
                  style={{
                    padding: '0.35rem 0.75rem',
                    border: 'none',
                    borderRadius: '6px',
                    fontSize: '0.78rem',
                    fontWeight: 700,
                    cursor: 'pointer',
                    background: viewMode === 'FARM' ? '#1c5236' : 'transparent',
                    color: viewMode === 'FARM' ? '#fff' : '#475569'
                  }}
                >
                  🏢 Por Finca
                </button>
                <button
                  type="button"
                  onClick={() => setViewMode('ITEM')}
                  style={{
                    padding: '0.35rem 0.75rem',
                    border: 'none',
                    borderRadius: '6px',
                    fontSize: '0.78rem',
                    fontWeight: 700,
                    cursor: 'pointer',
                    background: viewMode === 'ITEM' ? '#1c5236' : 'transparent',
                    color: viewMode === 'ITEM' ? '#fff' : '#475569'
                  }}
                >
                  📦 Por Ítem
                </button>
              </div>

              <button
                onClick={exportExcel}
                disabled={!data}
                style={{
                  padding: '0.45rem 0.9rem',
                  borderRadius: '8px',
                  border: '1.5px solid #059669',
                  background: '#ecfdf5',
                  color: '#059669',
                  fontWeight: 700,
                  fontSize: '0.8rem',
                  cursor: 'pointer',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '0.35rem'
                }}
              >
                <span>📥 Excel</span>
              </button>

              <button
                onClick={handlePrint}
                style={{
                  padding: '0.45rem 0.9rem',
                  borderRadius: '8px',
                  border: '1.5px solid #3b82f6',
                  background: '#eff6ff',
                  color: '#1d4ed8',
                  fontWeight: 700,
                  fontSize: '0.8rem',
                  cursor: 'pointer',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '0.35rem'
                }}
              >
                <span>🖨️ Imprimir PDF</span>
              </button>

              <button
                onClick={onClose}
                style={{
                  border: 'none',
                  background: 'none',
                  fontSize: '1.5rem',
                  cursor: 'pointer',
                  color: '#94a3b8',
                  marginLeft: '0.5rem',
                  lineHeight: 1
                }}
              >
                &times;
              </button>
            </div>
          </div>

          {/* Body Content */}
          <div style={{ flex: 1, overflowY: 'auto', padding: '1.25rem 1.75rem' }}>
            {loading ? (
              <div style={{ textAlign: 'center', padding: '4rem', color: '#1c5236' }}>
                <div className="loading-spinner" style={{ margin: '0 auto 12px' }}></div>
                <p style={{ fontWeight: 600, fontSize: '0.9rem' }}>Cargando reporte de AWB...</p>
              </div>
            ) : error ? (
              <div style={{ padding: '1.5rem', background: '#fef2f2', border: '1px solid #fecaca', color: '#b91c1c', borderRadius: '10px', textAlign: 'center' }}>
                ⚠️ {error}
              </div>
            ) : !data || (data.itemsSummary.length === 0 && data.farmsSummary.length === 0) ? (
              <div style={{ textAlign: 'center', padding: '3rem', color: '#64748b' }}>
                No se encontraron cajas registradas asociadas a la guía AWB {awb}.
              </div>
            ) : (
              <div>
                {/* Mode 1: Por Finca */}
                {viewMode === 'FARM' && (
                  <div>
                    {data.farmsSummary.map((f: any, fIdx: number) => (
                      <div key={fIdx} style={{ marginBottom: '1.75rem', border: '1px solid #cbd5e1', borderRadius: '10px', overflow: 'hidden' }}>
                        <div style={{ background: '#f1f5f9', padding: '0.65rem 1rem', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <span style={{ fontSize: '0.9rem', fontWeight: 800, color: '#0f172a' }}>
                            🌻 FINCA: {f.farmName}
                          </span>
                          <span style={{ fontSize: '0.8rem', fontWeight: 700, color: '#059669' }}>
                            {f.subtotals.totalBoxes} cajas &bull; {f.subtotals.totalStems} tallos &bull; {f.subtotals.totalKg} kg
                          </span>
                        </div>

                        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                          <thead>
                            <tr>
                              <th style={{ ...thStyle, textAlign: 'left' }}>ITEM</th>
                              <th style={{ ...thStyle, textAlign: 'left' }}>PRODUCT NAME</th>
                              <th style={{ ...thStyle, textAlign: 'center' }}>PACK</th>
                              <th style={{ ...thStyle, textAlign: 'center' }}>Stems/Bunch</th>
                              <th style={{ ...thStyle, textAlign: 'center' }}>Stems/Box</th>
                              <th style={{ ...thStyle, textAlign: 'center' }}>Weight Kg</th>
                              <th style={{ ...thStyle, textAlign: 'center', background: '#166534' }}>ST</th>
                              <th style={{ ...thStyle, textAlign: 'center', background: '#166534' }}>EB</th>
                              <th style={{ ...thStyle, textAlign: 'center', background: '#166534' }}>QB</th>
                              <th style={{ ...thStyle, textAlign: 'center', background: '#166534' }}>HB</th>
                              <th style={{ ...thStyle, textAlign: 'center' }}>TOTAL STEMS</th>
                              <th style={{ ...thStyle, textAlign: 'right' }}>TOTAL Kg</th>
                            </tr>
                          </thead>
                          <tbody>
                            {f.rows.map((r: any, rIdx: number) => (
                              <tr key={rIdx} style={{ background: rIdx % 2 === 0 ? '#fff' : '#f8fafc' }}>
                                <td style={{ ...tdStyle, fontWeight: 700, fontFamily: 'monospace', color: '#1c5236' }}>{r.item}</td>
                                <td style={{ ...tdStyle, fontWeight: 600 }}>{r.productName}</td>
                                <td style={{ ...tdStyle, textAlign: 'center' }}>{r.pack}</td>
                                <td style={{ ...tdStyle, textAlign: 'center' }}>{r.stemsPerBunch}</td>
                                <td style={{ ...tdStyle, textAlign: 'center' }}>{r.stemsPerBox}</td>
                                <td style={{ ...tdStyle, textAlign: 'center' }}>{r.weightKg}</td>
                                <td style={{ ...tdStyle, textAlign: 'center', fontWeight: r.st ? 700 : 400, color: r.st ? '#166534' : '#94a3b8' }}>{r.st || 0}</td>
                                <td style={{ ...tdStyle, textAlign: 'center', fontWeight: r.eb ? 700 : 400, color: r.eb ? '#166534' : '#94a3b8' }}>{r.eb || 0}</td>
                                <td style={{ ...tdStyle, textAlign: 'center', fontWeight: r.qb ? 700 : 400, color: r.qb ? '#166534' : '#94a3b8' }}>{r.qb || 0}</td>
                                <td style={{ ...tdStyle, textAlign: 'center', fontWeight: r.hb ? 700 : 400, color: r.hb ? '#166534' : '#94a3b8' }}>{r.hb || 0}</td>
                                <td style={{ ...tdStyle, textAlign: 'center', fontWeight: 700, color: '#0f172a' }}>{r.totalStems}</td>
                                <td style={{ ...tdStyle, textAlign: 'right', fontWeight: 800, color: '#059669' }}>{r.totalKg} kg</td>
                              </tr>
                            ))}
                            {/* Subtotal row */}
                            <tr style={{ background: '#ecfdf5', fontWeight: 800, borderTop: '2px solid #a7f3d0' }}>
                              <td colSpan={6} style={{ ...tdStyle, textAlign: 'right', color: '#065f46' }}>
                                SUBTOTAL {f.farmName}:
                              </td>
                              <td style={{ ...tdStyle, textAlign: 'center', color: '#065f46' }}>{f.subtotals.st}</td>
                              <td style={{ ...tdStyle, textAlign: 'center', color: '#065f46' }}>{f.subtotals.eb}</td>
                              <td style={{ ...tdStyle, textAlign: 'center', color: '#065f46' }}>{f.subtotals.qb}</td>
                              <td style={{ ...tdStyle, textAlign: 'center', color: '#065f46' }}>{f.subtotals.hb}</td>
                              <td style={{ ...tdStyle, textAlign: 'center', color: '#065f46' }}>{f.subtotals.totalStems}</td>
                              <td style={{ ...tdStyle, textAlign: 'right', color: '#065f46' }}>{f.subtotals.totalKg} kg</td>
                            </tr>
                          </tbody>
                        </table>
                      </div>
                    ))}
                  </div>
                )}

                {/* Mode 2: Por Ítem */}
                {viewMode === 'ITEM' && (
                  <div style={{ border: '1px solid #cbd5e1', borderRadius: '10px', overflow: 'hidden' }}>
                    <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                      <thead>
                        <tr>
                          <th style={{ ...thStyle, textAlign: 'left' }}>ITEM</th>
                          <th style={{ ...thStyle, textAlign: 'left' }}>PRODUCT NAME</th>
                          <th style={{ ...thStyle, textAlign: 'center' }}>PACK</th>
                          <th style={{ ...thStyle, textAlign: 'center' }}>Stems/Bunch</th>
                          <th style={{ ...thStyle, textAlign: 'center' }}>Stems/Box</th>
                          <th style={{ ...thStyle, textAlign: 'center' }}>Weight Kg</th>
                          <th style={{ ...thStyle, textAlign: 'center', background: '#166534' }}>ST</th>
                          <th style={{ ...thStyle, textAlign: 'center', background: '#166534' }}>EB</th>
                          <th style={{ ...thStyle, textAlign: 'center', background: '#166534' }}>QB</th>
                          <th style={{ ...thStyle, textAlign: 'center', background: '#166534' }}>HB</th>
                          <th style={{ ...thStyle, textAlign: 'center' }}>TOTAL STEMS</th>
                          <th style={{ ...thStyle, textAlign: 'right' }}>TOTAL Kg</th>
                        </tr>
                      </thead>
                      <tbody>
                        {data.itemsSummary.map((r: any, rIdx: number) => (
                          <tr key={rIdx} style={{ background: rIdx % 2 === 0 ? '#fff' : '#f8fafc' }}>
                            <td style={{ ...tdStyle, fontWeight: 700, fontFamily: 'monospace', color: '#1c5236' }}>{r.item}</td>
                            <td style={{ ...tdStyle, fontWeight: 600 }}>{r.productName}</td>
                            <td style={{ ...tdStyle, textAlign: 'center' }}>{r.pack}</td>
                            <td style={{ ...tdStyle, textAlign: 'center' }}>{r.stemsPerBunch}</td>
                            <td style={{ ...tdStyle, textAlign: 'center' }}>{r.stemsPerBox}</td>
                            <td style={{ ...tdStyle, textAlign: 'center' }}>{r.weightKg}</td>
                            <td style={{ ...tdStyle, textAlign: 'center', fontWeight: r.st ? 700 : 400, color: r.st ? '#166534' : '#94a3b8' }}>{r.st || 0}</td>
                            <td style={{ ...tdStyle, textAlign: 'center', fontWeight: r.eb ? 700 : 400, color: r.eb ? '#166534' : '#94a3b8' }}>{r.eb || 0}</td>
                            <td style={{ ...tdStyle, textAlign: 'center', fontWeight: r.qb ? 700 : 400, color: r.qb ? '#166534' : '#94a3b8' }}>{r.qb || 0}</td>
                            <td style={{ ...tdStyle, textAlign: 'center', fontWeight: r.hb ? 700 : 400, color: r.hb ? '#166534' : '#94a3b8' }}>{r.hb || 0}</td>
                            <td style={{ ...tdStyle, textAlign: 'center', fontWeight: 700, color: '#0f172a' }}>{r.totalStems}</td>
                            <td style={{ ...tdStyle, textAlign: 'right', fontWeight: 800, color: '#059669' }}>{r.totalKg} kg</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </div>
            )}
          </div>

          {/* Footer Grand Totals Summary Bar */}
          {data && (
            <div style={{
              background: '#0f172a',
              color: '#fff',
              padding: '1rem 1.75rem',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              flexWrap: 'wrap',
              gap: '1rem'
            }}>
              <div style={{ display: 'flex', gap: '1.5rem', flexWrap: 'wrap', alignItems: 'center' }}>
                <div>
                  <span style={{ fontSize: '0.72rem', color: '#94a3b8', display: 'block', textTransform: 'uppercase' }}>Cajas por Categoría</span>
                  <div style={{ fontSize: '0.85rem', fontWeight: 700, fontFamily: 'monospace' }}>
                    ST: <span style={{ color: '#4ade80' }}>{data.grandTotals.st}</span> &bull;{' '}
                    EB: <span style={{ color: '#4ade80' }}>{data.grandTotals.eb}</span> &bull;{' '}
                    QB: <span style={{ color: '#4ade80' }}>{data.grandTotals.qb}</span> &bull;{' '}
                    HB: <span style={{ color: '#4ade80' }}>{data.grandTotals.hb}</span>
                  </div>
                </div>

                <div style={{ borderLeft: '1px solid #334155', paddingLeft: '1.25rem' }}>
                  <span style={{ fontSize: '0.72rem', color: '#94a3b8', display: 'block', textTransform: 'uppercase' }}>Total Piezas (Cajas)</span>
                  <div style={{ fontSize: '1.1rem', fontWeight: 800, color: '#38bdf8' }}>
                    {data.grandTotals.totalPieces} pcs
                  </div>
                </div>

                <div style={{ borderLeft: '1px solid #334155', paddingLeft: '1.25rem' }}>
                  <span style={{ fontSize: '0.72rem', color: '#94a3b8', display: 'block', textTransform: 'uppercase' }}>Total Tallos</span>
                  <div style={{ fontSize: '1.1rem', fontWeight: 800, color: '#facc15' }}>
                    {data.grandTotals.totalStems}
                  </div>
                </div>

                <div style={{ borderLeft: '1px solid #334155', paddingLeft: '1.25rem' }}>
                  <span style={{ fontSize: '0.72rem', color: '#94a3b8', display: 'block', textTransform: 'uppercase' }}>Peso Real Total</span>
                  <div style={{ fontSize: '1.1rem', fontWeight: 800, color: '#4ade80' }}>
                    {data.grandTotals.totalRealWeight} kg
                  </div>
                </div>

                <div style={{ borderLeft: '1px solid #334155', paddingLeft: '1.25rem' }}>
                  <span style={{ fontSize: '0.72rem', color: '#94a3b8', display: 'block', textTransform: 'uppercase' }}>Peso Dimensional Total</span>
                  <div style={{ fontSize: '1.1rem', fontWeight: 800, color: '#a78bfa' }}>
                    {data.grandTotals.totalDimWeight} kg
                  </div>
                </div>
              </div>

              <button
                type="button"
                onClick={onClose}
                style={{
                  padding: '0.5rem 1.25rem',
                  borderRadius: '8px',
                  background: '#334155',
                  color: '#fff',
                  border: 'none',
                  fontWeight: 700,
                  fontSize: '0.85rem',
                  cursor: 'pointer'
                }}
              >
                Cerrar
              </button>
            </div>
          )}
        </div>
      </div>
    </ModalPortal>
  );
}
