import { useState } from 'react';
import { shire } from '@/api/shireClient';
import { toast } from 'sonner';

const cardStyle = {
  background: '#1a1a2e',
  border: '1px solid rgba(107,47,179,0.4)',
  boxShadow: '0 0 20px rgba(107,47,179,0.15)',
};

function SkeletonCard() {
  return (
    <div className="rounded-xl p-4 animate-pulse" style={{ background: '#1a1a2e', border: '1px solid rgba(107,47,179,0.15)' }}>
      <div className="h-3 w-1/3 rounded mb-3" style={{ background: 'rgba(107,47,179,0.2)' }} />
      <div className="h-7 w-1/4 rounded mb-3" style={{ background: 'rgba(107,47,179,0.15)' }} />
      <div className="h-8 w-20 rounded" style={{ background: 'rgba(107,47,179,0.1)' }} />
    </div>
  );
}

function ServiceCard({ service, selected, onSelect, signatureRequested }) {
  const isExpress = service.type === 'Express Post';
  const accentColor = isExpress ? '#f59e0b' : '#3b82f6';
  const hasSignature = service.options?.some(o =>
    typeof o === 'string' ? o.includes('Signature') : o?.name?.includes('Signature')
  );

  return (
    <div
      className="rounded-xl p-4 cursor-pointer transition-all"
      style={{
        background: '#1a1a2e',
        border: selected ? '2px solid #6b2fb3' : '1px solid rgba(107,47,179,0.25)',
        boxShadow: selected ? '0 0 20px rgba(107,47,179,0.4)' : 'none',
        borderLeft: selected ? undefined : `3px solid ${accentColor}`,
      }}
      onClick={onSelect}
    >
      <div className="flex items-start justify-between gap-3">
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 flex-wrap">
            <p className="text-sm font-semibold text-white truncate">{service.name}</p>
            {signatureRequested && hasSignature && (
              <span className="text-xs px-1.5 py-0.5 rounded font-medium"
                style={{ background: 'rgba(124,58,237,0.2)', color: '#a78bfa' }}>
                ✍️ Sig
              </span>
            )}
          </div>
          <p className="text-xs mt-0.5" style={{ color: 'rgba(200,180,255,0.4)' }}>{service.code}</p>
        </div>
        <p className="text-xl font-black text-white whitespace-nowrap">${(service.price || 0).toFixed(2)}</p>
      </div>
      <button
        className="mt-3 px-4 py-1.5 rounded-lg text-xs font-bold transition-all"
        style={selected
          ? { background: '#7c3aed', color: 'white' }
          : { border: '1px solid rgba(107,47,179,0.4)', color: '#c084fc', background: 'transparent' }}
        onClick={e => { e.stopPropagation(); onSelect(); }}
      >
        {selected ? '✅ Selected' : 'Select'}
      </button>
    </div>
  );
}

function SaveToOrderModal({ service, onClose }) {
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedOrderId, setSelectedOrderId] = useState('');
  const [saving, setSaving] = useState(false);

  useState(() => {
    shire.entities.Order.list('-order_date', 50).then(data => {
      setOrders(data);
      setLoading(false);
    });
  }, []);

  const handleSave = async () => {
    if (!selectedOrderId) return;
    setSaving(true);
    const order = orders.find(o => o.id === selectedOrderId);
    await shire.entities.Order.update(selectedOrderId, {
      shipping_cost: service.price,
      notes: `AusPost ${service.name} - selected via Shipping Calculator`,
    });
    setSaving(false);
    toast.success(`✅ Shipping saved to Order #${order?.order_number}`);
    onClose();
  };

  const overlayStyle = { background: 'rgba(0,0,0,0.75)', backdropFilter: 'blur(4px)' };
  const modalStyle = { background: '#1a1a2e', border: '1px solid rgba(107,47,179,0.5)', boxShadow: '0 0 60px rgba(107,47,179,0.3)' };
  const selStyle = { background: '#0d0d1a', border: '1px solid rgba(107,47,179,0.3)', color: 'white' };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4" style={overlayStyle}>
      <div className="w-full max-w-md rounded-2xl overflow-hidden" style={modalStyle}>
        <div className="flex items-center justify-between px-5 py-4" style={{ borderBottom: '1px solid rgba(107,47,179,0.2)' }}>
          <h2 className="font-bold text-white">💾 Save to Order</h2>
          <button onClick={onClose} className="text-white/40 hover:text-white text-lg">✕</button>
        </div>
        <div className="p-5 space-y-4">
          <div className="rounded-xl p-3 text-center" style={{ background: 'rgba(124,58,237,0.1)', border: '1px solid rgba(124,58,237,0.3)' }}>
            <p className="text-xs mb-0.5" style={{ color: 'rgba(200,180,255,0.6)' }}>{service.name}</p>
            <p className="text-2xl font-black text-white">${service.price.toFixed(2)}</p>
          </div>
          <div>
            <label className="block text-xs font-semibold mb-1.5" style={{ color: 'rgba(200,180,255,0.7)' }}>Select Order</label>
            {loading ? (
              <div className="flex justify-center py-3">
                <div className="w-5 h-5 border-2 border-purple-400/30 border-t-purple-400 rounded-full animate-spin" />
              </div>
            ) : (
              <select value={selectedOrderId} onChange={e => setSelectedOrderId(e.target.value)}
                className="w-full px-3 py-2.5 text-sm rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
                style={selStyle}>
                <option value="">Select an order…</option>
                {orders.map(o => (
                  <option key={o.id} value={o.id}>
                    {o.order_number} — {o.customer_name}{o.product_title ? ` | ${o.product_title}` : ''}
                  </option>
                ))}
              </select>
            )}
          </div>
          <div className="flex gap-3">
            <button onClick={onClose}
              className="flex-1 py-2.5 rounded-xl text-sm font-semibold border transition-all hover:bg-white/5"
              style={{ color: 'rgba(200,180,255,0.7)', borderColor: 'rgba(107,47,179,0.3)' }}>
              Cancel
            </button>
            <button onClick={handleSave} disabled={!selectedOrderId || saving}
              className="flex-1 py-2.5 rounded-xl text-white text-sm font-bold flex items-center justify-center gap-2 transition-all disabled:opacity-40"
              style={{ background: 'linear-gradient(135deg, #7c3aed, #6366f1)' }}>
              {saving ? <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : '✅ Confirm'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

export default function ShippingRatesPanel({ rates, loading, error, selectedService, setSelectedService, signatureRequested }) {
  const [showSaveModal, setShowSaveModal] = useState(false);

  const expressServices = rates?.services?.filter(s => s.type === 'Express Post') || [];
  const parcelServices = rates?.services?.filter(s => s.type !== 'Express Post') || [];

  const ServiceGroup = ({ title, accent, services }) => {
    if (services.length === 0) return null;
    return (
      <div className="space-y-2">
        <div className="flex items-center gap-2">
          <div className="w-2 h-2 rounded-full" style={{ background: accent }} />
          <p className="text-xs font-bold uppercase tracking-widest" style={{ color: accent }}>{title}</p>
        </div>
        {services.map(service => (
          <ServiceCard
            key={service.code}
            service={service}
            selected={selectedService?.code === service.code}
            onSelect={() => setSelectedService(selectedService?.code === service.code ? null : service)}
            signatureRequested={signatureRequested}
          />
        ))}
      </div>
    );
  };

  return (
    <div className="rounded-2xl p-5 space-y-5 xl:sticky xl:top-4 xl:max-h-[calc(100vh-6rem)] xl:overflow-y-auto" style={cardStyle}>
      <div className="flex items-center gap-2">
        <div className="w-1 h-5 rounded-full" style={{ background: 'linear-gradient(to bottom, #7c3aed, #f97316)' }} />
        <span className="text-sm font-bold text-white">📬 Shipping Rates</span>
      </div>

      {/* Placeholder */}
      {!loading && !error && !rates && (
        <div className="py-12 text-center">
          <p className="text-4xl mb-3">📮</p>
          <p className="text-sm font-medium" style={{ color: 'rgba(200,180,255,0.5)' }}>
            Enter parcel details and click <span style={{ color: '#c084fc' }}>Get Rates</span> to see live AusPost pricing
          </p>
        </div>
      )}

      {/* Loading skeletons */}
      {loading && (
        <div className="space-y-3">
          {[1, 2, 3, 4].map(i => <SkeletonCard key={i} />)}
        </div>
      )}

      {/* Error */}
      {error && (
        <div className="rounded-xl p-4" style={{ background: 'rgba(239,68,68,0.1)', border: '1px solid rgba(239,68,68,0.3)' }}>
          <p className="text-sm font-semibold text-red-400 mb-1">⚠️ Error fetching rates</p>
          <p className="text-xs text-red-300">{error}</p>
        </div>
      )}

      {/* Results */}
      {rates && !loading && (
        <>
          {rates.services?.length === 0 ? (
            <p className="text-sm text-center py-8" style={{ color: 'rgba(200,180,255,0.5)' }}>
              No services available for this route.
            </p>
          ) : (
            <div className="space-y-5">
              <ServiceGroup title="⚡ Express Post" accent="#f59e0b" services={expressServices} />
              <ServiceGroup title="🐢 Parcel Post" accent="#3b82f6" services={parcelServices} />
            </div>
          )}
        </>
      )}

      {/* Selected service summary */}
      {selectedService && (
        <div className="rounded-xl p-4 space-y-3 mt-2" style={{ background: 'rgba(107,47,179,0.12)', border: '1px solid rgba(107,47,179,0.35)' }}>
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs mb-0.5" style={{ color: 'rgba(200,180,255,0.5)' }}>Selected Service</p>
              <p className="text-sm font-semibold text-white">{selectedService.name}</p>
            </div>
            <p className="text-xl font-black" style={{ color: '#c084fc' }}>${selectedService.price.toFixed(2)}</p>
          </div>
          <div className="flex gap-2">
            <button
              onClick={() => setShowSaveModal(true)}
              className="flex-1 py-2.5 rounded-xl text-white text-sm font-bold transition-all hover:opacity-90"
              style={{ background: 'linear-gradient(135deg, #7c3aed, #a855f7)' }}
            >
              💾 Save to Order
            </button>
            <div className="relative group">
              <button disabled
                className="px-4 py-2.5 rounded-xl text-sm font-semibold opacity-40 cursor-not-allowed"
                style={{ border: '1px solid rgba(107,47,179,0.3)', color: '#c084fc' }}>
                🖨️ Print Label
              </button>
              <div className="absolute bottom-full mb-1 left-1/2 -translate-x-1/2 hidden group-hover:block z-10">
                <div className="text-xs px-3 py-1.5 rounded-lg whitespace-nowrap"
                  style={{ background: '#1a1a2e', border: '1px solid rgba(107,47,179,0.3)', color: 'rgba(200,180,255,0.7)' }}>
                  Full label printing coming soon with MyPost Business API
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {showSaveModal && (
        <SaveToOrderModal service={selectedService} onClose={() => setShowSaveModal(false)} />
      )}
    </div>
  );
}