import React, { useState, useEffect } from 'react';
import ModalPortal from '@/components/common/ModalPortal';
import { validateOrderDates, calculateShipDate, formatDateToYYYYMMDD } from '@/lib/dateUtils';

type Props = {
  orderId: string;
  onClose: () => void;
  onSuccess: () => void;
};

export default function FullOrderEditModal({ orderId, onClose, onSuccess }: Props) {
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  
  const [form, setForm] = useState<any>({
    shippingCustomer: {},
    billingCustomer: {},
    lines: []
  });

  useEffect(() => {
    if (!orderId) {
      setError('ID de orden no proporcionado');
      setLoading(false);
      return;
    }

    const fetchOrder = async () => {
      try {
        const res = await fetch(`/api/orders/${orderId}`);
        if (!res.ok) {
          const errData = await res.json().catch(() => ({}));
          throw new Error(errData.error || `Error al cargar la orden (${res.status})`);
        }
        const data = await res.json();
        
        setForm({
          ...data,
          creationDate: data.creationDate ? formatDateToYYYYMMDD(data.creationDate) : '',
          deliveryDate: data.deliveryDate ? formatDateToYYYYMMDD(data.deliveryDate) : '',
          shippingCustomer: data.shippingCustomer || {},
          billingCustomer: data.billingCustomer || {},
          lines: (data.lines || []).map((l: any) => ({
            ...l,
            product: l.product || { code: '', name: '' }
          }))
        });
      } catch (err: any) {
        setError(err.message || 'Error al cargar la orden');
      }
      setLoading(false);
    };
    fetchOrder();
  }, [orderId]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    if (name === 'deliveryDate') {
      const recalculatedShipdt = calculateShipDate(value, form.service || 'FEDEX');
      setForm((prev: any) => ({
        ...prev,
        deliveryDate: value,
        shipdt: recalculatedShipdt || prev.shipdt
      }));
    } else {
      setForm((prev: any) => ({ ...prev, [name]: value }));
    }
  };

  const handleShippingChange = (field: string, value: string) => {
    setForm((prev: any) => ({
      ...prev,
      shippingCustomer: { ...prev.shippingCustomer, [field]: value }
    }));
  };

  const handleBillingChange = (field: string, value: string) => {
    setForm((prev: any) => ({
      ...prev,
      billingCustomer: { ...prev.billingCustomer, [field]: value }
    }));
  };

  const handleLineChange = (index: number, field: string, value: any) => {
    setForm((prev: any) => {
      const nextLines = [...prev.lines];
      if (field === 'code' || field === 'name') {
        nextLines[index] = {
          ...nextLines[index],
          product: { ...nextLines[index].product, [field]: value }
        };
      } else {
        nextLines[index] = {
          ...nextLines[index],
          [field]: value
        };
      }
      return { ...prev, lines: nextLines };
    });
  };

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true); setError('');
    try {
      const res = await fetch(`/api/orders/${orderId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form)
      });
      if (!res.ok) {
        const errData = await res.json();
        throw new Error(errData.error || 'Error al guardar cambios');
      }
      onSuccess();
      onClose();
    } catch (err: any) {
      setError(err.message);
    }
    setSaving(false);
  };

  if (loading) {
    return (
      <ModalPortal>
        <div style={{ position: 'fixed', inset: 0, zIndex: 9999, background: 'rgba(0,0,0,0.45)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div style={{ background: 'white', padding: '2rem', borderRadius: 'var(--radius-lg)' }}>Cargando orden...</div>
        </div>
      </ModalPortal>
    );
  }

  const labelStyle: React.CSSProperties = { display: 'block', fontSize: '0.72rem', fontWeight: 700, marginBottom: '0.25rem', color: 'var(--primary-color)', textTransform: 'uppercase' };

  return (
    <ModalPortal>
      <div style={{ position: 'fixed', inset: 0, zIndex: 9999, background: 'rgba(0,0,0,0.45)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '1rem', overflowY: 'auto' }}>
      <div style={{ background: 'white', borderRadius: 'var(--radius-lg)', padding: '2rem', width: '100%', maxWidth: '850px', maxHeight: '90vh', overflowY: 'auto', boxShadow: '0 25px 50px rgba(0,0,0,0.25)', margin: 'auto' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.25rem', borderBottom: '1px solid #e2e8f0', paddingBottom: '0.75rem' }}>
          <h2 style={{ fontSize: '1.25rem', fontWeight: 700, color: 'var(--primary-color)', margin: 0 }}>Edición Completa de Orden</h2>
          <button onClick={onClose} style={{ color: 'var(--text-secondary)', fontSize: '1.5rem', background: 'none', border: 'none', cursor: 'pointer' }}>×</button>
        </div>

        {error && <div style={{ padding: '0.75rem', background: '#fef2f2', color: '#dc2626', borderRadius: '8px', fontSize: '0.875rem', marginBottom: '1rem' }}>{error}</div>}

        <form onSubmit={handleSave} style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>
          {/* Identificación de Orden */}
          <div style={{ background: '#f8fafc', padding: '1rem', borderRadius: '8px', border: '1px solid #e2e8f0' }}>
            <h3 style={{ fontSize: '0.8rem', fontWeight: 800, color: '#1c5236', textTransform: 'uppercase', marginBottom: '0.75rem' }}>
              📋 Datos de Orden
            </h3>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.75rem', marginBottom: '0.75rem' }}>
              <div>
                <label style={labelStyle}>PO Number</label>
                <input name="po" className="input-field" required value={form.po || ''} onChange={handleChange} />
              </div>
              <div>
                <label style={labelStyle}>CUSTnbr (Order Number)</label>
                <input name="orderNumber" className="input-field" required value={form.orderNumber || ''} onChange={handleChange} />
              </div>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: '0.75rem' }}>
              <div>
                <label style={labelStyle}>Fecha de Orden</label>
                <input type="date" name="creationDate" className="input-field" required value={form.creationDate || ''} onChange={handleChange} />
              </div>
              <div>
                <label style={labelStyle}>Fecha de Entrega</label>
                <input type="date" name="deliveryDate" className="input-field" required value={form.deliveryDate || ''} onChange={handleChange} />
              </div>
              <div>
                <label style={labelStyle}>ShipDt (Vuelo)</label>
                <input name="shipdt" placeholder="YYYY-MM-DD" className="input-field" value={form.shipdt || ''} onChange={handleChange} />
              </div>
              <div>
                <label style={labelStyle}>AWB</label>
                <input name="awb" className="input-field" value={form.awb || ''} onChange={handleChange} />
              </div>
            </div>

            {/* Advertencias de fechas en vivo */}
            {(() => {
              const val = validateOrderDates(form.creationDate, form.deliveryDate);
              if (!val.hasWarning) return null;
              return (
                <div style={{ marginTop: '0.75rem', display: 'flex', flexDirection: 'column', gap: '0.35rem' }}>
                  {val.isWeekendDelivery && (
                    <div style={{
                      padding: '0.45rem 0.75rem',
                      background: '#fef9c3',
                      border: '1px solid #facc15',
                      borderRadius: '6px',
                      fontSize: '0.75rem',
                      color: '#854d0e',
                      fontWeight: 700
                    }}>
                      ⚠️ Advertencia: Fecha de entrega cae en {val.weekendDayName}. FedEx no tiene habilitadas entregas en fines de semana. Por favor mueve la entrega al próximo día hábil.
                    </div>
                  )}
                  {val.isLeadTimeWarning && (
                    <div style={{
                      padding: '0.45rem 0.75rem',
                      background: val.isLeadTimeUrgent ? '#fff7ed' : '#fefce8',
                      border: `1px solid ${val.isLeadTimeUrgent ? '#fed7aa' : '#fde047'}`,
                      borderRadius: '6px',
                      fontSize: '0.75rem',
                      color: val.isLeadTimeUrgent ? '#9a3412' : '#854d0e',
                      fontWeight: 600
                    }}>
                      ⚠️ Advertencia: Solo hay {val.leadTimeDays} día{val.leadTimeDays !== 1 ? 's' : ''} de anticipación entre la orden y la entrega (mínimo requerido: 6 días).
                    </div>
                  )}
                </div>
              );
            })()}
          </div>

          {/* Información del Ship To */}
          <div style={{ background: '#f8fafc', padding: '1rem', borderRadius: '8px', border: '1px solid #e2e8f0' }}>
            <h3 style={{ fontSize: '0.8rem', fontWeight: 800, color: '#1c5236', textTransform: 'uppercase', marginBottom: '0.75rem' }}>
              📍 Información del Destinatario (Ship To)
            </h3>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.75rem', marginBottom: '0.75rem' }}>
              <div>
                <label style={labelStyle}>Nombre / Empresa (Ship To)</label>
                <input className="input-field" value={form.shippingCustomer?.businessName || ''} onChange={e => handleShippingChange('businessName', e.target.value)} />
              </div>
              <div>
                <label style={labelStyle}>Atención / Contacto (Ship To 2)</label>
                <input className="input-field" value={form.shippingCustomer?.contactName || ''} onChange={e => handleShippingChange('contactName', e.target.value)} />
              </div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: '0.75rem', marginBottom: '0.75rem' }}>
              <div>
                <label style={labelStyle}>Dirección (Address)</label>
                <input className="input-field" value={form.shippingCustomer?.address || ''} onChange={e => handleShippingChange('address', e.target.value)} />
              </div>
              <div>
                <label style={labelStyle}>Dirección 2 (Apt/Suite)</label>
                <input className="input-field" value={form.shippingCustomer?.address2 || ''} onChange={e => handleShippingChange('address2', e.target.value)} />
              </div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: '0.75rem' }}>
              <div>
                <label style={labelStyle}>Ciudad</label>
                <input className="input-field" value={form.shippingCustomer?.city || ''} onChange={e => handleShippingChange('city', e.target.value)} />
              </div>
              <div>
                <label style={labelStyle}>Estado</label>
                <input className="input-field" value={form.shippingCustomer?.state || ''} onChange={e => handleShippingChange('state', e.target.value)} />
              </div>
              <div>
                <label style={labelStyle}>Código Postal (Zip)</label>
                <input className="input-field" value={form.shippingCustomer?.zipCode || ''} onChange={e => handleShippingChange('zipCode', e.target.value)} />
              </div>
              <div>
                <label style={labelStyle}>Teléfono</label>
                <input className="input-field" value={form.shippingCustomer?.phone || ''} onChange={e => handleShippingChange('phone', e.target.value)} />
              </div>
            </div>
          </div>

          {/* Información del Sold To */}
          <div style={{ background: '#f8fafc', padding: '1rem', borderRadius: '8px', border: '1px solid #e2e8f0' }}>
            <h3 style={{ fontSize: '0.8rem', fontWeight: 800, color: '#1c5236', textTransform: 'uppercase', marginBottom: '0.75rem' }}>
              🏢 Información de Facturación (Sold To)
            </h3>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '0.75rem' }}>
              <div>
                <label style={labelStyle}>Cliente / Empresa (Sold To)</label>
                <input className="input-field" value={form.billingCustomer?.businessName || ''} onChange={e => handleBillingChange('businessName', e.target.value)} />
              </div>
              <div>
                <label style={labelStyle}>Contacto (Sold To 2)</label>
                <input className="input-field" value={form.billingCustomer?.contactName || ''} onChange={e => handleBillingChange('contactName', e.target.value)} />
              </div>
              <div>
                <label style={labelStyle}>Teléfono Facturación</label>
                <input className="input-field" value={form.billingCustomer?.phone || ''} onChange={e => handleBillingChange('phone', e.target.value)} />
              </div>
            </div>
          </div>

          {/* Líneas / Productos de la Orden */}
          <div style={{ background: '#f8fafc', padding: '1rem', borderRadius: '8px', border: '1px solid #e2e8f0' }}>
            <h3 style={{ fontSize: '0.8rem', fontWeight: 800, color: '#1c5236', textTransform: 'uppercase', marginBottom: '0.75rem' }}>
              📦 Productos / Cajas de la Orden ({form.lines?.length || 0})
            </h3>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem', maxHeight: '250px', overflowY: 'auto' }}>
              {form.lines && form.lines.map((line: any, idx: number) => (
                <div key={line.id || idx} style={{ display: 'grid', gridTemplateColumns: '120px 2fr 70px 150px 80px', gap: '0.5rem', alignItems: 'center', background: '#fff', padding: '0.6rem', borderRadius: '6px', border: '1px solid #e2e8f0' }}>
                  <div>
                    <label style={{ fontSize: '0.68rem', fontWeight: 700, color: '#666' }}>Item Code</label>
                    <input className="input-field" style={{ fontSize: '0.8rem', padding: '0.3rem' }} value={line.product?.code || ''} onChange={e => handleLineChange(idx, 'code', e.target.value)} />
                  </div>
                  <div>
                    <label style={{ fontSize: '0.68rem', fontWeight: 700, color: '#666' }}>Descripción</label>
                    <input className="input-field" style={{ fontSize: '0.8rem', padding: '0.3rem' }} value={line.product?.name || ''} onChange={e => handleLineChange(idx, 'name', e.target.value)} />
                  </div>
                  <div>
                    <label style={{ fontSize: '0.68rem', fontWeight: 700, color: '#666' }}>Qty</label>
                    <input type="number" min="1" className="input-field" style={{ fontSize: '0.8rem', padding: '0.3rem' }} value={line.quantity || 1} onChange={e => handleLineChange(idx, 'quantity', e.target.value)} />
                  </div>
                  <div>
                    <label style={{ fontSize: '0.68rem', fontWeight: 700, color: '#666' }}>Tracking</label>
                    <input className="input-field" style={{ fontSize: '0.8rem', padding: '0.3rem', fontFamily: 'monospace' }} value={line.trackingNumber || ''} onChange={e => handleLineChange(idx, 'trackingNumber', e.target.value)} />
                  </div>
                  <div>
                    <label style={{ fontSize: '0.68rem', fontWeight: 700, color: '#666' }}>Precio ($)</label>
                    <input type="number" step="0.01" className="input-field" style={{ fontSize: '0.8rem', padding: '0.3rem' }} value={line.price || 0} onChange={e => handleLineChange(idx, 'price', e.target.value)} />
                  </div>
                </div>
              ))}
              {(!form.lines || form.lines.length === 0) && (
                <div style={{ fontSize: '0.85rem', color: 'var(--text-secondary)', textAlign: 'center', padding: '1rem' }}>
                  Sin líneas registradas.
                </div>
              )}
            </div>
          </div>

          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '1rem', marginTop: '0.5rem' }}>
            <button type="button" className="btn-secondary" onClick={onClose} disabled={saving}>Cancelar</button>
            <button type="submit" className="btn-primary" disabled={saving}>
              {saving ? 'Guardando...' : 'Guardar Cambios Completos'}
            </button>
          </div>
        </form>
      </div>
    </div>
    </ModalPortal>
  );
}
