'use client';

import MainLayout from '@/components/layout/MainLayout';
import { useState, useEffect } from 'react';

type ReportData = {
  totalOrders: number;
  totalRevenue: number;
  totalBoxes: number;
  topCustomers: { name: string; total: number; boxes: number }[];
  topFarms: { name: string; total: number; boxes: number }[];
  topProducts: { name: string; total: number; boxes: number }[];
  chartData: { date: string; count: number }[];
};

export default function ReportsPage() {
  const [data, setData] = useState<ReportData | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('/api/reports')
      .then(r => r.json())
      .then(d => {
        setData(d);
        setLoading(false);
      })
      .catch(e => {
        console.error(e);
        setLoading(false);
      });
  }, []);

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

  return (
    <MainLayout>
      <div className="page-header" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <h1 className="page-title">Reportes Avanzados</h1>
          <p className="page-description" style={{ color: 'var(--text-secondary)' }}>
            Métricas clave, clientes y consolidado de productos.
          </p>
        </div>
        <button 
          onClick={handlePrint}
          className="btn-primary" 
          style={{ padding: '0.6rem 1.2rem', display: 'flex', gap: '8px', alignItems: 'center' }}
        >
          <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z" /></svg>
          Exportar PDF / Imprimir
        </button>
      </div>

      {loading ? (
        <div style={{ padding: '40px', textAlign: 'center', color: 'var(--text-secondary)' }}>
          <div className="loading-spinner" style={{ margin: '0 auto 16px' }}></div>
          Cargando reportes...
        </div>
      ) : data ? (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '1.5rem', paddingBottom: '2rem' }}>
          
          {/* Summary Cards */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: '1rem' }}>
            <div className="glass-panel" style={{ padding: '1.5rem' }}>
              <p style={{ fontSize: '0.875rem', color: 'var(--text-secondary)', marginBottom: '0.5rem', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>Ingresos Totales</p>
              <h2 style={{ fontSize: '2rem', fontWeight: 700, color: 'var(--primary-color)' }}>
                ${data.totalRevenue.toLocaleString('en-US', { minimumFractionDigits: 2 })}
              </h2>
            </div>
            <div className="glass-panel" style={{ padding: '1.5rem' }}>
              <p style={{ fontSize: '0.875rem', color: 'var(--text-secondary)', marginBottom: '0.5rem', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>Órdenes Procesadas</p>
              <h2 style={{ fontSize: '2rem', fontWeight: 700, color: 'var(--primary-color)' }}>
                {data.totalOrders}
              </h2>
            </div>
            <div className="glass-panel" style={{ padding: '1.5rem' }}>
              <p style={{ fontSize: '0.875rem', color: 'var(--text-secondary)', marginBottom: '0.5rem', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>Total de Cajas</p>
              <h2 style={{ fontSize: '2rem', fontWeight: 700, color: 'var(--primary-color)' }}>
                {data.totalBoxes}
              </h2>
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(400px, 1fr))', gap: '1.5rem' }}>
            
            {/* Top Customers */}
            <div className="glass-panel table-container" style={{ padding: '1.5rem' }}>
              <h3 style={{ fontSize: '1.1rem', marginBottom: '1.5rem', color: 'var(--text-primary)', display: 'flex', alignItems: 'center', gap: '8px' }}>
                <svg width="20" height="20" fill="none" stroke="var(--primary-color)" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" /></svg>
                Top Clientes (Ingresos)
              </h3>
              <table>
                <thead>
                  <tr>
                    <th>Cliente</th>
                    <th>Cajas</th>
                    <th style={{ textAlign: 'right' }}>Ingresos</th>
                  </tr>
                </thead>
                <tbody>
                  {data.topCustomers.map((c, i) => (
                    <tr key={i}>
                      <td>{c.name}</td>
                      <td>{c.boxes}</td>
                      <td style={{ textAlign: 'right', fontWeight: 600, color: 'var(--primary-color)' }}>
                        ${c.total.toLocaleString('en-US', { minimumFractionDigits: 2 })}
                      </td>
                    </tr>
                  ))}
                  {data.topCustomers.length === 0 && (
                    <tr><td colSpan={3} style={{ padding: '1rem 0', textAlign: 'center', color: 'var(--text-secondary)' }}>No hay datos suficientes</td></tr>
                  )}
                </tbody>
              </table>
            </div>

            {/* Top Products */}
            <div className="glass-panel table-container" style={{ padding: '1.5rem' }}>
              <h3 style={{ fontSize: '1.1rem', marginBottom: '1.5rem', color: 'var(--text-primary)', display: 'flex', alignItems: 'center', gap: '8px' }}>
                <svg width="20" height="20" fill="none" stroke="var(--primary-color)" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8m-9 4h4" /></svg>
                Top Productos (Vendidos)
              </h3>
              <table>
                <thead>
                  <tr>
                    <th>Producto</th>
                    <th>Cajas</th>
                    <th style={{ textAlign: 'right' }}>Ingresos</th>
                  </tr>
                </thead>
                <tbody>
                  {data.topProducts.map((p, i) => (
                    <tr key={i}>
                      <td>{p.name}</td>
                      <td>{p.boxes}</td>
                      <td style={{ textAlign: 'right', fontWeight: 600, color: 'var(--primary-color)' }}>
                        ${p.total.toLocaleString('en-US', { minimumFractionDigits: 2 })}
                      </td>
                    </tr>
                  ))}
                  {data.topProducts.length === 0 && (
                    <tr><td colSpan={3} style={{ padding: '1rem 0', textAlign: 'center', color: 'var(--text-secondary)' }}>No hay datos suficientes</td></tr>
                  )}
                </tbody>
              </table>
            </div>

            {/* Top Farms */}
            <div className="glass-panel table-container" style={{ padding: '1.5rem' }}>
              <h3 style={{ fontSize: '1.1rem', marginBottom: '1.5rem', color: 'var(--text-primary)', display: 'flex', alignItems: 'center', gap: '8px' }}>
                <svg width="20" height="20" fill="none" stroke="var(--primary-color)" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3.055 11H5a2 2 0 012 2v1a2 2 0 002 2 2 2 0 012 2v2.945M8 3.935V5.5A2.5 2.5 0 0010.5 8h.5a2 2 0 012 2 2 2 0 104 0 2 2 0 012-2h1.064M15 20.488V18a2 2 0 012-2h3.064" /></svg>
                Top Fincas (Cajas Asignadas)
              </h3>
              <table>
                <thead>
                  <tr>
                    <th>Finca</th>
                    <th>Cajas</th>
                    <th style={{ textAlign: 'right' }}>Monto Aprox</th>
                  </tr>
                </thead>
                <tbody>
                  {data.topFarms.map((f, i) => (
                    <tr key={i}>
                      <td>{f.name}</td>
                      <td>{f.boxes}</td>
                      <td style={{ textAlign: 'right', fontWeight: 600, color: 'var(--primary-color)' }}>
                        ${f.total.toLocaleString('en-US', { minimumFractionDigits: 2 })}
                      </td>
                    </tr>
                  ))}
                  {data.topFarms.length === 0 && (
                    <tr><td colSpan={3} style={{ padding: '1rem 0', textAlign: 'center', color: 'var(--text-secondary)' }}>No hay datos suficientes</td></tr>
                  )}
                </tbody>
              </table>
            </div>

            {/* Simple Volume Chart */}
            <div className="glass-panel" style={{ padding: '1.5rem', display: 'flex', flexDirection: 'column' }}>
              <h3 style={{ fontSize: '1.1rem', marginBottom: '1.5rem', color: 'var(--text-primary)', display: 'flex', alignItems: 'center', gap: '8px' }}>
                <svg width="20" height="20" fill="none" stroke="var(--primary-color)" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 12l3-3 3 3 4-4M8 21l4-4 4 4M3 4h18M4 4h16v12a1 1 0 01-1 1H5a1 1 0 01-1-1V4z" /></svg>
                Órdenes por Día
              </h3>
              
              <div style={{ flex: 1, display: 'flex', alignItems: 'flex-end', gap: '8px', minHeight: '150px', marginTop: '1rem', borderBottom: '1px solid var(--border-color)', paddingBottom: '10px' }}>
                {data.chartData.map((d, i) => {
                  const maxCount = Math.max(...data.chartData.map(cd => cd.count), 1);
                  const heightPercent = (d.count / maxCount) * 100;
                  return (
                    <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '8px', position: 'relative' }}>
                      <div style={{ 
                        width: '100%', 
                        height: `${heightPercent}%`, 
                        minHeight: '4px',
                        background: 'linear-gradient(180deg, var(--primary-color) 0%, rgba(209,107,118,0.2) 100%)',
                        borderRadius: '4px 4px 0 0',
                        transition: 'height 0.5s ease'
                      }} title={`${d.count} órdenes el ${d.date}`} />
                      <span style={{ fontSize: '0.7rem', color: 'var(--text-secondary)', transform: 'rotate(-45deg)', transformOrigin: 'top left', marginTop: '4px', whiteSpace: 'nowrap' }}>
                        {d.date.slice(5)}
                      </span>
                    </div>
                  );
                })}
                {data.chartData.length === 0 && (
                  <div style={{ width: '100%', textAlign: 'center', color: 'var(--text-secondary)', paddingBottom: '20px' }}>No hay órdenes recientes</div>
                )}
              </div>
            </div>

          </div>
        </div>
      ) : null}
      
      {/* Print styles */}
      <style dangerouslySetInnerHTML={{__html: `
        @media print {
          body { background: white !important; color: black !important; }
          .sidebar, button, .page-description { display: none !important; }
          .glass-panel { background: white !important; border: 1px solid #eee !important; box-shadow: none !important; color: black !important; break-inside: avoid; margin-bottom: 20px; }
          h1, h2, h3, p, td, th { color: black !important; }
          tr { border-bottom: 1px solid #ccc !important; }
          .main-content { padding: 0 !important; margin: 0 !important; }
        }
      `}} />
    </MainLayout>
  );
}
