import { useState, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import ParcelDetailsPanel from '@/components/shipping/ParcelDetailsPanel';
import ShippingRatesPanel from '@/components/shipping/ShippingRatesPanel';
import { shire } from '@/api/shireClient';
import { toast } from 'sonner';

const DEFAULT_PARCEL = {
  fromPostcode: '6172',
  toPostcode: '',
  weight: '',
  length: 15,
  width: 12,
  height: 10,
  signatureOnDelivery: false,
  extraCover: false,
  coverAmount: '',
};

export default function Shipping() {
  const location = useLocation();
  const [parcel, setParcel] = useState(DEFAULT_PARCEL);
  const [rates, setRates] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [selectedService, setSelectedService] = useState(null);

  // Handle deep-link from Orders page
  useEffect(() => {
    const params = new URLSearchParams(location.search);
    const orderId = params.get('orderId');
    if (orderId) {
      shire.entities.Order.filter({ id: orderId }).then(orders => {
        const order = orders[0];
        if (order?.customer_postcode) {
          setParcel(p => ({ ...p, toPostcode: order.customer_postcode }));
        }
      });
    }
  }, [location.search]);

  const handleFromPostcodeChange = () => {}; // locked — always 6172

  const getRates = async () => {
    if (!parcel.toPostcode || !parcel.weight) {
      toast.error('Please enter a destination postcode and weight.');
      return;
    }
    setLoading(true);
    setError(null);
    setRates(null);
    setSelectedService(null);
    try {
      const res = await shire.functions.invoke('getAusPostRates', {
        from_postcode: '6172',
        to_postcode: parcel.toPostcode,
        weight: Number(parcel.weight),
        length: Number(parcel.length),
        width: Number(parcel.width),
        height: Number(parcel.height),
      });
      setRates(res.data);
    } catch (err) {
      setError(err?.response?.data?.error || err.message || 'Failed to fetch rates. Check your API key and parcel details.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen p-4 md:p-6" style={{ background: '#0d0d1a' }}>
      <div className="max-w-7xl mx-auto">
        <div className="mb-6">
          <h1 className="text-2xl md:text-3xl font-bold text-white tracking-tight">📬 Shipping Calculator</h1>
          <p className="text-sm mt-1" style={{ color: 'rgba(200,180,255,0.6)' }}>
            Live AusPost postage rates — enter parcel details and get instant quotes
          </p>
        </div>

        <div className="grid grid-cols-1 xl:grid-cols-2 gap-5">
          <ParcelDetailsPanel
            parcel={parcel}
            setParcel={setParcel}
            onFromPostcodeChange={handleFromPostcodeChange}
            onGetRates={getRates}
            loading={loading}
          />
          <ShippingRatesPanel
            rates={rates}
            loading={loading}
            error={error}
            selectedService={selectedService}
            setSelectedService={setSelectedService}
            signatureRequested={parcel.signatureOnDelivery}
          />
        </div>
      </div>
    </div>
  );
}