import React, { useEffect, useState } from 'react';
import Modal from '../components/Modal';
import IconTruck from '../components/Icon/IconTruck';
import IconMapPin from '../components/Icon/IconMapPin';
import IconPhone from '../components/Icon/IconPhone';
import IconSearch from '../components/Icon/IconSearch';
import IconRefresh from '../components/Icon/IconRefresh';
import { shipmentApi } from '../api/shipmentApi';
import {
    ArticleShape,
    PincodeOffice,
    ServiceType,
    TariffBreakdown,
    indiaPostApi,
} from '../api/indiaPostApi';
import Swal from 'sweetalert2';

interface CreateShipmentModalProps {
    open: boolean;
    onClose: () => void;
    order: any;
    onSuccess?: (shipment: any) => void;
}

const SERVICE_OPTIONS: { code: ServiceType; label: string; isDoc: boolean }[] = [
    { code: 'SP_INLAND_PARCEL', label: 'Speed Post Parcel (SP_INLAND_PARCEL)', isDoc: false },
    { code: 'SP_INLAND_DOC', label: 'Speed Post Document (SP_INLAND_DOC)', isDoc: true },
    { code: 'BUSINESS_PARCEL', label: 'Business Parcel (BUSINESS_PARCEL)', isDoc: false },
    { code: '24_SPEEDPOST_DOC', label: '24H Speed Post Doc (24_SPEEDPOST_DOC)', isDoc: true },
    { code: '48_SPEEDPOST_DOC', label: '48H Speed Post Doc (48_SPEEDPOST_DOC)', isDoc: true },
    { code: '24_SPP_PARSPL', label: '24H Speed Post Parcel OTP (24_SPP_PARSPL)', isDoc: false },
];

const extractPin = (addr: string): string => {
    const m = String(addr || '').match(/\b([1-9]\d{5})\b/);
    return m ? m[1] : '';
};

const CreateShipmentModal: React.FC<CreateShipmentModalProps> = ({
    open,
    onClose,
    order,
    onSuccess,
}) => {
    const isSpeedOrder = Boolean(
        order?.delivery_mode === 'speed' ||
        order?.deliveryMode === 'speed' ||
        Number(order?.shipping_fee || order?.shippingFee) > 0
    );

    const [articleType, setArticleType] = useState<ServiceType>('SP_INLAND_PARCEL');
    const [shape, setShape] = useState<ArticleShape>('NROL');
    const [weightGrams, setWeightGrams] = useState(250);
    const [length, setLength] = useState(15);
    const [breadth, setBreadth] = useState(11);
    const [height, setHeight] = useState(5);

    const [pincode, setPincode] = useState('');
    const [city, setCity] = useState('');
    const [stateName, setStateName] = useState('');
    const [offices, setOffices] = useState<PincodeOffice[]>([]);
    const [destOfficeId, setDestOfficeId] = useState('');
    const [destOfficeName, setDestOfficeName] = useState('');
    const [lookingUpPin, setLookingUpPin] = useState(false);

    const [pickupOrDropoff, setPickupOrDropoff] = useState<'dropoff' | 'pickup'>('dropoff');
    const [pickupDate, setPickupDate] = useState(() => {
        const d = new Date();
        d.setDate(d.getDate() + 1);
        return d.toISOString().split('T')[0];
    });
    const [pickupSlot, setPickupSlot] = useState('10:00-13:00');

    const [cod, setCod] = useState(false);
    const [codAmount, setCodAmount] = useState(0);
    const [insurance, setInsurance] = useState(false);
    const [insuranceAmount, setInsuranceAmount] = useState(0);
    const [ack, setAck] = useState(false);
    const [reg, setReg] = useState(false);
    const [otp, setOtp] = useState(false);
    const [labelSize, setLabelSize] = useState<'A6' | 'A7'>('A6');

    const [senderPin, setSenderPin] = useState('625009');
    const [sourceOfficeId, setSourceOfficeId] = useState('29661417');

    const [tariff, setTariff] = useState<TariffBreakdown | null>(null);
    const [loadingTariff, setLoadingTariff] = useState(false);
    const [tariffError, setTariffError] = useState('');

    const [customAwb, setCustomAwb] = useState('');
    const [barcodeMsg, setBarcodeMsg] = useState<{ ok: boolean; text: string } | null>(null);
    const [isSubmitting, setIsSubmitting] = useState(false);

    // Pre-populate cleanly from the selected Order each time modal opens
    useEffect(() => {
        if (!open || !order) return;
        const speed = Boolean(
            order?.delivery_mode === 'speed' ||
            order?.deliveryMode === 'speed' ||
            Number(order?.shipping_fee || order?.shippingFee) > 0
        );
        const defaultService: ServiceType = speed ? 'SP_INLAND_PARCEL' : 'BUSINESS_PARCEL';
        setArticleType(defaultService);
        setShape('NROL');
        setWeightGrams(250);
        setLength(15);
        setBreadth(11);
        setHeight(5);

        const addr = String(order.shipping_address || order.address || '');
        const parsedPin = order.pincode || extractPin(addr);
        setPincode(parsedPin);
        setCity(order.city || '');
        setStateName(order.state || '');
        setOffices([]);
        setDestOfficeId('');
        setDestOfficeName('');

        const total = Number(order.amount || order.total || 0);
        const isPaid = (order.payment_status || order.payment || '').toLowerCase() === 'paid';
        setCod(!isPaid && total > 0);
        setCodAmount(!isPaid ? total : 0);
        setInsurance(false);
        setInsuranceAmount(0);
        setAck(false);
        setReg(false);
        setOtp(false);
        setPickupOrDropoff('dropoff');
        setTariff(null);
        setTariffError('');
        setCustomAwb('');
        setBarcodeMsg(null);

        indiaPostApi
            .getSenderProfile()
            .then((res) => {
                if (res.success && res.data) {
                    setSenderPin(res.data.sender_pincode || '625009');
                    setSourceOfficeId(res.data.pickup_office_id || '29661417');
                }
            })
            .catch(() => {});
    }, [open, order?.id]);

    // Enforce India Post shape & OTP rules when article type changes
    useEffect(() => {
        const meta = SERVICE_OPTIONS.find((s) => s.code === articleType);
        if (meta?.isDoc) {
            setShape('DOC');
        } else if (shape === 'DOC') {
            setShape('NROL');
        }
        if (articleType === '24_SPP_PARSPL') {
            setOtp(true);
        }
        setTariff(null);
    }, [articleType]);

    if (!open || !order) return null;

    const orderNo = order.order_no || order.orderNo || `ORD-${order.id}`;
    const customerName = order.customer_name || order.customer || 'Valued Customer';
    const customerPhone = order.customer_phone || order.phone || order.phones?.[0] || 'N/A';
    const address = order.shipping_address || order.address || 'Address on file';
    const totalAmount = Number(order.amount || order.total || 0);
    const isPaid = (order.payment_status || order.payment || '').toLowerCase() === 'paid';
    const isDoc = SERVICE_OPTIONS.find((s) => s.code === articleType)?.isDoc ?? false;
    const volumetricGrams = Math.round(((length * breadth * height) / 5) * 100) / 100;

    const handleLookupPin = async () => {
        if (!/^\d{6}$/.test(pincode)) {
            Swal.fire('Invalid PIN', 'Enter a 6-digit destination PIN code.', 'warning');
            return;
        }
        setLookingUpPin(true);
        try {
            const res = await indiaPostApi.searchPincode(pincode);
            const list: PincodeOffice[] = res.data?.offices || [];
            setOffices(list);
            const eligible = list.find((o) => o.is_eligible_delivery_office) || list[0];
            if (eligible) {
                setDestOfficeId(eligible.office_id);
                setDestOfficeName(eligible.office_name);
                if (eligible.city_name) setCity(eligible.city_name);
                if (eligible.state_name) setStateName(eligible.state_name);
            } else {
                Swal.fire('No Offices Found', 'India Post returned no delivery offices for this PIN.', 'warning');
            }
        } catch (err: any) {
            Swal.fire('PIN Lookup Failed', err.response?.data?.message || 'Unable to verify PIN code.', 'error');
        } finally {
            setLookingUpPin(false);
        }
    };

    const handleCalculateTariff = async () => {
        if (!/^\d{6}$/.test(pincode)) {
            Swal.fire('Destination PIN Required', 'Enter a valid 6-digit receiver PIN code first.', 'warning');
            return;
        }
        setLoadingTariff(true);
        setTariffError('');
        try {
            const res = await indiaPostApi.calculateTariff({
                article_type: articleType,
                weight: weightGrams,
                length,
                breadth,
                height,
                source_pincode: senderPin,
                destination_pincode: pincode,
                source_office_id: sourceOfficeId,
                destination_office_id: destOfficeId,
                insurance_value: insurance ? insuranceAmount : 0,
                cod_value: cod ? codAmount : 0,
                ack,
                reg,
                otp: articleType === '24_SPP_PARSPL' ? true : otp,
                pod: ack,
            });
            if (res.success && res.data) {
                setTariff(res.data);
            }
        } catch (err: any) {
            setTariff(null);
            setTariffError(err.response?.data?.message || 'Tariff lookup failed for this route/service.');
        } finally {
            setLoadingTariff(false);
        }
    };

    const handleCheckBarcode = async (code?: string) => {
        const val = (code ?? customAwb).trim().toUpperCase();
        if (!val) return;
        try {
            const res = await indiaPostApi.validateBarcode(val);
            if (res.data) {
                setBarcodeMsg({ ok: res.data.is_available, text: res.data.message });
            }
        } catch {
            setBarcodeMsg({ ok: false, text: 'Could not validate barcode.' });
        }
    };

    const handleDrawPoolBarcode = async () => {
        try {
            const res = await indiaPostApi.suggestBarcode();
            if (res.success && res.barcode_no) {
                setCustomAwb(res.barcode_no);
                await handleCheckBarcode(res.barcode_no);
            }
        } catch (err: any) {
            Swal.fire(
                'No Allocated Barcodes in Pool',
                err.response?.data?.message ||
                    'Import your official India Post barcodes in Settings → India Post or type an authorized barcode manually.',
                'warning'
            );
        }
    };

    const handleCreateShipment = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!/^\d{6}$/.test(pincode)) {
            Swal.fire('PIN Required', 'Enter a valid 6-digit destination PIN code.', 'warning');
            return;
        }
        if (!isDoc && (length < 14 || breadth < 9 || height < 1)) {
            Swal.fire('Dimensions Too Small', 'Parcel services require minimum 14 × 9 × 1 cm.', 'warning');
            return;
        }

        setIsSubmitting(true);
        try {
            const payload: any = {
                order_id: order.id || order.dbId || order.rawId || orderNo,
                courier_name: isSpeedOrder || articleType.includes('SP') ? 'India Speed Post' : 'India Normal Post',
                article_type: articleType,
                shape_of_article: shape,
                weight: weightGrams / 1000,
                length,
                breadth,
                height,
                city: city || undefined,
                state: stateName || undefined,
                pincode,
                destination_office_id: destOfficeId || undefined,
                destination_office_name: destOfficeName || undefined,
                pickup_or_dropoff: pickupOrDropoff,
                pickup_details:
                    pickupOrDropoff === 'pickup'
                        ? { schedule_date: pickupDate, schedule_slot: pickupSlot }
                        : undefined,
                cod,
                cod_amount: cod ? codAmount : 0,
                insurance,
                insurance_amount: insurance ? insuranceAmount : 0,
                ack,
                reg,
                otp: articleType === '24_SPP_PARSPL' ? true : otp,
                label_size: labelSize,
                tariff_breakdown: tariff || undefined,
            };

            if (customAwb.trim()) {
                payload.awb_code = customAwb.trim().toUpperCase();
            }

            const res = await shipmentApi.createShipmentFromOrder(payload);

            if (res.success) {
                const shipment = res.data;
                const bookingId = res.india_post?.booking_id;
                const trackingUrl = res.tracking_url || shipment.tracking_url || 'https://www.indiapost.gov.in';

                Swal.fire({
                    icon: 'success',
                    title: 'Order Dispatched via India Post!',
                    html: `
                        <div class="text-left space-y-1.5 mt-3 p-3.5 bg-red-50/70 border border-red-200 rounded-xl text-xs text-slate-700">
                            <div><strong>Shipment ID:</strong> <span class="font-mono text-[#990000] font-bold">${shipment.shipment_no}</span></div>
                            <div><strong>Service:</strong> <span class="font-bold">${articleType} (${shape})</span></div>
                            <div><strong>Barcode (AWB):</strong> <span class="font-mono font-bold text-blue-700">${shipment.awb_code}</span></div>
                            <div><strong>Package:</strong> ${weightGrams}g • ${length} × ${breadth} × ${height} cm</div>
                            ${res.india_post?.calculated_tariff ? `<div><strong>India Post Tariff:</strong> ₹${Number(res.india_post.calculated_tariff).toFixed(2)}</div>` : ''}
                            <div class="pt-1 text-amber-800 font-medium">API accepted & shipment added to <strong>Shipments</strong>. Physical scan updates once handed over at Post Office.</div>
                        </div>
                    `,
                    showCancelButton: true,
                    confirmButtonText: bookingId ? `Preview ${labelSize} Label PDF` : 'Track on India Post ↗',
                    cancelButtonText: 'Done',
                    confirmButtonColor: '#990000',
                }).then(async (result) => {
                    if (result.isConfirmed) {
                        if (bookingId) {
                            try {
                                const blobUrl = await indiaPostApi.fetchLabelBlobUrl(bookingId);
                                window.open(blobUrl, '_blank');
                            } catch {
                                window.open(trackingUrl, '_blank');
                            }
                        } else {
                            window.open(trackingUrl, '_blank');
                        }
                    }
                });

                if (onSuccess) onSuccess(shipment);
                onClose();
            } else {
                Swal.fire('Shipment Creation Failed', res.message || 'Could not dispatch via India Post.', 'error');
            }
        } catch (err: any) {
            console.error('Shipment creation error:', err);
            const msg = err.response?.data?.message || err.message || 'Failed to dispatch shipment via India Post.';
            const errs = Array.isArray(err.response?.data?.errors) ? err.response.data.errors.join(' | ') : '';
            Swal.fire('India Post Dispatch Error', errs || msg, 'error');
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <Modal
            open={open}
            onClose={onClose}
            title={`Order → Ship via India Post (${orderNo})`}
            icon={
                <span className="p-1 rounded-md bg-[#990000] text-white shadow-xs inline-flex items-center justify-center">
                    <IconTruck className="w-4 h-4" />
                </span>
            }
            width="lg"
        >
            <form onSubmit={handleCreateShipment} className="space-y-3.5 pt-1 max-h-[78vh] overflow-y-auto pr-1">
                {/* Order Summary & Receiver Destination */}
                <div className="bg-slate-50 border border-slate-200/80 rounded-xl p-3 space-y-2">
                    <div className="flex justify-between items-center pb-1.5 border-b border-slate-200/60">
                        <div>
                            <span className="font-mono text-xs font-bold text-amber-900 bg-amber-100/70 px-2 py-0.5 rounded-md">
                                {orderNo}
                            </span>
                            <span className="ml-2 text-xs font-bold text-slate-800">{customerName}</span>
                        </div>
                        <span
                            className={`text-[10px] font-extrabold px-2.5 py-0.5 rounded-full border uppercase tracking-wider ${
                                isPaid ? 'bg-emerald-50 text-emerald-700 border-emerald-200' : 'bg-amber-50 text-amber-700 border-amber-200'
                            }`}
                        >
                            {isPaid ? 'PREPAID' : 'COD'} • ₹{totalAmount.toLocaleString('en-IN')}
                        </span>
                    </div>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-1.5 text-xs text-slate-600">
                        <div className="flex items-center gap-1.5">
                            <IconPhone className="w-3.5 h-3.5 shrink-0" />
                            <span>{customerPhone}</span>
                        </div>
                        <div className="flex items-start gap-1.5">
                            <IconMapPin className="w-3.5 h-3.5 shrink-0 mt-0.5" />
                            <span className="line-clamp-2">{address}</span>
                        </div>
                    </div>
                </div>

                {/* Service, Shape & Destination PIN Verification */}
                <div className="p-3 rounded-xl border border-slate-200 bg-white space-y-2.5">
                    <div className="grid grid-cols-1 sm:grid-cols-3 gap-2.5">
                        <div className="sm:col-span-2">
                            <label className="text-[11px] font-bold text-slate-700 block mb-1">India Post Service</label>
                            <select
                                value={articleType}
                                onChange={(e) => setArticleType(e.target.value as ServiceType)}
                                className="form-select w-full text-xs font-semibold py-1.5"
                            >
                                {SERVICE_OPTIONS.map((s) => (
                                    <option key={s.code} value={s.code}>
                                        {s.label}
                                    </option>
                                ))}
                            </select>
                        </div>
                        <div>
                            <label className="text-[11px] font-bold text-slate-700 block mb-1">Article Shape</label>
                            <select
                                value={shape}
                                disabled={isDoc}
                                onChange={(e) => setShape(e.target.value as ArticleShape)}
                                className="form-select w-full text-xs font-semibold py-1.5"
                            >
                                {isDoc ? (
                                    <option value="DOC">DOC (Document)</option>
                                ) : (
                                    <>
                                        <option value="NROL">NROL (Rectangular)</option>
                                        <option value="ROLL">ROLL (Cylindrical)</option>
                                    </>
                                )}
                            </select>
                        </div>
                    </div>

                    <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 pt-1">
                        <div>
                            <label className="text-[10px] font-semibold text-slate-500">Receiver PIN *</label>
                            <div className="flex gap-1">
                                <input
                                    type="text"
                                    maxLength={6}
                                    required
                                    value={pincode}
                                    onChange={(e) => setPincode(e.target.value.replace(/\D/g, '').slice(0, 6))}
                                    className="form-input w-full text-xs font-mono py-1.5 px-2"
                                />
                                <button
                                    type="button"
                                    onClick={handleLookupPin}
                                    disabled={lookingUpPin}
                                    title="Validate PIN & lookup India Post delivery offices"
                                    className="px-2 rounded-lg bg-[#8B3E1F] text-white text-[11px] font-bold hover:bg-[#703017] shrink-0"
                                >
                                    <IconSearch className="w-3.5 h-3.5" />
                                </button>
                            </div>
                        </div>
                        <div>
                            <label className="text-[10px] font-semibold text-slate-500">City</label>
                            <input
                                type="text"
                                value={city}
                                onChange={(e) => setCity(e.target.value)}
                                placeholder="Auto / City"
                                className="form-input w-full text-xs py-1.5 px-2"
                            />
                        </div>
                        <div>
                            <label className="text-[10px] font-semibold text-slate-500">State</label>
                            <input
                                type="text"
                                value={stateName}
                                onChange={(e) => setStateName(e.target.value)}
                                placeholder="Auto / State"
                                className="form-input w-full text-xs py-1.5 px-2"
                            />
                        </div>
                        <div>
                            <label className="text-[10px] font-semibold text-slate-500">Delivery Office</label>
                            {offices.length > 0 ? (
                                <select
                                    value={destOfficeId}
                                    onChange={(e) => {
                                        const found = offices.find((o) => o.office_id === e.target.value);
                                        setDestOfficeId(e.target.value);
                                        setDestOfficeName(found?.office_name || '');
                                    }}
                                    className="form-select w-full text-xs py-1.5 px-2"
                                >
                                    {offices.map((o) => (
                                        <option key={o.office_id} value={o.office_id}>
                                            {o.office_name} {o.is_eligible_delivery_office ? '✓' : '(Non-Deliv)'}
                                        </option>
                                    ))}
                                </select>
                            ) : (
                                <input
                                    type="text"
                                    readOnly
                                    placeholder="Click search PIN"
                                    value={destOfficeName}
                                    className="form-input w-full text-xs py-1.5 px-2 bg-slate-50"
                                />
                            )}
                        </div>
                    </div>
                </div>

                {/* Weight, Dimensions & VAS */}
                <div className="p-3 rounded-xl border border-slate-200 bg-white space-y-2.5">
                    <div className="flex items-center justify-between">
                        <label className="text-[11px] font-bold text-slate-700">Packed Weight, Dimensions & Services</label>
                        <span className="text-[10px] font-mono text-slate-500">
                            Volumetric: <strong>{volumetricGrams}g</strong>
                        </span>
                    </div>
                    <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
                        {[
                            { label: 'Weight (g)', value: weightGrams, setter: setWeightGrams, step: 1, min: 1 },
                            { label: 'Length (cm)', value: length, setter: setLength, step: 0.1, min: 1 },
                            { label: 'Breadth (cm)', value: breadth, setter: setBreadth, step: 0.1, min: 1 },
                            { label: 'Height (cm)', value: height, setter: setHeight, step: 0.1, min: 0.1 },
                        ].map((field) => (
                            <div key={field.label}>
                                <label className="text-[10px] font-semibold text-slate-500">{field.label}</label>
                                <input
                                    type="number"
                                    required
                                    min={field.min}
                                    step={field.step}
                                    value={field.value}
                                    onChange={(e) => {
                                        field.setter(Number(e.target.value));
                                        setTariff(null);
                                    }}
                                    className="w-full text-xs font-mono px-2.5 py-1.5 rounded-lg border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#990000]"
                                />
                            </div>
                        ))}
                    </div>

                    <div className="flex flex-wrap items-center gap-4 pt-1 text-xs">
                        <label className="inline-flex items-center gap-1.5 font-semibold">
                            <input type="checkbox" checked={cod} onChange={(e) => setCod(e.target.checked)} className="form-checkbox text-[#990000]" />
                            COD {cod && `(₹${codAmount})`}
                        </label>
                        <label className="inline-flex items-center gap-1.5 font-semibold">
                            <input type="checkbox" checked={insurance} onChange={(e) => setInsurance(e.target.checked)} className="form-checkbox text-[#990000]" />
                            Insurance
                        </label>
                        {insurance && (
                            <input
                                type="number"
                                placeholder="Insured Value ₹"
                                value={insuranceAmount}
                                onChange={(e) => setInsuranceAmount(Number(e.target.value))}
                                className="form-input w-28 py-1 px-2 text-xs font-mono"
                            />
                        )}
                        <label className="inline-flex items-center gap-1.5">
                            <input type="checkbox" checked={ack} onChange={(e) => setAck(e.target.checked)} className="form-checkbox text-[#990000]" />
                            ACK/POD
                        </label>
                        <label className="inline-flex items-center gap-1.5">
                            <input type="checkbox" checked={reg} onChange={(e) => setReg(e.target.checked)} className="form-checkbox text-[#990000]" />
                            REG
                        </label>
                        <label className="inline-flex items-center gap-1.5">
                            <input
                                type="checkbox"
                                checked={otp}
                                disabled={articleType === '24_SPP_PARSPL'}
                                onChange={(e) => setOtp(e.target.checked)}
                                className="form-checkbox text-[#990000]"
                            />
                            OTP {articleType === '24_SPP_PARSPL' ? '(Req)' : ''}
                        </label>
                    </div>

                    <div className="grid grid-cols-1 sm:grid-cols-3 gap-2 pt-1 border-t border-slate-100">
                        <div>
                            <label className="text-[10px] font-semibold text-slate-500">Handover</label>
                            <select
                                value={pickupOrDropoff}
                                onChange={(e) => setPickupOrDropoff(e.target.value as 'dropoff' | 'pickup')}
                                className="form-select w-full text-xs py-1.5"
                            >
                                <option value="dropoff">Dropoff at Booking Office</option>
                                <option value="pickup">Scheduled Pickup</option>
                            </select>
                        </div>
                        {pickupOrDropoff === 'pickup' ? (
                            <>
                                <div>
                                    <label className="text-[10px] font-semibold text-slate-500">Pickup Date</label>
                                    <input
                                        type="date"
                                        value={pickupDate}
                                        onChange={(e) => setPickupDate(e.target.value)}
                                        className="form-input w-full text-xs py-1.5"
                                    />
                                </div>
                                <div>
                                    <label className="text-[10px] font-semibold text-slate-500">Pickup Slot</label>
                                    <select
                                        value={pickupSlot}
                                        onChange={(e) => setPickupSlot(e.target.value)}
                                        className="form-select w-full text-xs py-1.5"
                                    >
                                        <option value="10:00-13:00">10:00-13:00</option>
                                        <option value="13:00-16:00">13:00-16:00</option>
                                    </select>
                                </div>
                            </>
                        ) : (
                            <div>
                                <label className="text-[10px] font-semibold text-slate-500">Label Size</label>
                                <select
                                    value={labelSize}
                                    onChange={(e) => setLabelSize(e.target.value as 'A6' | 'A7')}
                                    className="form-select w-full text-xs py-1.5"
                                >
                                    <option value="A6">A6 (4×6 Thermal)</option>
                                    <option value="A7">A7 (Compact)</option>
                                </select>
                            </div>
                        )}
                    </div>
                </div>

                {/* Live India Post Tariff Check */}
                <div className="p-3 rounded-xl border border-[#C89B5E]/40 bg-[#FAF6F0] flex flex-wrap items-center justify-between gap-2">
                    <div className="text-xs">
                        {tariff ? (
                            <div className="space-y-0.5">
                                <p className="font-bold text-[#8B3E1F]">
                                    Official Tariff: <span className="font-mono text-sm">₹{tariff.final_amount.toFixed(2)}</span>
                                    <span className="ml-2 text-[11px] font-normal text-slate-600">
                                        (Base ₹{tariff.base_tariff} + VAS ₹{tariff.vas_charges} + GST ₹{tariff.total_tax} • Chg Wt: {tariff.chargeable_weight}g)
                                    </span>
                                </p>
                            </div>
                        ) : tariffError ? (
                            <p className="text-rose-700 font-semibold">{tariffError}</p>
                        ) : (
                            <p className="text-slate-600">Calculate live shipping rate from India Post API before dispatch.</p>
                        )}
                    </div>
                    <button
                        type="button"
                        onClick={handleCalculateTariff}
                        disabled={loadingTariff}
                        className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-[#8B3E1F] text-white text-xs font-bold hover:bg-[#703017] disabled:opacity-50"
                    >
                        <IconRefresh className={`w-3.5 h-3.5 ${loadingTariff ? 'animate-spin' : ''}`} />
                        <span>{loadingTariff ? 'Calculating...' : 'Check Live Tariff'}</span>
                    </button>
                </div>

                {/* Authorized Barcode Input / Pool Draw */}
                <div className="p-3 rounded-xl border border-slate-200 bg-white space-y-1.5">
                    <div className="flex items-center justify-between">
                        <label className="text-[11px] font-bold text-slate-700">
                            Allocated India Post Barcode (13-Char S10)
                        </label>
                        <span className="text-[10px] text-slate-400">Draws next pool barcode if left blank</span>
                    </div>
                    <div className="flex flex-wrap gap-1.5">
                        <input
                            type="text"
                            maxLength={13}
                            value={customAwb}
                            onChange={(e) => {
                                setCustomAwb(e.target.value.toUpperCase());
                                setBarcodeMsg(null);
                            }}
                            placeholder="Scan/enter barcode or click Draw from Pool"
                            className="flex-1 text-xs font-mono font-bold px-3 py-1.5 rounded-lg border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#990000] uppercase"
                        />
                        <button
                            type="button"
                            onClick={() => handleCheckBarcode()}
                            className="px-2.5 py-1.5 rounded-lg border border-slate-300 text-xs font-bold text-slate-700 hover:bg-slate-50"
                        >
                            Check
                        </button>
                        <button
                            type="button"
                            onClick={handleDrawPoolBarcode}
                            className="px-3 py-1.5 rounded-lg bg-[#C89B5E] text-[#1E110C] text-xs font-bold hover:bg-[#b5854b]"
                        >
                            Draw from Pool
                        </button>
                    </div>
                    {barcodeMsg && (
                        <p className={`text-[11px] font-semibold ${barcodeMsg.ok ? 'text-emerald-700' : 'text-rose-600'}`}>
                            {barcodeMsg.text}
                        </p>
                    )}
                </div>

                {/* Footer */}
                <div className="flex justify-end items-center gap-2.5 pt-2 border-t border-slate-100">
                    <button
                        type="button"
                        onClick={onClose}
                        disabled={isSubmitting}
                        className="px-4 py-2 text-xs font-bold text-slate-600 bg-slate-100 hover:bg-slate-200 rounded-lg transition"
                    >
                        Cancel
                    </button>
                    <button
                        type="submit"
                        disabled={isSubmitting}
                        className="px-5 py-2 text-xs font-bold text-white bg-[#990000] hover:bg-[#800000] rounded-lg shadow-sm flex items-center gap-2 cursor-pointer transition disabled:opacity-60"
                    >
                        <IconTruck className="w-4 h-4" />
                        <span>{isSubmitting ? 'Creating India Post Shipment...' : 'Dispatch & Create Shipment'}</span>
                    </button>
                </div>
            </form>
        </Modal>
    );
};

export default CreateShipmentModal;
