import { useState, useEffect } from 'react';
import Button from '../../components/Buttons';
import Toast from '../../components/Toast';
import IconTruck from '../../components/Icon/IconTruck';
import IconRefresh from '../../components/Icon/IconRefresh';
import IconUser from '../../components/Icon/IconUser';
import IconMapPin from '../../components/Icon/IconMapPin';
import IconServer from '../../components/Icon/IconServer';
import { shipmentApi } from '../../api/shipmentApi';
import { indiaPostApi } from '../../api/indiaPostApi';
import Swal from 'sweetalert2';

interface BarcodePoolItem {
    id: number;
    barcode_no: string;
    series_label?: string;
    status: 'AVAILABLE' | 'RESERVED' | 'USED';
    used_at?: string;
}

const IndiaPostSettings = () => {
    const [customerId, setCustomerId] = useState('');
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [hasPassword, setHasPassword] = useState(false);
    const [contractNo, setContractNo] = useState('');
    const [facilityId, setFacilityId] = useState('');
    const [bookingOfficePin, setBookingOfficePin] = useState('');
    const [pickupOfficeId, setPickupOfficeId] = useState('');
    const [barcodePrefix, setBarcodePrefix] = useState('CT');
    const [bpLabelServiceType, setBpLabelServiceType] = useState('Business Parcel');
    const [isConfigured, setIsConfigured] = useState(false);
    const [hasAccessToken, setHasAccessToken] = useState(false);
    const [tokenExpiresAt, setTokenExpiresAt] = useState<string | null>(null);
    const [loading, setLoading] = useState(false);
    const [saving, setSaving] = useState(false);
    const [testing, setTesting] = useState(false);
    const [connectionStatus, setConnectionStatus] = useState<{
        tested: boolean;
        connected: boolean;
        message: string;
        details?: any;
    }>({
        tested: false,
        connected: false,
        message: '',
    });

    const [toast, setToast] = useState<{
        show: boolean;
        message: string;
        type: 'success' | 'error' | 'info';
    }>({
        show: false,
        message: '',
        type: 'success',
    });

    const [barcodePool, setBarcodePool] = useState<BarcodePoolItem[]>([]);
    const [barcodeStats, setBarcodeStats] = useState({ total: 0, available: 0, used: 0 });
    const [importText, setImportText] = useState('');
    const [seriesLabel, setSeriesLabel] = useState('');
    const [importingBarcodes, setImportingBarcodes] = useState(false);

    const loadBarcodePool = async () => {
        try {
            const res = await indiaPostApi.listBarcodes();
            if (res.success) {
                setBarcodePool(res.data || []);
                setBarcodeStats(res.stats || { total: 0, available: 0, used: 0 });
            }
        } catch (err) {
            console.error('Failed to load allocated barcodes:', err);
        }
    };

    const loadSettings = async () => {
        setLoading(true);
        try {
            const res = await shipmentApi.getIndiaPostSettings();
            if (res.success && res.data) {
                setCustomerId(res.data.customer_id || '');
                setUsername(res.data.username || res.data.customer_id || '');
                setHasPassword(!!res.data.has_password);
                setPassword(res.data.has_password ? '••••••••••••' : '');
                setContractNo(res.data.contract_no || '');
                setFacilityId(res.data.facility_id || '');
                setBookingOfficePin(res.data.booking_office_pin || '');
                setPickupOfficeId(res.data.pickup_office_id || '');
                setBarcodePrefix(res.data.barcode_prefix || 'CT');
                setBpLabelServiceType(res.data.bp_label_service_type || 'Business Parcel');
                setIsConfigured(!!res.data.is_configured);
                setHasAccessToken(!!res.data.has_access_token);
                setTokenExpiresAt(res.data.token_expires_at || null);
            }
        } catch (err) {
            console.error('Failed to load India Post settings:', err);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        loadSettings();
        loadBarcodePool();
    }, []);

    const handleImportBarcodes = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!importText.trim()) return;
        setImportingBarcodes(true);
        try {
            const res = await indiaPostApi.importBarcodes(importText, seriesLabel.trim() || undefined);
            setToast({ show: true, message: res.message || 'Barcodes imported!', type: 'success' });
            setImportText('');
            await loadBarcodePool();
        } catch (err: any) {
            setToast({
                show: true,
                message: err.response?.data?.message || 'Failed to import allocated barcodes.',
                type: 'error',
            });
        } finally {
            setImportingBarcodes(false);
        }
    };

    const handleDeleteBarcode = async (id: number) => {
        try {
            await indiaPostApi.deleteBarcode(id);
            await loadBarcodePool();
        } catch (err: any) {
            setToast({
                show: true,
                message: err.response?.data?.message || 'Unable to remove barcode.',
                type: 'error',
            });
        }
    };

    const handleSave = async (e: React.FormEvent) => {
        e.preventDefault();
        setSaving(true);
        try {
            const payload: any = {
                customer_id: customerId,
                username,
                contract_no: contractNo,
                facility_id: facilityId,
                booking_office_pin: bookingOfficePin,
                pickup_office_id: pickupOfficeId,
                barcode_prefix: barcodePrefix,
                bp_label_service_type: bpLabelServiceType,
            };
            if (password && password !== '••••••••••••') {
                payload.password = password;
            }
            const res = await shipmentApi.saveIndiaPostSettings(payload);
            if (res.success) {
                setHasAccessToken(false);
                setTokenExpiresAt(null);
                setToast({
                    show: true,
                    message: 'India Post settings saved successfully!',
                    type: 'success',
                });
                setIsConfigured(true);
            }
        } catch (err: any) {
            console.error(err);
            setToast({
                show: true,
                message: err.response?.data?.message || 'Failed to save India Post settings.',
                type: 'error',
            });
        } finally {
            setSaving(false);
        }
    };

    const handleTestConnection = async () => {
        setTesting(true);
        try {
            const confirmation = await Swal.fire({
                icon: 'question',
                title: 'Login to India Post',
                html: `
                    <p style="font-size:13px;color:#64748b;margin:0 0 14px">Enter the exact credentials that work in Postman.</p>
                    <input id="indiapost-login-username" class="swal2-input" type="text" placeholder="Portal / API username" autocomplete="username" style="margin:8px 0;width:80%">
                    <input id="indiapost-login-password" class="swal2-input" type="password" placeholder="Portal / API password" autocomplete="current-password" style="margin:8px 0;width:80%">
                `,
                didOpen: () => {
                    const usernameInput = document.getElementById('indiapost-login-username') as HTMLInputElement | null;
                    if (usernameInput) usernameInput.value = username || customerId;
                    document.getElementById('indiapost-login-password')?.focus();
                },
                showCancelButton: true,
                confirmButtonText: 'Login & Generate Token',
                confirmButtonColor: '#990000',
                showLoaderOnConfirm: true,
                allowOutsideClick: () => !Swal.isLoading(),
                preConfirm: async () => {
                    const loginUsername = (document.getElementById('indiapost-login-username') as HTMLInputElement | null)?.value.trim() || '';
                    const loginPassword = (document.getElementById('indiapost-login-password') as HTMLInputElement | null)?.value || '';
                    if (!loginUsername || !loginPassword) {
                        Swal.showValidationMessage('Username and password are required.');
                        return false;
                    }
                    try {
                        const res = await shipmentApi.testIndiaPostConnection({
                            customer_id: customerId || undefined,
                            username: loginUsername,
                            password: loginPassword,
                        });
                        return { res, loginUsername };
                    } catch (err: any) {
                        const message = err.response?.data?.message || err.message || 'India Post authentication failed.';
                        setConnectionStatus({ tested: true, connected: false, message });
                        Swal.showValidationMessage(message);
                        return false;
                    }
                },
            });

            if (confirmation.isConfirmed && confirmation.value?.res?.success) {
                const { res, loginUsername } = confirmation.value;
                setUsername(loginUsername);
                setConnectionStatus({
                    tested: true,
                    connected: true,
                    message: res.message || 'Connected successfully to India Post.',
                    details: res,
                });
                await loadSettings();
                await Swal.fire({
                    icon: 'success',
                    title: 'India Post Login Successful',
                    text: `Username ${loginUsername} verified. Access and refresh tokens are stored securely.`,
                    confirmButtonColor: '#990000',
                });
            }
        } catch (err: any) {
            setConnectionStatus({
                tested: true,
                connected: false,
                message: err.response?.data?.message || 'Connection test failed. Network or server error.',
            });
            Swal.fire({
                icon: 'error',
                title: 'Connection Error',
                text: err.response?.data?.message || 'Failed to reach India Post API.',
                confirmButtonColor: '#990000',
            });
        } finally {
            setTesting(false);
        }
    };

    return (
        <div className="p-4 md:p-6 max-w-5xl mx-auto space-y-6">
            <Toast
                show={toast.show}
                message={toast.message}
                type={toast.type}
                onClose={() => setToast((prev) => ({ ...prev, show: false }))}
            />

            {/* HEADER BANNER */}
            <div className="bg-gradient-to-r from-[#990000] via-[#B71C1C] to-[#C62828] text-white p-6 rounded-2xl shadow-md relative overflow-hidden flex flex-col md:flex-row md:items-center justify-between gap-4">
                <div className="absolute right-0 top-0 translate-x-8 -translate-y-8 opacity-10 pointer-events-none">
                    <IconTruck className="w-56 h-56 text-white" />
                </div>

                <div className="space-y-1.5 z-10">
                    <div className="flex items-center gap-2">
                        <span className="bg-[#FFD54F] text-[#4E1000] text-[11px] font-black uppercase px-2.5 py-0.5 rounded-full shadow-xs tracking-wider">
                            Department of Posts • Gov. of India
                        </span>
                        <span className="bg-emerald-400/25 text-emerald-100 border border-emerald-300/40 text-[11px] font-bold px-2 py-0.5 rounded-full">
                            LIVE PRODUCTION
                        </span>
                    </div>
                    <h1 className="text-2xl md:text-3xl font-black tracking-tight text-white flex items-center gap-2.5">
                        India Post Logistics &amp; API Integration
                    </h1>
                    <p className="text-red-100 text-xs md:text-sm max-w-xl">
                        Seamlessly dispatch orders via <strong className="text-white">India Speed Post</strong> and <strong className="text-white">Business Parcel</strong> with automatic consignment barcode assignment, manifest generation, and live indiapost.gov.in tracking.
                    </p>
                </div>

                <div className="flex items-center gap-2 z-10">
                    <button
                        type="button"
                        onClick={handleTestConnection}
                        disabled={testing}
                        className="px-4 py-2.5 rounded-xl font-bold text-xs bg-white text-[#990000] hover:bg-red-50 active:scale-95 transition shadow-sm flex items-center gap-1.5 cursor-pointer disabled:opacity-50"
                    >
                        <IconRefresh className={`w-3.5 h-3.5 ${testing ? 'animate-spin' : ''}`} />
                        <span>{testing ? 'Logging in...' : 'Login & Generate Token'}</span>
                    </button>
                </div>
            </div>

            {/* STATUS ALERT */}
            {connectionStatus.tested && (
                <div
                    className={`p-4 rounded-xl border flex items-center gap-3 transition-all ${
                        connectionStatus.connected
                            ? 'bg-emerald-50 border-emerald-200 text-emerald-900'
                            : 'bg-rose-50 border-rose-200 text-rose-900'
                    }`}
                >
                    <div
                        className={`w-3 h-3 rounded-full shrink-0 ${
                            connectionStatus.connected ? 'bg-emerald-500 animate-ping' : 'bg-rose-500'
                        }`}
                    />
                    <div className="flex-1 text-xs">
                        <strong className="block text-sm font-bold">
                            {connectionStatus.connected
                                ? 'Connected to India Post Live Production'
                                : 'Connection Test Failed'}
                        </strong>
                        <span>{connectionStatus.message}</span>
                    </div>
                </div>
            )}

            {/* SETTINGS FORM */}
            <form onSubmit={handleSave} className="bg-white rounded-2xl border border-slate-200/80 shadow-xs p-6 space-y-6">
                <div className="flex items-center justify-between border-b border-slate-100 pb-4">
                    <div>
                        <h2 className="text-base font-extrabold text-slate-800">
                            Department of Posts (DoP) Account Credentials
                        </h2>
                        <p className="text-xs text-slate-500">
                            Configure the credentials issued for the India Post live production environment.
                        </p>
                    </div>

                    <span
                        className={`text-[11px] font-extrabold px-3 py-1 rounded-full border ${
                            isConfigured
                                ? 'bg-emerald-50 text-emerald-700 border-emerald-200'
                                : 'bg-amber-50 text-amber-700 border-amber-200'
                        }`}
                    >
                        {isConfigured ? '✓ Configured' : 'Setup Required'}
                    </span>
                </div>

                <div className={`rounded-xl border px-4 py-3 text-xs ${hasAccessToken ? 'border-emerald-200 bg-emerald-50 text-emerald-800' : 'border-amber-200 bg-amber-50 text-amber-800'}`}>
                    <strong>{hasAccessToken ? 'Access token stored securely in database' : 'No stored access token'}</strong>
                    {tokenExpiresAt && <span className="ml-2">Expires: {new Date(tokenExpiresAt).toLocaleString()}</span>}
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                    {/* CUSTOMER ID */}
                    <div className="space-y-1.5">
                        <label className="text-xs font-bold text-slate-700 flex items-center gap-1.5">
                            <IconUser className="w-3.5 h-3.5 text-slate-500" />
                            India Post Customer ID <span className="text-red-500">*</span>
                        </label>
                        <input
                            type="text"
                            required
                            inputMode="numeric"
                            pattern="[0-9]{10}"
                            maxLength={10}
                            value={customerId}
                            onChange={(e) => setCustomerId(e.target.value.replace(/\D/g, '').slice(0, 10))}
                            placeholder="e.g. 9999227860"
                            className="w-full text-xs font-medium px-3.5 py-2.5 rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#990000] focus:border-transparent transition"
                        />
                        <p className="text-[11px] text-slate-400">
                            Your 10-digit Customer ID assigned for India Post live API access.
                        </p>
                    </div>

                    {/* USERNAME */}
                    <div className="space-y-1.5">
                        <label className="text-xs font-bold text-slate-700">Portal Login Username</label>
                        <input
                            type="text"
                            required
                            value={username}
                            onChange={(e) => setUsername(e.target.value)}
                            placeholder="Customer Self-Service Portal username"
                            className="w-full text-xs font-medium px-3.5 py-2.5 rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#990000]"
                        />
                    </div>

                    {/* PASSWORD */}
                    <div className="space-y-1.5">
                        <div className="flex items-center justify-between">
                            <label className="text-xs font-bold text-slate-700">Portal / API Password</label>
                            {hasPassword && (
                                <span className="text-[10px] text-emerald-600 font-extrabold bg-emerald-50 px-2 py-0.5 rounded-full border border-emerald-200">
                                    ✓ Password Stored
                                </span>
                            )}
                        </div>
                        <input
                            type="password"
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                            placeholder={hasPassword ? '••••••••••••' : 'Enter portal password'}
                            autoComplete="current-password"
                            className="w-full text-xs font-medium px-3.5 py-2.5 rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#990000]"
                        />
                        <p className="text-[11px] text-slate-400">
                            Leave blank or keep bullets to preserve your existing saved password.
                        </p>
                    </div>

                    {/* CONTRACT / ACCOUNT NUMBER */}
                    <div className="space-y-1.5">
                        <label className="text-xs font-bold text-slate-700 flex items-center gap-1.5">
                            <IconServer className="w-3.5 h-3.5 text-slate-500" />
                            Contract / Account Number
                        </label>
                        <input
                            type="text"
                            required
                            inputMode="numeric"
                            pattern="[0-9]{8}"
                            maxLength={8}
                            value={contractNo}
                            onChange={(e) => setContractNo(e.target.value.replace(/\D/g, '').slice(0, 8))}
                            placeholder="e.g. 41101054"
                            className="w-full text-xs font-medium px-3.5 py-2.5 rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#990000] focus:border-transparent transition"
                        />
                        <p className="text-[11px] text-slate-400">
                            Required 8-digit India Post BNPL contract number (for example, <strong>41101054</strong>).
                        </p>
                    </div>

                    {/* BOOKING FACILITY / BPC */}
                    <div className="space-y-1.5">
                        <label className="text-xs font-bold text-slate-700 flex items-center gap-1.5">
                            <IconMapPin className="w-3.5 h-3.5 text-slate-500" />
                            Booking Facility / Post Office
                        </label>
                        <input
                            type="text"
                            value={facilityId}
                            onChange={(e) => setFacilityId(e.target.value)}
                            placeholder="e.g. Madurai Palace SO (625001)"
                            className="w-full text-xs font-medium px-3.5 py-2.5 rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#990000] focus:border-transparent transition"
                        />
                        <p className="text-[11px] text-slate-400">
                            Designated Booking Office (e.g. <strong>Madurai Palace SO - PIN 625001</strong>).
                        </p>
                    </div>

                    <div className="space-y-1.5">
                        <label className="text-xs font-bold text-slate-700">Pickup / Drop-off Office ID</label>
                        <input
                            type="text"
                            required
                            inputMode="numeric"
                            pattern="[0-9]{8}"
                            value={pickupOfficeId}
                            onChange={(e) => setPickupOfficeId(e.target.value.replace(/\D/g, '').slice(0, 8))}
                            placeholder="8-digit office ID from pincode API"
                            className="w-full text-xs font-medium px-3.5 py-2.5 rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#990000]"
                        />
                    </div>

                    <div className="space-y-1.5">
                        <label className="text-xs font-bold text-slate-700">Booking Office PIN</label>
                        <input
                            type="text"
                            required
                            inputMode="numeric"
                            pattern="[0-9]{6}"
                            maxLength={6}
                            value={bookingOfficePin}
                            onChange={(e) => setBookingOfficePin(e.target.value.replace(/\D/g, '').slice(0, 6))}
                            placeholder="6-digit booking office PIN"
                            className="w-full text-xs font-medium px-3.5 py-2.5 rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#990000]"
                        />
                    </div>

                    <div className="space-y-1.5">
                        <label className="text-xs font-bold text-slate-700">Assigned Barcode Prefix</label>
                        <input
                            type="text"
                            required
                            pattern="[A-Za-z]{2}"
                            maxLength={2}
                            value={barcodePrefix}
                            onChange={(e) => setBarcodePrefix(e.target.value.replace(/[^A-Za-z]/g, '').toUpperCase())}
                            placeholder="e.g. CT"
                            className="w-full text-xs font-medium px-3.5 py-2.5 rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#990000]"
                        />
                        <p className="text-[11px] text-slate-400">Use only the two-letter series assigned by India Post.</p>
                    </div>

                    <div className="space-y-1.5">
                        <label className="text-xs font-bold text-slate-700">Business Parcel Label Service Type</label>
                        <input
                            type="text"
                            value={bpLabelServiceType}
                            onChange={(e) => setBpLabelServiceType(e.target.value)}
                            placeholder="Business Parcel"
                            className="w-full text-xs font-medium px-3.5 py-2.5 rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-[#990000]"
                        />
                        <p className="text-[11px] text-slate-400">
                            Label service code for BUSINESS_PARCEL (Default: <strong>Business Parcel</strong>; never silently mapped to SP).
                        </p>
                    </div>
                </div>

                <div className="rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-xs text-emerald-800">
                    <strong>Live endpoint:</strong> https://app.indiapost.gov.in/beextcustomer
                </div>

                {/* SUBMIT BUTTON */}
                <div className="pt-2 flex items-center justify-end gap-3 border-t border-slate-100">
                    <button
                        type="button"
                        onClick={loadSettings}
                        disabled={loading}
                        className="px-4 py-2 text-xs font-bold text-slate-600 hover:text-slate-800 transition"
                    >
                        Discard Changes
                    </button>

                    <button
                        type="submit"
                        disabled={saving}
                        className="px-5 py-2.5 text-xs font-bold rounded-xl bg-[#990000] hover:bg-[#800000] text-white active:scale-95 transition shadow-sm flex items-center gap-2 cursor-pointer disabled:opacity-50"
                    >
                        {saving ? (
                            <>
                                <IconRefresh className="w-3.5 h-3.5 animate-spin" />
                                <span>Saving Settings...</span>
                            </>
                        ) : (
                            <span>Save India Post Settings</span>
                        )}
                    </button>
                </div>
            </form>

            {/* AUTHORIZED BARCODE ALLOCATION POOL */}
            <div className="bg-white rounded-2xl border border-slate-200/80 shadow-xs p-6 space-y-5">
                <div className="flex flex-wrap items-center justify-between gap-4 border-b border-slate-100 pb-4">
                    <div>
                        <h2 className="text-base font-extrabold text-slate-800">
                            Authorized India Post Barcode Pool
                        </h2>
                        <p className="text-xs text-slate-500">
                            Import barcodes officially supplied by India Post (Customer Self-Service Portal / Booking Office). Barcodes are never randomly generated.
                        </p>
                    </div>
                    <div className="flex items-center gap-2 text-xs font-bold">
                        <span className="rounded-full bg-emerald-50 border border-emerald-200 px-3 py-1 text-emerald-700">
                            Available: {barcodeStats.available}
                        </span>
                        <span className="rounded-full bg-slate-100 border border-slate-200 px-3 py-1 text-slate-700">
                            Used: {barcodeStats.used}
                        </span>
                    </div>
                </div>

                <form onSubmit={handleImportBarcodes} className="space-y-3">
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                        <div className="md:col-span-2">
                            <label className="mb-1 block text-xs font-bold text-slate-700">
                                Paste Authorized India Post Barcodes (one per line, space, or comma-separated)
                            </label>
                            <textarea
                                rows={3}
                                value={importText}
                                onChange={(e) => setImportText(e.target.value)}
                                placeholder={"EY000027272IN\nCT000000014IN"}
                                className="w-full rounded-xl border border-slate-200 px-3.5 py-2 font-mono text-xs uppercase focus:outline-none focus:ring-2 focus:ring-[#990000]"
                            />
                        </div>
                        <div className="flex flex-col justify-between gap-2">
                            <div>
                                <label className="mb-1 block text-xs font-bold text-slate-700">
                                    Allocation Batch Label (Optional)
                                </label>
                                <input
                                    type="text"
                                    value={seriesLabel}
                                    onChange={(e) => setSeriesLabel(e.target.value)}
                                    placeholder="e.g. Madurai BPC Series 1"
                                    className="w-full rounded-xl border border-slate-200 px-3.5 py-2 text-xs focus:outline-none focus:ring-2 focus:ring-[#990000]"
                                />
                            </div>
                            <button
                                type="submit"
                                disabled={importingBarcodes || !importText.trim()}
                                className="w-full rounded-xl bg-[#990000] px-4 py-2.5 text-xs font-bold text-white hover:bg-[#800000] disabled:opacity-50"
                            >
                                {importingBarcodes ? 'Importing Barcodes...' : 'Add to Authorized Pool'}
                            </button>
                        </div>
                    </div>
                </form>

                {barcodePool.length > 0 && (
                    <div className="max-h-56 overflow-auto rounded-xl border border-slate-200">
                        <table className="w-full text-left text-xs">
                            <thead className="sticky top-0 bg-slate-50 text-[11px] font-bold uppercase text-slate-500">
                                <tr>
                                    <th className="p-2.5">Barcode</th>
                                    <th className="p-2.5">Batch Label</th>
                                    <th className="p-2.5">Status</th>
                                    <th className="p-2.5 text-right">Action</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-100">
                                {barcodePool.map((item) => (
                                    <tr key={item.id}>
                                        <td className="p-2.5 font-mono font-bold text-slate-800">{item.barcode_no}</td>
                                        <td className="p-2.5 text-slate-500">{item.series_label || '-'}</td>
                                        <td className="p-2.5">
                                            <span
                                                className={`rounded-full px-2 py-0.5 text-[10px] font-bold ${
                                                    item.status === 'AVAILABLE'
                                                        ? 'bg-emerald-100 text-emerald-700'
                                                        : 'bg-slate-200 text-slate-600'
                                                }`}
                                            >
                                                {item.status}
                                            </span>
                                        </td>
                                        <td className="p-2.5 text-right">
                                            {item.status === 'AVAILABLE' && (
                                                <button
                                                    type="button"
                                                    onClick={() => handleDeleteBarcode(item.id)}
                                                    className="text-xs font-semibold text-rose-600 hover:underline"
                                                >
                                                    Remove
                                                </button>
                                            )}
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>

            {/* OPERATIONAL INFORMATION CARD */}
            <div className="bg-gradient-to-r from-red-50/50 via-white to-amber-50/50 border border-red-100 rounded-2xl p-5 space-y-4">
                <div className="flex items-center gap-2">
                    <div className="w-7 h-7 rounded-lg bg-[#990000] text-white flex items-center justify-center font-bold text-xs shadow-xs">
                        📮
                    </div>
                    <h3 className="text-sm font-black text-slate-800 uppercase tracking-wider">
                        How India Post Logistics Works in Shas ERP
                    </h3>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-xs">
                    <div className="bg-white/80 p-3.5 rounded-xl border border-slate-200/60 shadow-2xs space-y-1">
                        <span className="font-extrabold text-[#990000] block text-[11px] uppercase tracking-wide">
                            1. Speed vs Normal Post
                        </span>
                        <p className="text-slate-600 leading-relaxed">
                            Orders with express delivery or shipping fees automatically select <strong>India Speed Post</strong> (AWB prefix <code>SP...IN</code>). Standard orders use <strong>India Normal Post</strong> (<code>NP...IN</code>).
                        </p>
                    </div>

                    <div className="bg-white/80 p-3.5 rounded-xl border border-slate-200/60 shadow-2xs space-y-1">
                        <span className="font-extrabold text-[#990000] block text-[11px] uppercase tracking-wide">
                            2. 1-Click Order Dispatch
                        </span>
                        <p className="text-slate-600 leading-relaxed">
                            In Orders &amp; Billing, click <strong>"Dispatch via India Post"</strong> individually or in bulk. Consignments are registered immediately in the shipment ledger.
                        </p>
                    </div>

                    <div className="bg-white/80 p-3.5 rounded-xl border border-slate-200/60 shadow-2xs space-y-1">
                        <span className="font-extrabold text-[#990000] block text-[11px] uppercase tracking-wide">
                            3. Official Gov Tracking
                        </span>
                        <p className="text-slate-600 leading-relaxed">
                            Tracking links direct customers straight to <strong>indiapost.gov.in</strong> consignment tracking portal. Copy links with 1-click for WhatsApp or SMS.
                        </p>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default IndiaPostSettings;
