import React, { useEffect, useState } from "react";
import IconX from "../../components/Icon/IconX";
import IconCalendar from "../../components/Icon/IconCalendar";
import IconShoppingBag from "../../components/Icon/IconShoppingBag";
import Offcanvas from "../../components/Offcanvas";
import IconDownload from "../../components/Icon/IconDownload";
import IconClock from "../../components/Icon/IconClock";
import IconTruck from "../../components/Icon/IconTruck";
import IconCopy from "../../components/Icon/IconCopy";
import IconLink from "../../components/Icon/IconLink";
import IconRefresh from "../../components/Icon/IconRefresh";
import IconPrinter from "../../components/Icon/IconPrinter";
import { generatePackingSlipPDF } from "../../utils/generatePackingSlipPDF";
import { shipmentApi } from "../../api/shipmentApi";
import { indiaPostApi } from "../../api/indiaPostApi";
import Swal from "sweetalert2";

interface Props {
  isOpen: boolean;
  onClose: () => void;
  customer: any;
  onRefresh?: () => void;
}

const ViewShipment = ({ isOpen, onClose, customer, onRefresh }: Props) => {
  const [downloading, setDownloading] = useState(false);
  const [syncing, setSyncing] = useState(false);
  const [loadingLabel, setLoadingLabel] = useState(false);
  const [copiedLink, setCopiedLink] = useState(false);
  const [shipmentData, setShipmentData] = useState<any>(customer);

  useEffect(() => {
    if (customer) {
      setShipmentData(customer);
    }
  }, [customer]);

  if (!isOpen || !customer || !shipmentData) return null;

  const o = shipmentData;
  const ipBooking = o.india_post_booking || null;
  const awb = o.tracking || o.awb_code || "-";
  const officialIndiaPostUrl = "https://www.indiapost.gov.in/_layouts/15/dop.portal.tracking/trackconsignment.aspx";
  const portalTrackingUrl = "https://app.indiapost.gov.in/customer-selfservice/bulk-articles-tracking";
  
  // Dedicated Customer Portal Tracking Link hosted on our website
  const trackingLookup = (awb && awb !== '-') ? awb : (o.orderNo || o.order_no || o.shipment_no || '');
  const customerTrackingUrl = typeof window !== 'undefined' && trackingLookup
    ? `${window.location.origin}/track/${encodeURIComponent(trackingLookup.replace(/^#/, ''))}`
    : officialIndiaPostUrl;

  const trackingUrl = customerTrackingUrl;
  const status = o.status || "IN TRANSIT";

  // Determine active timeline step based on status
  const currentStep = (() => {
    switch (status) {
      case "AWAITING PICKUP":
      case "PENDING":
        return 1;
      case "IN TRANSIT":
        return 2;
      case "OUT FOR DELIVERY":
        return 3;
      case "DELIVERED":
        return 4;
      default:
        return 2;
    }
  })();

  const handleCopyTrackingLink = () => {
    if (!customerTrackingUrl) return;
    navigator.clipboard.writeText(customerTrackingUrl);
    setCopiedLink(true);
    setTimeout(() => setCopiedLink(false), 2000);
    Swal.fire({
      icon: "success",
      title: "Customer Tracking Link Copied!",
      html: `
        <div class="text-xs text-left space-y-1">
          <p class="text-slate-600">Send this link to the customer via WhatsApp or SMS:</p>
          <p class="font-mono font-bold text-[#990000] break-all bg-red-50 p-2 rounded-lg border border-red-200">${customerTrackingUrl}</p>
        </div>
      `,
      confirmButtonText: "OK",
      confirmButtonColor: "#990000",
    });
  };

  const handleSyncWithIndiaPost = async () => {
    setSyncing(true);
    try {
      const res = await shipmentApi.trackShipment(o.id || o.shipmentid || o.shipment_no);
      if (res.success && res.data) {
        setShipmentData({ ...res.data, india_post_booking: res.data.india_post_booking || ipBooking });
        if (onRefresh) onRefresh();
        Swal.fire({
          icon: "success",
          title: "India Post Status Synced!",
          text: `Current status is ${res.data.status}`,
          toast: true,
          position: "top-end",
          showConfirmButton: false,
          timer: 2500,
        });
      }
    } catch (err: any) {
      console.error(err);
      Swal.fire({
        icon: "error",
        title: "Sync Error",
        text: err.response?.data?.message || "Could not fetch tracking data from India Post.",
      });
    } finally {
      setSyncing(false);
    }
  };

  const handleOpenLabel = async (printNow = false) => {
    if (!ipBooking?.booking_id) return;
    setLoadingLabel(true);
    try {
      const blobUrl = await indiaPostApi.fetchLabelBlobUrl(ipBooking.booking_id);
      const win = window.open(blobUrl, "_blank");
      if (printNow && win) {
        win.addEventListener("load", () => win.print());
      }
    } catch (err: any) {
      Swal.fire("Label Error", err.response?.data?.message || "Unable to fetch India Post PDF label.", "error");
    } finally {
      setLoadingLabel(false);
    }
  };

  const handleRegenerateLabel = async (size: "A6" | "A7") => {
    if (!ipBooking?.booking_id) return;
    setLoadingLabel(true);
    try {
      const res = await indiaPostApi.generateLabel(ipBooking.booking_id, size);
      if (res.success) {
        setShipmentData((prev: any) => ({
          ...prev,
          label_url: res.label_url,
          india_post_booking: { ...ipBooking, label_size: size, label_url: res.label_url, status: "LABEL_GENERATED" },
        }));
        if (onRefresh) onRefresh();
        Swal.fire({
          icon: "success",
          title: `${size} Shipping Label Ready`,
          toast: true,
          position: "top-end",
          showConfirmButton: false,
          timer: 2000,
        });
      }
    } catch (err: any) {
      Swal.fire("Label Generation Failed", err.response?.data?.message || "Could not regenerate label.", "error");
    } finally {
      setLoadingLabel(false);
    }
  };

  const handleUpdateStage = async (newStatus: string) => {
    try {
      const res = await shipmentApi.updateShipmentStatus(o.id || o.shipmentid || o.shipment_no, newStatus);
      if (res.success && res.data) {
        setShipmentData(res.data);
        if (onRefresh) onRefresh();
        Swal.fire({
          icon: "success",
          title: "Delivery Stage Updated",
          text: `Status updated to ${newStatus}`,
          toast: true,
          position: "top-end",
          showConfirmButton: false,
          timer: 2000,
        });
      }
    } catch (err: any) {
      console.error(err);
      Swal.fire({
        icon: "error",
        title: "Update Failed",
        text: err.response?.data?.message || "Failed to update delivery stage.",
      });
    }
  };

  const header = (
    <div
      style={{
        margin: "-18px -20px -18px",
        borderRadius: "16px 16px 0 0",
        overflow: "hidden",
      }}
    >
      <div className="flex justify-between bg-[#5B1F00] items-center p-4">
        <div className="flex items-center gap-2.5">
          <span className="p-1 rounded-lg bg-orange-500/20 text-orange-300">
            <IconTruck className="w-5 h-5" />
          </span>
          <div>
            <span className="text-[13px] text-orange-200 font-extrabold uppercase tracking-wider block">
              SHIPMENT &amp; LOGISTICS
            </span>
            <span className="text-[11px] text-orange-200 font-mono">
              {o.shipmentid || o.shipment_no}
            </span>
          </div>
        </div>

        <button
          onClick={onClose}
          className="p-1.5 rounded-full hover:bg-white/10 text-amber-200 hover:text-white transition-all cursor-pointer"
        >
          <IconX />
        </button>
      </div>
    </div>
  );

  const footer = (
    <div className="p-4 bg-slate-50 flex justify-between items-center border-t border-slate-200/80">
      <button
        disabled={downloading}
        onClick={async () => {
          setDownloading(true);
          const rawPhones: string[] = [];
          if (o.customer_phone) rawPhones.push(String(o.customer_phone));
          if (o.customer_phone2 || o.phone2 || o.alt_phone) rawPhones.push(String(o.customer_phone2 || o.phone2 || o.alt_phone));
          if (Array.isArray(o.phones)) {
            o.phones.forEach((p: any) => { if (p) rawPhones.push(String(p)); });
          }
          const phones: string[] = [];
          rawPhones.forEach((p) => {
            p.split(/[,/\n]+/).map(s => s.trim()).filter(Boolean).forEach(num => {
              if (!phones.includes(num)) phones.push(num);
            });
          });

          await generatePackingSlipPDF({
            shipmentId: o.shipmentid || o.shipment_no || o.id,
            orderNumber: o.orderNo || o.order_no,
            orderDate: o.orderDate || o.date || new Date().toLocaleDateString("en-IN", { day: "2-digit", month: "short", year: "numeric" }),
            shippingMethod: o.courier || o.courier_name || "Shiprocket",
            to: {
              name: o.customer || o.customer_name,
              address: o.address || o.shipping_address,
              city: o.city || o.shipping_city,
              state: o.state || o.shipping_state,
              pincode: o.pincode || o.shipping_pincode,
              phones: phones.length > 0 ? phones : (o.phones || []),
            },
            items: (o.items || []).map((it: any) => ({
              product: it.product_name || it.product || it.name || "Jewellery Product",
              qty: Number(it.qty) || 1,
              color: it.color || it.selected_color || it.variant,
              chainType: it.chain_type || it.chainType,
              chainQty: it.chain_qty || it.chainQty,
              addons: it.addons,
              options: it.options,
            })),
          });
          setDownloading(false);
        }}
        className="flex gap-2 items-center px-4 py-2 rounded-xl text-xs font-bold bg-white text-slate-800 border border-slate-200 hover:bg-slate-50 transition cursor-pointer shadow-xs disabled:opacity-60"
      >
        {downloading ? (
          <svg className="animate-spin w-3.5 h-3.5" fill="none" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4l3-3-3-3v4a8 8 0 00-8 8h4z" />
          </svg>
        ) : (
          <IconDownload />
        )}
        Packing Slip
      </button>

      <button
        onClick={handleCopyTrackingLink}
        className="flex gap-2 items-center px-4 py-2 rounded-xl text-xs font-bold bg-[#5B1F00] text-amber-200 hover:text-white hover:bg-[#461901] transition cursor-pointer shadow-xs"
      >
        <IconCopy className="w-3.5 h-3.5" />
        {copiedLink ? "Tracking Link Copied!" : "Copy Tracking Link"}
      </button>
    </div>
  );

  return (
    <Offcanvas
      isOpen={isOpen}
      onClose={onClose}
      width={672}
      header={header}
      footer={footer}
    >
      <div className="p-1 space-y-4 overflow-y-auto">

        {/* SHIPMENT COURIER & AWB CARD */}
        <div className="border border-slate-200/80 rounded-2xl p-4 bg-gradient-to-r from-red-50/50 via-white to-amber-50/40 shadow-xs space-y-3">
          <div className="flex justify-between items-start">
            <div>
              <span className="text-xs font-bold text-[#990000] uppercase tracking-wider flex items-center gap-1.5">
                <IconTruck className="w-4 h-4" />
                {o.courier || o.courier_name || "India Post"}
              </span>
              <p className="text-base font-extrabold text-slate-900 mt-1 font-mono">
                AWB: {awb}
              </p>
            </div>

            <div className="flex flex-col items-end gap-1.5">
              <span className="text-[10px] px-2.5 py-1 rounded-full border font-extrabold uppercase bg-amber-50 text-amber-800 border-amber-200 shadow-2xs">
                {status}
              </span>

              <button
                type="button"
                onClick={handleSyncWithIndiaPost}
                disabled={syncing}
                className="inline-flex items-center gap-1 text-[11px] font-bold text-[#990000] hover:text-red-900 hover:underline cursor-pointer"
              >
                <IconRefresh className={`w-3.5 h-3.5 ${syncing ? 'animate-spin' : ''}`} />
                <span>{syncing ? 'Syncing...' : 'Sync India Post'}</span>
              </button>
            </div>
          </div>

          {/* ACTION BUTTONS: COPY TRACKING & OPEN TRACKING */}
          <div className="flex flex-wrap items-center gap-2 pt-2 border-t border-slate-200/60">
            <button
              type="button"
              onClick={handleCopyTrackingLink}
              className="flex-1 min-w-[140px] flex items-center justify-center gap-1.5 py-2 px-3 text-xs font-bold rounded-xl border border-blue-200 bg-blue-50 text-blue-700 hover:bg-blue-100 transition cursor-pointer shadow-xs"
            >
              <IconCopy className="w-3.5 h-3.5" />
              <span>{copiedLink ? "Link Copied!" : "Copy Tracking Link"}</span>
            </button>

            {trackingUrl && (
              <button
                type="button"
                onClick={() => {
                  if (awb && awb !== "-") {
                    navigator.clipboard.writeText(awb);
                  }
                  Swal.fire({
                    icon: "info",
                    title: "Consignment Copied!",
                    text: `AWB ${awb} copied to clipboard. Opening official India Post tracking portal...`,
                    toast: true,
                    position: "top-end",
                    showConfirmButton: false,
                    timer: 2500,
                  });
                  window.open(officialIndiaPostUrl, "_blank");
                }}
                className="flex items-center justify-center gap-1.5 py-2 px-3.5 text-xs font-bold rounded-xl border border-red-300 bg-red-50 hover:bg-red-100 text-[#990000] transition cursor-pointer shadow-xs"
                title="Open official India Post tracking portal"
              >
                <IconLink className="w-3.5 h-3.5 text-[#990000]" />
                <span>Track on India Post ↗</span>
              </button>
            )}
          </div>
        </div>

        {/* KPI CARDS */}
        <div className="grid grid-cols-2 gap-3">
          <div className="border border-slate-200 rounded-xl p-3 text-xs bg-white shadow-2xs">
            <p className="text-slate-500 font-bold flex items-center gap-1">
              <IconCalendar />
              ESTIMATED DELIVERY
            </p>
            <p className="text-base font-extrabold text-slate-800 mt-1">{o.delivery || o.estimated_delivery || "In 3-4 Days"}</p>
          </div>

          <div className="border border-slate-200 rounded-xl p-3 text-xs bg-white shadow-2xs">
            <p className="text-slate-500 font-bold flex items-center gap-1">
              <IconShoppingBag />
              RELATED ORDER
            </p>
            <p className="text-base font-extrabold text-slate-800 font-mono mt-1">{o.orderNo || o.order_no}</p>
          </div>
        </div>

        {/* CUSTOMER & ADDRESS SECTION */}
        <div className="border border-slate-200 rounded-xl p-3.5 text-xs bg-white shadow-2xs space-y-1.5">
          <p className="text-slate-500 font-bold flex items-center gap-1 uppercase tracking-wider text-[10px]">
            CUSTOMER &amp; DELIVERY DESTINATION
          </p>

          <div>
            <span className="text-sm font-bold text-slate-900 block">
              {o.customer || o.customer_name}
            </span>
            <p className="text-xs font-medium text-slate-600 mt-0.5 whitespace-pre-line leading-relaxed">
              {o.address || o.shipping_address || "Address on file"}
            </p>
          </div>
        </div>

        {/* INDIA POST SHIPPING LABEL & BOOKING AUDIT */}
        {ipBooking && (
          <div className="border border-amber-200/80 rounded-2xl p-4 bg-[#FAF6F0] space-y-3 shadow-2xs">
            <div className="flex flex-wrap items-center justify-between gap-2">
              <div>
                <h3 className="text-xs font-extrabold uppercase text-[#8B3E1F] tracking-wider">
                  Official India Post Label &amp; Tariff
                </h3>
                <p className="text-[11px] text-slate-600 mt-0.5">
                  Service: <span className="font-mono font-bold">{ipBooking.article_type}</span> ({ipBooking.shape_of_article || 'NROL'})
                  {ipBooking.final_amount ? ` • Tariff: ₹${Number(ipBooking.final_amount).toFixed(2)}` : ''}
                  {ipBooking.batch_id ? ` • Batch: ${ipBooking.batch_id}` : ''}
                </p>
              </div>
              <span className="text-[10px] font-bold px-2.5 py-0.5 rounded-full bg-white border border-amber-300 text-amber-900">
                {String(ipBooking.status || '').replace(/_/g, ' ')}
              </span>
            </div>

            {['API_ACCEPTED', 'LABEL_GENERATED', 'AWAITING_POSTAL_CONFIRMATION'].includes(ipBooking.status) && (
              <p className="text-[11px] text-amber-900 bg-amber-100/70 border border-amber-200 rounded-lg px-2.5 py-1.5 leading-relaxed">
                <strong>Awaiting Physical Postal Scan:</strong> Data is accepted by India Post API and the label is printable. Live scan events begin once accepted at the booking Post Office counter.
              </p>
            )}

            <div className="flex flex-wrap items-center justify-between gap-2">
              <div className="flex items-center gap-1.5">
                {(['A6', 'A7'] as const).map((sz) => (
                  <button
                    key={sz}
                    type="button"
                    disabled={loadingLabel}
                    onClick={() => handleRegenerateLabel(sz)}
                    className={`px-2.5 py-1 rounded-lg text-[11px] font-bold border transition ${
                      (ipBooking.label_size || 'A6') === sz
                        ? 'bg-[#8B3E1F] text-white border-[#8B3E1F]'
                        : 'bg-white text-slate-700 border-slate-300 hover:bg-slate-50'
                    }`}
                  >
                    {sz} Label
                  </button>
                ))}
              </div>
              <div className="flex items-center gap-2">
                <button
                  type="button"
                  disabled={loadingLabel}
                  onClick={() => handleOpenLabel(false)}
                  className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-slate-300 bg-white text-slate-700 text-xs font-bold hover:bg-slate-50"
                >
                  <IconDownload className="w-3.5 h-3.5" />
                  Preview PDF
                </button>
                <button
                  type="button"
                  disabled={loadingLabel}
                  onClick={() => handleOpenLabel(true)}
                  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]"
                >
                  <IconPrinter className="w-3.5 h-3.5" />
                  Print Label
                </button>
              </div>
            </div>
          </div>
        )}

        {/* TRACKING TIMELINE SECTION */}
        <div className="border border-slate-200 rounded-2xl p-4 bg-white shadow-2xs space-y-3">
          <div className="flex justify-between items-center pb-2 border-b border-slate-100">
            <div>
              <h3 className="text-xs font-extrabold uppercase text-slate-800 tracking-wider flex items-center gap-1.5">
                <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></span>
                LIVE INDIA POST TRACKING TIMELINE
              </h3>
              <p className="text-[11px] text-slate-500 mt-0.5">
                Real-time scanning history and sorting milestones from Department of Posts
              </p>
            </div>
            <span className="text-[10px] font-mono font-bold text-[#990000] bg-red-50 px-2 py-0.5 rounded border border-red-200 shrink-0">
              {Array.isArray(o.tracking_data) && o.tracking_data.length > 0
                ? `${o.tracking_data.length} Scans Logged`
                : 'Synced with India Post'}
            </span>
          </div>

          {/* Detailed Transit Scans or Stage Overview */}
          <div className="space-y-3 pt-1">
            {Array.isArray(o.tracking_data) && o.tracking_data.length > 0 ? (
              <div className="relative pl-6 space-y-4 before:content-[''] before:absolute before:left-2.5 before:top-2 before:bottom-2 before:w-0.5 before:bg-slate-200">
                {o.tracking_data.map((act: any, idx: number) => {
                  const isLatest = idx === o.tracking_data.length - 1;
                  return (
                    <div key={idx} className="relative group">
                      {/* Timeline dot */}
                      <div
                        className={`absolute -left-6 top-1 w-3.5 h-3.5 rounded-full border-2 flex items-center justify-center transition ${
                          isLatest
                            ? 'bg-[#990000] border-red-200 shadow-xs ring-4 ring-red-100'
                            : 'bg-emerald-500 border-white shadow-2xs'
                        }`}
                      />

                      <div className="bg-slate-50/80 hover:bg-slate-50 border border-slate-200/80 rounded-xl p-3 transition space-y-1">
                        <div className="flex items-center justify-between gap-2 flex-wrap">
                          {act.location ? (
                            <span className="inline-flex items-center gap-1 text-[11px] font-extrabold text-[#990000] bg-red-100/70 px-2 py-0.5 rounded-md font-mono">
                              📍 {act.location}
                            </span>
                          ) : (
                            <span className="text-[11px] font-bold text-slate-700">Postal Hub</span>
                          )}

                          <span className="text-[10px] font-mono text-slate-500 font-medium">
                            {act.date}
                          </span>
                        </div>

                        <p className="text-xs font-bold text-slate-900 pt-0.5">
                          {act.status}
                        </p>

                        {act.activity && (
                          <p className="text-[11px] text-slate-600 leading-relaxed">
                            {act.activity}
                          </p>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            ) : (
              /* Completely dynamic state if no scans logged yet */
              <div className="py-6 px-4 text-center bg-slate-50 border border-dashed border-slate-200 rounded-xl space-y-2.5">
                <div className="w-9 h-9 rounded-full bg-red-100 text-[#990000] flex items-center justify-center mx-auto text-base font-bold shadow-xs">
                  📮
                </div>
                <div className="space-y-0.5">
                  <p className="text-xs font-bold text-slate-800">
                    Awaiting First Post Office Scan
                  </p>
                  <p className="text-[11px] text-slate-500 max-w-sm mx-auto leading-relaxed">
                    Transit logs and physical post office locations will be dynamically recorded as India Post scans the barcode <strong>{awb}</strong>.
                  </p>
                </div>
                <button
                  type="button"
                  onClick={handleSyncWithIndiaPost}
                  disabled={syncing}
                  className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold text-[#990000] bg-red-50 hover:bg-red-100 border border-red-200 rounded-lg transition cursor-pointer"
                >
                  <IconRefresh className={`w-3.5 h-3.5 ${syncing ? 'animate-spin' : ''}`} />
                  <span>{syncing ? 'Fetching...' : 'Check for Live Scans Now'}</span>
                </button>
              </div>
            )}
          </div>
        </div>

        {/* AUTOMATED INDIA POST STATUS SYNCHRONIZATION */}
        <div className="p-4 bg-gradient-to-r from-red-50/70 via-amber-50/30 to-white border border-red-200/80 rounded-2xl space-y-3 shadow-2xs">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-xs font-black uppercase text-[#990000] tracking-wider flex items-center gap-1.5">
                <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></span>
                Automated India Post Synchronization
              </h3>
              <p className="text-[11px] text-slate-600 mt-0.5">
                Pulls real-time scan locations and events from Department of Posts. When marked delivered, customer is notified.
              </p>
            </div>
          </div>

          <button
            type="button"
            onClick={handleSyncWithIndiaPost}
            disabled={syncing}
            className="w-full flex items-center justify-center gap-2 py-2.5 px-4 rounded-xl text-xs font-bold text-white bg-[#990000] hover:bg-[#800000] active:scale-95 transition shadow-xs cursor-pointer disabled:opacity-50"
          >
            <IconRefresh className={`w-4 h-4 ${syncing ? 'animate-spin' : ''}`} />
            <span>{syncing ? 'Syncing with India Post...' : 'Sync Live Status from India Post'}</span>
          </button>

          {/* Optional Emergency Manual Override & Add Milestone */}
          <details className="text-[11px] text-slate-500 pt-1 border-t border-red-100">
            <summary className="cursor-pointer hover:text-slate-800 font-semibold select-none flex items-center justify-between">
              <span>Post Office Milestone Controls (Admin Updates)</span>
              <span className="text-[10px] text-slate-400">Click to expand</span>
            </summary>
            
            <div className="pt-3 space-y-2.5">
              <span className="text-[10px] uppercase font-bold text-slate-400 block">Quick Stage Change:</span>
              <div className="grid grid-cols-2 gap-1.5">
                {['AWAITING PICKUP', 'IN TRANSIT', 'OUT FOR DELIVERY', 'DELIVERED'].map((st) => (
                  <button
                    key={st}
                    type="button"
                    onClick={() => handleUpdateStage(st)}
                    className={`px-2.5 py-1.5 rounded-lg text-[10px] font-bold border transition ${
                      status === st
                        ? 'bg-slate-800 text-white border-slate-800'
                        : 'bg-white text-slate-600 border-slate-200 hover:bg-slate-100'
                    }`}
                  >
                    {st}
                  </button>
                ))}
              </div>

              {/* Add Custom Location Milestone */}
              <div className="pt-2 border-t border-slate-100">
                <button
                  type="button"
                  onClick={async () => {
                    const { value: formValues } = await Swal.fire({
                      title: 'Add Postal Scan Milestone',
                      html: `
                        <div class="space-y-2 text-left text-xs">
                          <div>
                            <label class="font-bold text-slate-700 block mb-1">Post Office / Location</label>
                            <input id="swal-location" class="swal2-input !m-0 !w-full !text-xs !h-9" placeholder="e.g. Madurai Palace SO, Madurai Rs TMO, Madurai PH" value="${o.city || 'Madurai Hub'}">
                          </div>
                          <div class="pt-2">
                            <label class="font-bold text-slate-700 block mb-1">Postal Stage / Status</label>
                            <select id="swal-stage" class="swal2-select !m-0 !w-full !text-xs !h-9">
                              <option value="IN TRANSIT">In Transit / Sorting</option>
                              <option value="OUT FOR DELIVERY">Out for Delivery</option>
                              <option value="DELIVERED">Delivered</option>
                              <option value="AWAITING PICKUP">Awaiting Pickup</option>
                            </select>
                          </div>
                          <div class="pt-2">
                            <label class="font-bold text-slate-700 block mb-1">Activity Description</label>
                            <input id="swal-activity" class="swal2-input !m-0 !w-full !text-xs !h-9" placeholder="e.g. Bag Received for Forwarding, Item Dispatched">
                          </div>
                        </div>
                      `,
                      focusConfirm: false,
                      showCancelButton: true,
                      confirmButtonText: 'Add Milestone',
                      confirmButtonColor: '#990000',
                      preConfirm: () => {
                        const loc = (document.getElementById('swal-location') as HTMLInputElement)?.value;
                        const stg = (document.getElementById('swal-stage') as HTMLSelectElement)?.value;
                        const act = (document.getElementById('swal-activity') as HTMLInputElement)?.value;
                        if (!loc) {
                          Swal.showValidationMessage('Please enter a Post Office location');
                          return null;
                        }
                        return { location: loc, status: stg, activity: act };
                      }
                    });

                    if (formValues) {
                      try {
                        const res = await shipmentApi.updateShipmentStatus(
                          o.id || o.shipmentid || o.shipment_no,
                          formValues.status,
                          { location: formValues.location, activity: formValues.activity }
                        );
                        if (res.success && res.data) {
                          setShipmentData(res.data);
                          if (onRefresh) onRefresh();
                          Swal.fire({
                            icon: 'success',
                            title: 'Milestone Added!',
                            text: `Added scan for ${formValues.location}`,
                            toast: true,
                            position: 'top-end',
                            showConfirmButton: false,
                            timer: 2000,
                          });
                        }
                      } catch (err: any) {
                        Swal.fire({
                          icon: 'error',
                          title: 'Failed',
                          text: err.response?.data?.message || 'Could not add milestone',
                        });
                      }
                    }
                  }}
                  className="w-full py-1.5 px-3 rounded-lg border border-dashed border-[#990000] text-[#990000] hover:bg-red-50 text-[10px] font-bold transition flex items-center justify-center gap-1 cursor-pointer"
                >
                  <span>+ Add Exact Location / Post Office Milestone</span>
                </button>
              </div>
            </div>
          </details>
        </div>

      </div>
    </Offcanvas>
  );
};

export default ViewShipment;
