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

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

const inputStyle = {
  background: '#0d0d1a',
  border: '1px solid rgba(107,47,179,0.3)',
  color: 'white',
};

const inputClass = 'w-full px-3 py-2.5 text-sm rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 text-white transition-all';

const Section = ({ title, children }) => (
  <div className="space-y-3">
    <div className="flex items-center gap-2">
      <div className="w-1 h-4 rounded-full" style={{ background: 'linear-gradient(to bottom, #7c3aed, #f97316)' }} />
      <p className="text-xs font-bold uppercase tracking-widest" style={{ color: 'rgba(200,180,255,0.7)' }}>{title}</p>
    </div>
    {children}
  </div>
);

const Toggle = ({ label, value, onChange }) => (
  <div className="flex items-center justify-between">
    <span className="text-sm" style={{ color: 'rgba(200,180,255,0.8)' }}>{label}</span>
    <button
      onClick={() => onChange(!value)}
      className="relative inline-flex h-6 w-11 items-center rounded-full transition-colors"
      style={{ background: value ? '#7c3aed' : 'rgba(255,255,255,0.1)' }}
    >
      <span className="inline-block h-4 w-4 transform rounded-full bg-white transition-transform"
        style={{ transform: value ? 'translateX(1.375rem)' : 'translateX(0.25rem)' }} />
    </button>
  </div>
);

const PACKAGING = {
  boxes: [
    { code: 'BX1',  icon: '📦', name: 'Parcel Box Extra Small', length: 22.0, width: 16.0, height: 7.0,  maxWeight: 5 },
    { code: 'BX2',  icon: '📦', name: 'Parcel Box Small',       length: 24.0, width: 19.0, height: 12.0, maxWeight: 5 },
    { code: 'BX3',  icon: '📦', name: 'Parcel Box Medium',      length: 39.0, width: 28.0, height: 14.0, maxWeight: 5 },
    { code: 'BX4',  icon: '📦', name: 'Parcel Box Large',       length: 44.0, width: 27.7, height: 16.8, maxWeight: 5 },
    { code: 'BX20', icon: '📦', name: 'Parcel Box XL',          length: 50.0, width: 44.0, height: 35.0, maxWeight: 20 },
  ],
  satchels: [
    { code: 'S500G', icon: '📨', name: 'Prepaid Satchel 500g (XS)', length: 22.5, width: 35.5, height: 3, maxWeight: 0.5 },
    { code: 'S1KG',  icon: '📨', name: 'Prepaid Satchel 1kg (S)',   length: 27.0, width: 39.0, height: 3, maxWeight: 1 },
    { code: 'S3KG',  icon: '📨', name: 'Prepaid Satchel 3kg (M)',   length: 31.5, width: 40.5, height: 3, maxWeight: 3 },
    { code: 'S5KG',  icon: '📨', name: 'Prepaid Satchel 5kg (L)',   length: 44.0, width: 51.0, height: 3, maxWeight: 5 },
  ],
};

export default function ParcelDetailsPanel({ parcel, setParcel, onFromPostcodeChange, onGetRates, loading }) {
  const [showPullOrder, setShowPullOrder] = useState(false);
  const [orders, setOrders] = useState([]);
  const [ordersLoading, setOrdersLoading] = useState(false);
  const [manualPostcode, setManualPostcode] = useState('');
  const [selectedPackaging, setSelectedPackaging] = useState(null);

  const update = (key, val) => setParcel(p => ({ ...p, [key]: val }));

  const openPullOrder = async () => {
    setShowPullOrder(true);
    setOrdersLoading(true);
    const data = await shire.entities.Order.list('-order_date', 50);
    setOrders(data);
    setOrdersLoading(false);
  };

  const pullFromOrder = (order) => {
    const pc = order.customer_postcode || manualPostcode;
    if (pc) update('toPostcode', pc);
    setShowPullOrder(false);
  };

  return (
    <div className="rounded-2xl p-5 space-y-5" 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">📦 Parcel Details</span>
      </div>

      {/* Postcodes */}
      <Section title="📍 Postcodes">
        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className="block text-xs mb-1.5" style={{ color: 'rgba(200,180,255,0.6)' }}>From Postcode</label>
            <div className="relative">
              <input
                type="text"
                value="6172"
                readOnly
                className={inputClass}
                style={{ ...inputStyle, opacity: 0.7, cursor: 'not-allowed', paddingRight: '4.5rem' }}
              />
              <span className="absolute right-2.5 top-1/2 -translate-y-1/2 text-xs font-semibold px-1.5 py-0.5 rounded"
                style={{ background: 'rgba(124,58,237,0.25)', color: '#a78bfa' }}>
                📍 Sender
              </span>
            </div>
          </div>
          <div>
            <label className="block text-xs mb-1.5" style={{ color: 'rgba(200,180,255,0.6)' }}>To Postcode</label>
            <input
              type="text" maxLength={4}
              placeholder="Enter postcode"
              value={parcel.toPostcode}
              onChange={e => update('toPostcode', e.target.value)}
              className={inputClass} style={inputStyle}
            />
          </div>
        </div>
        <button
          onClick={openPullOrder}
          className="text-xs transition-all hover:opacity-80"
          style={{ color: '#a78bfa' }}
        >
          📋 Pull from Order
        </button>

        {/* Pull from Order modal */}
        {showPullOrder && (
          <div className="rounded-xl p-4 space-y-3" style={{ background: '#0d0d1a', border: '1px solid rgba(107,47,179,0.3)' }}>
            <p className="text-xs font-bold text-white">Select an order to pull postcode</p>
            {ordersLoading ? (
              <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>
            ) : (
              <div className="max-h-40 overflow-y-auto space-y-1.5">
                {orders.map(o => (
                  <div key={o.id} className="flex items-center justify-between">
                    <div>
                      <span className="text-xs text-white font-medium">{o.order_number}</span>
                      <span className="text-xs ml-2" style={{ color: 'rgba(200,180,255,0.5)' }}>{o.customer_name}</span>
                      {o.customer_postcode && (
                        <span className="text-xs ml-2 font-mono" style={{ color: '#a78bfa' }}>{o.customer_postcode}</span>
                      )}
                    </div>
                    <button onClick={() => pullFromOrder(o)}
                      className="text-xs px-2 py-1 rounded-lg font-semibold"
                      style={{ background: 'rgba(124,58,237,0.2)', color: '#c084fc' }}>
                      Use
                    </button>
                  </div>
                ))}
              </div>
            )}
            <div>
              <label className="block text-xs mb-1" style={{ color: 'rgba(200,180,255,0.5)' }}>Or paste postcode manually</label>
              <div className="flex gap-2">
                <input type="text" maxLength={4} value={manualPostcode}
                  onChange={e => setManualPostcode(e.target.value)}
                  placeholder="4 digit postcode"
                  className={inputClass} style={{ ...inputStyle, flex: 1 }} />
                <button onClick={() => { update('toPostcode', manualPostcode); setShowPullOrder(false); }}
                  className="px-3 py-2 rounded-lg text-xs font-semibold text-white"
                  style={{ background: '#7c3aed' }}>
                  Use
                </button>
              </div>
            </div>
            <button onClick={() => setShowPullOrder(false)}
              className="text-xs" style={{ color: 'rgba(200,180,255,0.4)' }}>✕ Close</button>
          </div>
        )}
      </Section>

      {/* Packaging Picker */}
      <Section title="📦 Select AusPost Packaging">
        {/* Boxes */}
        <p className="text-xs font-semibold" style={{ color: 'rgba(200,180,255,0.45)' }}>📦 Parcel Boxes</p>
        <div className="grid grid-cols-2 gap-2">
          {PACKAGING.boxes.map(pkg => {
            const isSelected = selectedPackaging?.code === pkg.code;
            return (
              <button
                key={pkg.code}
                onClick={() => {
                  setSelectedPackaging(pkg);
                  setParcel(p => ({ ...p, length: pkg.length, width: pkg.width, height: pkg.height, weight: pkg.maxWeight }));
                }}
                className="text-left rounded-xl p-3 transition-all"
                style={{
                  background: isSelected ? 'rgba(107,47,179,0.25)' : 'rgba(13,13,26,0.8)',
                  border: isSelected ? '2px solid #6b2fb3' : '1px solid rgba(107,47,179,0.25)',
                  boxShadow: isSelected ? '0 0 14px rgba(107,47,179,0.35)' : 'none',
                }}
              >
                <div className="flex items-start gap-1.5">
                  <span className="text-base leading-none mt-0.5">{pkg.icon}</span>
                  <div className="min-w-0">
                    <p className="text-xs font-semibold text-white leading-tight truncate">{pkg.name}</p>
                    <p className="text-xs mt-0.5 font-mono" style={{ color: 'rgba(200,180,255,0.45)' }}>
                      {pkg.length}×{pkg.width}×{pkg.height}cm
                    </p>
                    <p className="text-xs mt-0.5" style={{ color: '#a78bfa' }}>Max {pkg.maxWeight}kg</p>
                  </div>
                </div>
              </button>
            );
          })}
        </div>

        {/* Satchels */}
        <p className="text-xs font-semibold mt-1" style={{ color: 'rgba(200,180,255,0.45)' }}>📨 Satchels</p>
        <div className="grid grid-cols-2 gap-2">
          {PACKAGING.satchels.map(pkg => {
            const isSelected = selectedPackaging?.code === pkg.code;
            return (
              <button
                key={pkg.code}
                onClick={() => {
                  setSelectedPackaging(pkg);
                  setParcel(p => ({ ...p, length: pkg.length, width: pkg.width, height: pkg.height, weight: pkg.maxWeight }));
                }}
                className="text-left rounded-xl p-3 transition-all"
                style={{
                  background: isSelected ? 'rgba(107,47,179,0.25)' : 'rgba(13,13,26,0.8)',
                  border: isSelected ? '2px solid #6b2fb3' : '1px solid rgba(107,47,179,0.25)',
                  boxShadow: isSelected ? '0 0 14px rgba(107,47,179,0.35)' : 'none',
                }}
              >
                <div className="flex items-start gap-1.5">
                  <span className="text-base leading-none mt-0.5">{pkg.icon}</span>
                  <div className="min-w-0">
                    <p className="text-xs font-semibold text-white leading-tight">{pkg.name}</p>
                    <p className="text-xs mt-0.5 font-mono" style={{ color: 'rgba(200,180,255,0.45)' }}>
                      {pkg.length}×{pkg.width} cm (flat)
                    </p>
                    <p className="text-xs mt-0.5" style={{ color: '#a78bfa' }}>Max {pkg.maxWeight}kg</p>
                  </div>
                </div>
              </button>
            );
          })}
        </div>
      </Section>

      {/* Custom card */}
      <button
        onClick={() => {
          setSelectedPackaging({ code: 'CUSTOM', name: 'Custom', icon: '✏️' });
          setParcel(p => ({ ...p, weight: '', length: '', width: '', height: '' }));
        }}
        className="w-full text-left rounded-xl p-3 transition-all"
        style={{
          background: selectedPackaging?.code === 'CUSTOM' ? 'rgba(249,115,22,0.18)' : 'rgba(13,13,26,0.8)',
          border: selectedPackaging?.code === 'CUSTOM' ? '2px solid #f97316' : '1px solid rgba(107,47,179,0.25)',
          boxShadow: selectedPackaging?.code === 'CUSTOM' ? '0 0 14px rgba(249,115,22,0.25)' : 'none',
        }}
      >
        <div className="flex items-center gap-2">
          <span className="text-base">✏️</span>
          <div>
            <p className="text-xs font-bold text-white">Custom Size / Weight</p>
            <p className="text-xs mt-0.5" style={{ color: 'rgba(200,180,255,0.45)' }}>Enter your own dimensions manually</p>
          </div>
        </div>
      </button>

      {/* Weight & Size — shown when Custom selected or after any preset */}
      {selectedPackaging && (
        <Section title="⚖️ Parcel Weight & Size">
          <div className="grid grid-cols-2 gap-3">
            <div className="col-span-2">
              <label className="block text-xs mb-1.5" style={{ color: 'rgba(200,180,255,0.6)' }}>Weight (kg)</label>
              <input type="number" step="0.001" placeholder="0.500"
                value={parcel.weight} onChange={e => update('weight', e.target.value)}
                className={inputClass} style={inputStyle} />
              {selectedPackaging.code !== 'CUSTOM' && selectedPackaging.maxWeight && (
                <p className="text-xs mt-1" style={{ color: 'rgba(200,180,255,0.4)' }}>
                  Max weight for this packaging: <span style={{ color: '#a78bfa' }}>{selectedPackaging.maxWeight}kg</span>
                </p>
              )}
            </div>
            {[
              { label: 'Length (cm)', key: 'length' },
              { label: 'Width (cm)', key: 'width' },
              { label: 'Height (cm)', key: 'height' },
            ].map(({ label, key }) => (
              <div key={key}>
                <label className="block text-xs mb-1.5" style={{ color: 'rgba(200,180,255,0.6)' }}>{label}</label>
                <input type="number" value={parcel[key]} onChange={e => update(key, e.target.value)}
                  className={inputClass} style={inputStyle} />
              </div>
            ))}
          </div>
        </Section>
      )}

      {/* Options */}
      <Section title="⚙️ Options">
        <Toggle label="Signature on Delivery" value={parcel.signatureOnDelivery}
          onChange={v => update('signatureOnDelivery', v)} />
        <Toggle label="Extra Cover" value={parcel.extraCover}
          onChange={v => update('extraCover', v)} />
        {parcel.extraCover && (
          <div>
            <label className="block text-xs mb-1.5" style={{ color: 'rgba(200,180,255,0.6)' }}>Cover Amount ($)</label>
            <input type="number" step="0.01" placeholder="0.00"
              value={parcel.coverAmount} onChange={e => update('coverAmount', e.target.value)}
              className={inputClass} style={inputStyle} />
          </div>
        )}
      </Section>

      {/* Get Rates */}
      <button
        onClick={onGetRates}
        disabled={loading}
        className="w-full py-3.5 rounded-xl text-white font-bold text-sm flex items-center justify-center gap-2 transition-all hover:opacity-90 active:scale-95 disabled:opacity-60"
        style={{ background: 'linear-gradient(135deg, #7c3aed, #f97316)', boxShadow: '0 0 20px rgba(124,58,237,0.4)' }}
      >
        {loading
          ? <><div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> Fetching Rates…</>
          : '🔍 Get Rates'}
      </button>
    </div>
  );
}