'use client';

import MainLayout from '@/components/layout/MainLayout';
import { useState, useEffect, useMemo } from 'react';
import Link from 'next/link';

type AuditOrder = {
  id: string;
  po: string;
  orderNumber: string;
  customerName: string;
  creationDate: string;
  shipDate: string;
  deliveryDate: string;
  leadTimeDays: number;
  isWeekendDelivery: boolean;
  weekendDayName?: string;
  isLeadTimeUrgent: boolean;
  isLeadTimeWarning: boolean;
  status: string;
  totalBoxes: number;
  auditReasons: string[];
};

type Stats = {
  newOrdersCount: number;
  boxesToConfirm: number;
  weekendOrdersCount: number;
  shortLeadOrdersCount: number;
  productsWithoutRecipe: number;
  auditOrdersCount: number;
  auditOrders: AuditOrder[];
};

export default function DashboardPage() {
  const [stats, setStats] = useState<Stats | null>(null);
  const [loading, setLoading] = useState(true);
  const [auditFilter, setAuditFilter] = useState<'ALL' | 'WEEKEND' | 'SHORT_LEAD'>('ALL');
  const [auditSearch, setAuditSearch] = useState('');

  useEffect(() => {
    fetch('/api/dashboard')
      .then(r => r.json())
      .then(data => {
        setStats(data);
        setLoading(false);
      })
      .catch(err => {
        console.error('Error fetching stats:', err);
        setLoading(false);
      });
  }, []);

  const filteredAuditOrders = useMemo(() => {
    if (!stats || !stats.auditOrders) return [];
    return stats.auditOrders.filter(o => {
      // Tab filter
      if (auditFilter === 'WEEKEND' && !o.isWeekendDelivery) return false;
      if (auditFilter === 'SHORT_LEAD' && !o.isLeadTimeUrgent) return false;

      // Text search
      if (auditSearch.trim()) {
        const term = auditSearch.toLowerCase().trim();
        const matchPo = o.po.toLowerCase().includes(term);
        const matchOrd = o.orderNumber.toLowerCase().includes(term);
        const matchCust = o.customerName.toLowerCase().includes(term);
        const matchDel = o.deliveryDate.toLowerCase().includes(term);
        const matchDay = (o.weekendDayName || '').toLowerCase().includes(term);
        if (!matchPo && !matchOrd && !matchCust && !matchDel && !matchDay) return false;
      }

      return true;
    });
  }, [stats, auditFilter, auditSearch]);

  return (
    <MainLayout>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '1.75rem', flexWrap: 'wrap', gap: '1rem' }}>
        <div>
          <h1 style={{ fontSize: '2rem', fontWeight: 800, color: 'var(--primary-color)' }}>Dashboard</h1>
          <p className="page-subtitle" style={{ margin: 0 }}>Visión general, métricas y auditoría de órdenes de US Floral.</p>
        </div>
      </div>
      
      {loading ? (
        <div style={{ padding: '3rem', textAlign: 'center', color: 'var(--text-secondary)' }}>
          <div className="loading-spinner" style={{ margin: '0 auto 12px' }}></div>
          Cargando métricas y órdenes a auditar...
        </div>
      ) : stats ? (
        <>
          {/* ── 5 TARJETAS MÉTRICAS PRINCIPALES ── */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: '1.25rem' }}>
            
            {/* 1. Órdenes con Status New */}
            <Link href="/orders?status=new" style={{ textDecoration: 'none' }}>
              <div className="glass-panel" style={{
                padding: '1.5rem',
                background: 'rgba(30, 64, 175, 0.04)',
                border: '1px solid rgba(30, 64, 175, 0.18)',
                borderRadius: 'var(--radius-lg)',
                transition: 'var(--transition)',
                cursor: 'pointer',
                height: '100%'
              }}>
                <h3 style={{ color: '#1e40af', fontSize: '0.78rem', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700 }}>
                  Órdenes con Status New
                </h3>
                <p style={{ fontSize: '2.5rem', fontWeight: 800, color: '#1e40af', lineHeight: 1, marginTop: '0.6rem' }}>
                  {stats.newOrdersCount}
                </p>
                <span style={{ fontSize: '0.72rem', color: '#64748b', display: 'block', marginTop: '0.4rem' }}>
                  Pendientes de procesar →
                </span>
              </div>
            </Link>

            {/* 2. Órdenes con Delivery de Sábado y/o Domingo (FedEx Warning) */}
            <Link href="/orders?filter=weekend" style={{ textDecoration: 'none' }}>
              <div className="glass-panel" style={{
                padding: '1.5rem',
                background: stats.weekendOrdersCount > 0 ? '#fef9c3' : 'rgba(234, 179, 8, 0.06)',
                border: stats.weekendOrdersCount > 0 ? '1.5px solid #eab308' : '1px solid rgba(234, 179, 8, 0.2)',
                borderRadius: 'var(--radius-lg)',
                transition: 'var(--transition)',
                cursor: 'pointer',
                height: '100%',
                boxShadow: stats.weekendOrdersCount > 0 ? '0 4px 12px rgba(234, 179, 8, 0.2)' : undefined
              }}>
                <h3 style={{ color: '#854d0e', fontSize: '0.78rem', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <span>Delivery Sábado / Domingo</span>
                  <span style={{ fontSize: '1rem' }}>⚠️</span>
                </h3>
                <p style={{ fontSize: '2.5rem', fontWeight: 800, color: '#a16207', lineHeight: 1, marginTop: '0.6rem' }}>
                  {stats.weekendOrdersCount}
                </p>
                <span style={{ fontSize: '0.72rem', color: '#854d0e', display: 'block', marginTop: '0.4rem', fontWeight: 600 }}>
                  {stats.weekendOrdersCount > 0 ? 'FedEx no entrega en fin de semana →' : 'Sin entregas en fin de semana'}
                </span>
              </div>
            </Link>

            {/* 3. Órdenes Nuevas con Delivery Date <= 4 días */}
            <Link href="/orders?filter=short-lead" style={{ textDecoration: 'none' }}>
              <div className="glass-panel" style={{
                padding: '1.5rem',
                background: 'rgba(217, 119, 6, 0.05)',
                border: '1px solid rgba(217, 119, 6, 0.25)',
                borderRadius: 'var(--radius-lg)',
                transition: 'var(--transition)',
                cursor: 'pointer',
                height: '100%'
              }}>
                <h3 style={{ color: '#b45309', fontSize: '0.78rem', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <span>Delivery Date &le; 4 Días</span>
                  <span style={{ fontSize: '0.95rem' }}>⏳</span>
                </h3>
                <p style={{ fontSize: '2.5rem', fontWeight: 800, color: '#b45309', lineHeight: 1, marginTop: '0.6rem' }}>
                  {stats.shortLeadOrdersCount}
                </p>
                <span style={{ fontSize: '0.72rem', color: '#92400e', display: 'block', marginTop: '0.4rem' }}>
                  Anticipación crítica urgente →
                </span>
              </div>
            </Link>

            {/* 4. Cajas x Confirmar */}
            <div className="glass-panel" style={{
              padding: '1.5rem',
              background: 'rgba(28, 82, 54, 0.04)',
              border: '1px solid rgba(28, 82, 54, 0.2)',
              borderRadius: 'var(--radius-lg)',
              height: '100%'
            }}>
              <h3 style={{ color: 'var(--primary-color)', fontSize: '0.78rem', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700 }}>
                Cajas x Confirmar
              </h3>
              <p style={{ fontSize: '2.5rem', fontWeight: 800, color: 'var(--primary-color)', lineHeight: 1, marginTop: '0.6rem' }}>
                {stats.boxesToConfirm}
              </p>
              <span style={{ fontSize: '0.72rem', color: '#64748b', display: 'block', marginTop: '0.4rem' }}>
                En órdenes pendientes
              </span>
            </div>

            {/* 5. Productos Sin Recetas */}
            <Link href="/products?filter=no-recipe" style={{ textDecoration: 'none' }}>
              <div className="glass-panel" style={{
                padding: '1.5rem',
                background: 'rgba(239, 68, 68, 0.05)',
                border: '1px solid rgba(239, 68, 68, 0.25)',
                borderRadius: 'var(--radius-lg)',
                transition: 'var(--transition)',
                cursor: 'pointer',
                height: '100%'
              }}>
                <h3 style={{ color: '#dc2626', fontSize: '0.78rem', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <span>Productos Sin Recetas</span>
                  <span style={{ fontSize: '0.85rem' }}>⚠️</span>
                </h3>
                <p style={{ fontSize: '2.5rem', fontWeight: 800, color: '#dc2626', lineHeight: 1, marginTop: '0.6rem' }}>
                  {stats.productsWithoutRecipe}
                </p>
                <span style={{ fontSize: '0.72rem', color: '#b91c1c', display: 'block', marginTop: '0.4rem' }}>
                  {stats.productsWithoutRecipe > 0 ? 'Configurar recetas →' : 'Todos con receta activa'}
                </span>
              </div>
            </Link>

          </div>

          {/* ── SECCIÓN PRINCIPAL: TABLA DE ÓRDENES A AUDITAR ── */}
          <div style={{ marginTop: '2.5rem', display: 'grid', gridTemplateColumns: '3fr 1fr', gap: '2rem', alignItems: 'start' }}>
            
            <div className="glass-panel" style={{ padding: '1.75rem', borderRadius: 'var(--radius-lg)' }}>
              
              {/* Encabezado con título, pestañas y enlace a órdenes */}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '1.25rem', flexWrap: 'wrap', gap: '1rem' }}>
                <div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
                    <span style={{ fontSize: '1.4rem' }}>📋</span>
                    <h3 style={{ fontSize: '1.2rem', fontWeight: 800, color: 'var(--primary-color)', margin: 0 }}>
                      Órdenes a Auditar
                    </h3>
                  </div>
                  <p style={{ fontSize: '0.82rem', color: 'var(--text-secondary)', margin: '0.35rem 0 0' }}>
                    Órdenes con problemas de entrega en Sábado/Domingo (FedEx no disponible) o con entrega urgente &le; 4 días.
                  </p>
                </div>

                <Link
                  href="/orders?filter=audit"
                  style={{
                    fontSize: '0.82rem',
                    color: 'var(--secondary-color)',
                    fontWeight: 700,
                    textDecoration: 'none',
                    display: 'inline-flex',
                    alignItems: 'center',
                    gap: '0.3rem'
                  }}
                >
                  Ver todas en Gestión de Órdenes →
                </Link>
              </div>

              {/* Barra de Filtros por Tabs y Búsqueda */}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: '1rem', marginBottom: '1rem', flexWrap: 'wrap' }}>
                <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }}>
                  <button
                    onClick={() => setAuditFilter('ALL')}
                    style={{
                      padding: '0.4rem 0.85rem',
                      borderRadius: '2rem',
                      fontSize: '0.78rem',
                      fontWeight: 700,
                      cursor: 'pointer',
                      border: auditFilter === 'ALL' ? '2px solid var(--primary-color)' : '1px solid #cbd5e1',
                      background: auditFilter === 'ALL' ? 'var(--primary-color)' : 'white',
                      color: auditFilter === 'ALL' ? 'white' : '#475569'
                    }}
                  >
                    Todas a Auditar ({stats.auditOrders.length})
                  </button>
                  <button
                    onClick={() => setAuditFilter('WEEKEND')}
                    style={{
                      padding: '0.4rem 0.85rem',
                      borderRadius: '2rem',
                      fontSize: '0.78rem',
                      fontWeight: 700,
                      cursor: 'pointer',
                      border: auditFilter === 'WEEKEND' ? '2px solid #eab308' : '1px solid #fde047',
                      background: auditFilter === 'WEEKEND' ? '#fef08a' : '#fefce8',
                      color: '#854d0e'
                    }}
                  >
                    ⚠️ Fin de Semana ({stats.weekendOrdersCount})
                  </button>
                  <button
                    onClick={() => setAuditFilter('SHORT_LEAD')}
                    style={{
                      padding: '0.4rem 0.85rem',
                      borderRadius: '2rem',
                      fontSize: '0.78rem',
                      fontWeight: 700,
                      cursor: 'pointer',
                      border: auditFilter === 'SHORT_LEAD' ? '2px solid #f97316' : '1px solid #fed7aa',
                      background: auditFilter === 'SHORT_LEAD' ? '#ffedd5' : '#fffaf0',
                      color: '#9a3412'
                    }}
                  >
                    ⏳ Entrega &le; 4 Días ({stats.shortLeadOrdersCount})
                  </button>
                </div>

                <div style={{ minWidth: '220px', flex: '1', maxWidth: '300px' }}>
                  <input
                    type="text"
                    placeholder="🔍 Filtrar PO, cliente, fecha..."
                    value={auditSearch}
                    onChange={(e) => setAuditSearch(e.target.value)}
                    style={{ padding: '0.4rem 0.75rem', fontSize: '0.8rem', borderRadius: '8px' }}
                  />
                </div>
              </div>

              {/* Tabla de Órdenes a Auditar */}
              {filteredAuditOrders.length === 0 ? (
                <div style={{
                  padding: '3rem 1.5rem',
                  textAlign: 'center',
                  background: '#f8fafc',
                  borderRadius: '10px',
                  border: '1px dashed #cbd5e1',
                  color: '#64748b'
                }}>
                  <span style={{ fontSize: '2rem', display: 'block', marginBottom: '0.5rem' }}>✅</span>
                  <p style={{ margin: 0, fontWeight: 600 }}>No hay órdenes en este criterio de auditoría.</p>
                  <p style={{ margin: '0.25rem 0 0', fontSize: '0.8rem' }}>Todas las entregas cumplen con los días hábiles y la anticipación requerida.</p>
                </div>
              ) : (
                <div style={{ overflowX: 'auto', border: '1px solid #e2e8f0', borderRadius: '10px', maxHeight: '480px', overflowY: 'auto' }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.8rem', textAlign: 'left' }}>
                    <thead style={{ position: 'sticky', top: 0, zIndex: 3, background: '#f8fafc' }}>
                      <tr style={{ borderBottom: '2px solid #cbd5e1', color: '#334155' }}>
                        <th style={{ padding: '0.65rem 0.75rem', fontWeight: 800 }}>PO</th>
                        <th style={{ padding: '0.65rem 0.75rem', fontWeight: 800 }}>Order #</th>
                        <th style={{ padding: '0.65rem 0.75rem', fontWeight: 800 }}>Cliente</th>
                        <th style={{ padding: '0.65rem 0.75rem', fontWeight: 800 }}>Order Date</th>
                        <th style={{ padding: '0.65rem 0.75rem', fontWeight: 800 }}>Shipdate</th>
                        <th style={{ padding: '0.65rem 0.75rem', fontWeight: 800 }}>Delivery Date</th>
                        <th style={{ padding: '0.65rem 0.75rem', fontWeight: 800 }}>Anticipación</th>
                        <th style={{ padding: '0.65rem 0.75rem', fontWeight: 800 }}>Motivo de Auditoría</th>
                        <th style={{ padding: '0.65rem 0.75rem', fontWeight: 800, textAlign: 'center' }}>Acción</th>
                      </tr>
                    </thead>
                    <tbody>
                      {filteredAuditOrders.map((order, idx) => {
                        const isWeekend = order.isWeekendDelivery;
                        const rowBg = isWeekend ? '#fef9c3' : idx % 2 === 0 ? '#ffffff' : '#fafafa';

                        return (
                          <tr
                            key={order.id}
                            style={{
                              borderBottom: '1px solid #f1f5f9',
                              backgroundColor: rowBg,
                              borderLeft: isWeekend ? '4px solid #eab308' : '4px solid #f97316'
                            }}
                          >
                            <td style={{ padding: '0.6rem 0.75rem', fontWeight: 700, color: 'var(--primary-color)' }}>
                              {order.po}
                            </td>
                            <td style={{ padding: '0.6rem 0.75rem', fontWeight: 700, color: '#0f172a' }}>
                              #{order.orderNumber}
                            </td>
                            <td style={{ padding: '0.6rem 0.75rem', color: '#334155', maxWidth: '180px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                              {order.customerName}
                            </td>
                            <td style={{ padding: '0.6rem 0.75rem', fontFamily: 'monospace', color: '#475569' }}>
                              {order.creationDate}
                            </td>
                            <td style={{ padding: '0.6rem 0.75rem', fontFamily: 'monospace', fontWeight: 600, color: '#0f766e' }}>
                              {order.shipDate || '—'}
                            </td>
                            <td style={{ padding: '0.6rem 0.75rem' }}>
                              <span style={{
                                fontFamily: 'monospace',
                                fontWeight: 700,
                                color: isWeekend ? '#854d0e' : '#0f172a',
                                display: 'block'
                              }}>
                                {order.deliveryDate}
                              </span>
                              {isWeekend && (
                                <span style={{
                                  fontSize: '0.68rem',
                                  fontWeight: 800,
                                  color: '#854d0e',
                                  textTransform: 'uppercase',
                                  background: '#fef08a',
                                  padding: '0.1rem 0.35rem',
                                  borderRadius: '4px',
                                  display: 'inline-block',
                                  marginTop: '2px',
                                  border: '1px solid #facc15'
                                }}>
                                  ⚠️ {order.weekendDayName}
                                </span>
                              )}
                            </td>
                            <td style={{ padding: '0.6rem 0.75rem' }}>
                              <span style={{
                                display: 'inline-block',
                                padding: '0.2rem 0.5rem',
                                borderRadius: '4px',
                                fontSize: '0.72rem',
                                fontWeight: 700,
                                background: order.leadTimeDays <= 4 ? '#fee2e2' : '#fef3c7',
                                color: order.leadTimeDays <= 4 ? '#991b1b' : '#92400e',
                                border: order.leadTimeDays <= 4 ? '1px solid #fca5a5' : '1px solid #fde68a'
                              }}>
                                {order.leadTimeDays} día{order.leadTimeDays !== 1 ? 's' : ''}
                              </span>
                            </td>
                            <td style={{ padding: '0.6rem 0.75rem' }}>
                              <div style={{ display: 'flex', flexDirection: 'column', gap: '3px' }}>
                                {isWeekend && (
                                  <span style={{
                                    fontSize: '0.72rem',
                                    color: '#854d0e',
                                    fontWeight: 700,
                                    background: '#fefce8',
                                    padding: '0.2rem 0.4rem',
                                    borderRadius: '4px',
                                    border: '1px solid #fef08a'
                                  }}>
                                    ⚠️ FedEx sin entrega en {order.weekendDayName} — mover fecha
                                  </span>
                                )}
                                {order.isLeadTimeUrgent && (
                                  <span style={{
                                    fontSize: '0.72rem',
                                    color: '#9a3412',
                                    fontWeight: 600,
                                    background: '#fff7ed',
                                    padding: '0.2rem 0.4rem',
                                    borderRadius: '4px',
                                    border: '1px solid #ffedd5'
                                  }}>
                                    ⏳ Entrega urgente &le; 4 días
                                  </span>
                                )}
                              </div>
                            </td>
                            <td style={{ padding: '0.6rem 0.75rem', textAlign: 'center' }}>
                              <Link href={`/orders?po=${encodeURIComponent(order.po)}`} style={{ textDecoration: 'none' }}>
                                <button
                                  className="btn-secondary"
                                  style={{
                                    fontSize: '0.72rem',
                                    padding: '0.25rem 0.6rem',
                                    borderColor: '#3b82f6',
                                    color: '#1d4ed8'
                                  }}
                                >
                                  Revisar
                                </button>
                              </Link>
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              )}
            </div>

            {/* Accesos Rápidos Lateral */}
            <div className="glass-panel" style={{
              padding: '1.5rem',
              display: 'flex',
              flexDirection: 'column',
              gap: '1rem',
              background: 'linear-gradient(135deg, rgba(28,82,54,0.05), rgba(209,107,118,0.05))',
              borderRadius: 'var(--radius-lg)'
            }}>
              <h3 style={{ fontSize: '1.1rem', fontWeight: 700, color: 'var(--primary-color)', marginBottom: '0.5rem' }}>
                Accesos Rápidos
              </h3>
              <Link href="/orders" style={{ textDecoration: 'none' }}>
                <button className="btn-primary" style={{ width: '100%', justifyContent: 'center' }}>
                  📦 Gestión de Órdenes
                </button>
              </Link>
              <Link href="/orders?filter=weekend" style={{ textDecoration: 'none' }}>
                <button className="btn-secondary" style={{
                  width: '100%',
                  justifyContent: 'center',
                  background: '#fefce8',
                  borderColor: '#facc15',
                  color: '#854d0e',
                  fontWeight: 700
                }}>
                  ⚠️ Auditar Fines de Semana ({stats.weekendOrdersCount})
                </button>
              </Link>
              <Link href="/orders?filter=short-lead" style={{ textDecoration: 'none' }}>
                <button className="btn-secondary" style={{
                  width: '100%',
                  justifyContent: 'center',
                  background: '#fff7ed',
                  borderColor: '#fed7aa',
                  color: '#9a3412',
                  fontWeight: 700
                }}>
                  ⏳ Auditar Entregas &le; 4 Días ({stats.shortLeadOrdersCount})
                </button>
              </Link>
              <Link href="/pedidos" style={{ textDecoration: 'none' }}>
                <button className="btn-secondary" style={{ width: '100%', justifyContent: 'center', background: 'white' }}>
                  ✈️ Generación de Pedidos
                </button>
              </Link>
              <Link href="/products" style={{ textDecoration: 'none' }}>
                <button className="btn-secondary" style={{ width: '100%', justifyContent: 'center', background: 'white' }}>
                  🌸 Catálogo de Productos
                </button>
              </Link>
            </div>

          </div>
        </>
      ) : null}
    </MainLayout>
  );
}
