'use client';

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

type OrderLine = {
  id: string;
  quantity: number;
  trackingNumber?: string | null;
  airwayBill?: string | null;
  status: string;
  price?: number | null;
  message?: string | null;
  observaciones?: string | null;
  product: { code: string; name: string; stems?: number | null; declaredValue?: number | null };
  farm?: { name: string } | null;
};

type Order = {
  id: string;
  po: string;
  orderNumber: string;
  creationDate: string;
  deliveryDate: string;
  status: string;
  awb?: string | null;
  master?: string | null;
  shipdt?: string | null;
  service?: string | null;
  pkgType?: string | null;
  isReplacement?: boolean;
  billingCustomer?: { businessName: string; city?: string | null; state?: string | null } | null;
  shippingCustomer?: { businessName: string; city?: string | null; state?: string | null } | null;
  lines: OrderLine[];
};

export default function BuscarPOPage() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('ALL');
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [editOrderId, setEditOrderId] = useState<string | null>(null);
  const [editForm, setEditForm] = useState<Partial<Order>>({});
  const [saving, setSaving] = useState(false);
  const [resendsModal, setResendsModal] = useState<Order | null>(null);
  const [resendNote, setResendNote] = useState('');

  const fetchOrders = async () => {
    setLoading(true);
    try { const r = await fetch('/api/orders'); if (r.ok) setOrders(await r.json()); } catch {}
    setLoading(false);
  };
  useEffect(() => { fetchOrders(); }, []);

  const filtered = useMemo(() => {
    const s = search.toLowerCase();
    return orders.filter(o => {
      const matchSearch = !s ||
        o.po.toLowerCase().includes(s) ||
        o.orderNumber.toLowerCase().includes(s) ||
        (o.shippingCustomer?.businessName || '').toLowerCase().includes(s) ||
        (o.billingCustomer?.businessName || '').toLowerCase().includes(s) ||
        (o.awb || '').toLowerCase().includes(s) ||
        o.lines.some(l => (l.trackingNumber || '').toLowerCase().includes(s) || l.product.code.toLowerCase().includes(s));
      const matchStatus = statusFilter === 'ALL' || o.status === statusFilter;
      return matchSearch && matchStatus;
    });
  }, [orders, search, statusFilter]);

  const openEdit = (o: Order) => {
    setEditOrderId(o.id);
    setEditForm({ awb: o.awb || '', master: o.master || '', shipdt: o.shipdt || '', service: o.service || '', pkgType: o.pkgType || '', status: o.status });
  };

  const handleSaveEdit = async () => {
    if (!editOrderId) return;
    setSaving(true);
    const res = await fetch(`/api/orders/${editOrderId}`, {
      method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(editForm)
    });
    if (res.ok) { await fetchOrders(); setEditOrderId(null); }
    setSaving(false);
  };

  const handleResend = async (o: Order) => {
    setSaving(true);
    const res = await fetch('/api/orders', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        ...o,
        po: o.po,
        orderNumber: o.orderNumber + '-R',
        isReplacement: true,
        status: 'PENDING',
        awb: null, master: null, shipdt: null,
        notes: resendNote || `Reenvío de ${o.orderNumber}`,
        lines: o.lines.map(l => ({ productId: l.product.code, quantity: l.quantity, price: l.price, farmId: null })),
      }),
    });
    if (res.ok) { await fetchOrders(); setResendsModal(null); setResendNote(''); }
    setSaving(false);
  };

  const statusColors: Record<string, { bg: string; color: string; label: string }> = {
    PENDING: { bg: '#fef9c3', color: '#854d0e', label: 'Pendiente' },
    PROCESSING: { bg: '#dbeafe', color: '#1e40af', label: 'Procesando' },
    SHIPPED: { bg: '#d1fae5', color: '#065f46', label: 'Enviado' },
    DELIVERED: { bg: '#ede9fe', color: '#5b21b6', label: 'Entregado' },
    CANCELLED: { bg: '#fee2e2', color: '#991b1b', label: 'Cancelado' },
  };

  const badge = (s: string) => {
    const c = statusColors[s] || { bg: '#f3f4f6', color: '#374151', label: s };
    return <span style={{ background: c.bg, color: c.color, padding: '0.2rem 0.65rem', borderRadius: '12px', fontSize: '0.75rem', fontWeight: 600 }}>{c.label}</span>;
  };

  return (
    <MainLayout>
      <div style={{ padding: '2rem', maxWidth: '1200px', margin: '0 auto' }}>
        <div style={{ marginBottom: '1.5rem' }}>
          <h1 style={{ margin: 0, fontSize: '1.6rem', fontWeight: 700, color: '#1a1a2e' }}>🔍 Buscar / Gestionar Órdenes</h1>
          <p style={{ margin: '0.25rem 0 0', color: '#666', fontSize: '0.9rem' }}>Busca, edita y gestiona órdenes por PO, número, cliente o tracking</p>
        </div>

        {/* Filters */}
        <div style={{ display: 'flex', gap: '1rem', marginBottom: '1.25rem', flexWrap: 'wrap' }}>
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="🔍 Buscar por PO, orden, cliente, AWB, tracking, producto..."
            style={{ flex: '1 1 300px', padding: '0.65rem 1rem', borderRadius: '8px', border: '1px solid #ddd', fontSize: '0.95rem' }} />
          <select value={statusFilter} onChange={e => setStatusFilter(e.target.value)}
            style={{ padding: '0.65rem 1rem', borderRadius: '8px', border: '1px solid #ddd', fontSize: '0.9rem' }}>
            <option value="ALL">Todos los estados</option>
            <option value="PENDING">Pendiente</option>
            <option value="PROCESSING">Procesando</option>
            <option value="SHIPPED">Enviado</option>
            <option value="DELIVERED">Entregado</option>
            <option value="CANCELLED">Cancelado</option>
          </select>
        </div>

        <p style={{ color: '#999', fontSize: '0.85rem', marginBottom: '1rem' }}>{filtered.length} órdenes</p>

        {loading ? <div style={{ textAlign: 'center', padding: '3rem', color: '#999' }}>Cargando...</div> :
          filtered.map(o => (
            <div key={o.id} style={{ background: '#fff', borderRadius: '12px', boxShadow: '0 2px 8px rgba(0,0,0,0.07)', marginBottom: '0.85rem', overflow: 'hidden', border: o.isReplacement ? '2px solid #fbbf24' : 'none' }}>
              {/* Order header */}
              <div style={{ padding: '0.9rem 1.25rem', display: 'flex', alignItems: 'center', gap: '1rem', flexWrap: 'wrap', borderBottom: expandedId === o.id ? '1px solid #f0f0f0' : 'none' }}>
                <div style={{ flex: '1 1 200px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                    <span style={{ fontWeight: 700, color: '#667eea', fontSize: '0.95rem' }}>PO: {o.po}</span>
                    {o.isReplacement && <span style={{ background: '#fef3c7', color: '#92400e', fontSize: '0.7rem', padding: '0.15rem 0.5rem', borderRadius: '10px', fontWeight: 600 }}>REENVÍO</span>}
                  </div>
                  <div style={{ fontSize: '0.8rem', color: '#999' }}>#{o.orderNumber} · {o.shippingCustomer?.businessName || o.billingCustomer?.businessName || '—'}</div>
                </div>
                <div style={{ fontSize: '0.82rem', color: '#555', flex: '1 1 120px' }}>
                  <div>Entrega: <strong>{new Date(o.deliveryDate).toLocaleDateString()}</strong></div>
                  {o.awb && <div>AWB: <strong>{o.awb}</strong></div>}
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                  {badge(o.status)}
                  <span style={{ color: '#999', fontSize: '0.82rem' }}>{o.lines.length} líneas</span>
                </div>
                <div style={{ display: 'flex', gap: '0.5rem' }}>
                  <button onClick={() => setExpandedId(expandedId === o.id ? null : o.id)}
                    style={{ padding: '0.4rem 0.9rem', borderRadius: '6px', border: '1px solid #ddd', background: '#f9fafb', cursor: 'pointer', fontSize: '0.82rem', color: '#555' }}>
                    {expandedId === o.id ? '▲ Ocultar' : '▼ Ver líneas'}
                  </button>
                  <button onClick={() => openEdit(o)}
                    style={{ padding: '0.4rem 0.9rem', borderRadius: '6px', border: 'none', background: '#dbeafe', color: '#1e40af', cursor: 'pointer', fontSize: '0.82rem', fontWeight: 600 }}>
                    ✏️ Editar
                  </button>
                  <button onClick={() => { setResendsModal(o); setResendNote(''); }}
                    style={{ padding: '0.4rem 0.9rem', borderRadius: '6px', border: 'none', background: '#fef3c7', color: '#92400e', cursor: 'pointer', fontSize: '0.82rem', fontWeight: 600 }}>
                    🔄 Reenviar
                  </button>
                </div>
              </div>

              {/* Inline edit row */}
              {editOrderId === o.id && (
                <div style={{ padding: '1rem 1.25rem', background: '#f0f4ff', borderBottom: '1px solid #e0e7ff', display: 'flex', flexWrap: 'wrap', gap: '0.75rem', alignItems: 'flex-end' }}>
                  {[['awb','AWB'],['master','Master'],['shipdt','Ship Date'],['service','Servicio'],['pkgType','Pkg Type']].map(([field, label]) => (
                    <div key={field}>
                      <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 600, marginBottom: '0.3rem', color: '#555' }}>{label}</label>
                      <input value={(editForm as any)[field] || ''} onChange={e => setEditForm(f => ({ ...f, [field]: e.target.value }))}
                        style={{ padding: '0.4rem 0.6rem', border: '1px solid #c7d2fe', borderRadius: '6px', fontSize: '0.85rem', width: '130px' }} />
                    </div>
                  ))}
                  <div>
                    <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 600, marginBottom: '0.3rem', color: '#555' }}>Estado</label>
                    <select value={editForm.status || 'PENDING'} onChange={e => setEditForm(f => ({ ...f, status: e.target.value }))}
                      style={{ padding: '0.4rem 0.6rem', border: '1px solid #c7d2fe', borderRadius: '6px', fontSize: '0.85rem' }}>
                      {Object.keys(statusColors).map(s => <option key={s} value={s}>{statusColors[s].label}</option>)}
                    </select>
                  </div>
                  <button onClick={handleSaveEdit} disabled={saving}
                    style={{ padding: '0.5rem 1.2rem', borderRadius: '8px', border: 'none', background: '#667eea', color: '#fff', cursor: 'pointer', fontWeight: 600, fontSize: '0.85rem' }}>
                    {saving ? '...' : '💾 Guardar'}
                  </button>
                  <button onClick={() => setEditOrderId(null)}
                    style={{ padding: '0.5rem 0.9rem', borderRadius: '8px', border: '1px solid #ddd', background: '#fff', cursor: 'pointer', fontSize: '0.85rem' }}>
                    Cancelar
                  </button>
                </div>
              )}

              {/* Lines detail */}
              {expandedId === o.id && (
                <div style={{ padding: '0 0 0.5rem' }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.82rem' }}>
                    <thead>
                      <tr style={{ background: '#f8f9fa', color: '#555' }}>
                        <th style={{ padding: '0.5rem 1.25rem', textAlign: 'left', fontWeight: 600 }}>Producto</th>
                        <th style={{ padding: '0.5rem 0.8rem', textAlign: 'center' }}>Cant.</th>
                        <th style={{ padding: '0.5rem 0.8rem', textAlign: 'left' }}>Finca</th>
                        <th style={{ padding: '0.5rem 0.8rem', textAlign: 'left' }}>Tracking</th>
                        <th style={{ padding: '0.5rem 0.8rem', textAlign: 'left' }}>AWB</th>
                        <th style={{ padding: '0.5rem 0.8rem', textAlign: 'center' }}>Estado</th>
                      </tr>
                    </thead>
                    <tbody>
                      {o.lines.map(l => (
                        <tr key={l.id} style={{ borderTop: '1px solid #f0f0f0' }}>
                          <td style={{ padding: '0.5rem 1.25rem', fontWeight: 600, color: '#667eea' }}>{l.product.code}</td>
                          <td style={{ padding: '0.5rem 0.8rem', textAlign: 'center' }}>{l.quantity}</td>
                          <td style={{ padding: '0.5rem 0.8rem', color: '#666' }}>{l.farm?.name || '—'}</td>
                          <td style={{ padding: '0.5rem 0.8rem', fontFamily: 'monospace', color: l.trackingNumber ? '#059669' : '#999' }}>{l.trackingNumber || '—'}</td>
                          <td style={{ padding: '0.5rem 0.8rem', fontFamily: 'monospace', color: '#666' }}>{l.airwayBill || '—'}</td>
                          <td style={{ padding: '0.5rem 0.8rem', textAlign: 'center' }}>{badge(l.status)}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          ))}
      </div>

      {/* Resend Modal */}
      {resendsModal && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000 }}>
          <div style={{ background: '#fff', borderRadius: '16px', padding: '2rem', width: '480px', maxWidth: '95vw' }}>
            <h2 style={{ margin: '0 0 0.5rem', fontSize: '1.2rem' }}>🔄 Reenviar Orden</h2>
            <p style={{ color: '#666', marginBottom: '1.25rem', fontSize: '0.9rem' }}>
              Se creará una copia de <strong>{resendsModal.orderNumber}</strong> marcada como reenvío, con estado Pendiente y sin AWB.
            </p>
            <div style={{ marginBottom: '1rem' }}>
              <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 600, marginBottom: '0.4rem' }}>Nota de reenvío (opcional)</label>
              <input value={resendNote} onChange={e => setResendNote(e.target.value)} placeholder="Motivo del reenvío..."
                style={{ width: '100%', padding: '0.6rem 0.8rem', border: '1px solid #ddd', borderRadius: '8px', boxSizing: 'border-box' }} />
            </div>
            <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end' }}>
              <button onClick={() => setResendsModal(null)} style={{ padding: '0.6rem 1.4rem', borderRadius: '8px', border: '1px solid #ddd', background: '#fff', cursor: 'pointer' }}>Cancelar</button>
              <button onClick={() => handleResend(resendsModal)} disabled={saving}
                style={{ padding: '0.6rem 1.4rem', borderRadius: '8px', border: 'none', background: 'linear-gradient(135deg, #f59e0b, #d97706)', color: '#fff', cursor: 'pointer', fontWeight: 600 }}>
                {saving ? 'Creando...' : '🔄 Confirmar Reenvío'}
              </button>
            </div>
          </div>
        </div>
      )}
    </MainLayout>
  );
}
