// @File: src/pages/shop/TrackShipment.tsx
// @Desc: Customer-facing shipment tracking page. Reads the tracking number
//        from the URL (or a search box if none is provided) and renders a
//        vertical timeline of DHL tracking events plus the email
//        notifications that have been sent to the customer about this
//        shipment.
import { useCallback, useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import {
  CheckCircle2,
  Clock,
  Loader2,
  Mail,
  MailCheck,
  MailWarning,
  MapPin,
  Package,
  Search,
  Truck,
  AlertCircle,
} from "lucide-react";
import SiteLayout from "@/components/SiteLayout";
import {
  trackShipment,
  getShipmentNotifications,
  type DhlTrackingResult,
  type PublicShipmentNotification,
} from "@/lib/dhlApi";

function formatTs(ts: string | null | undefined): string {
  if (!ts) return "";
  const d = new Date(ts);
  if (Number.isNaN(d.getTime())) return ts;
  return d.toLocaleString(undefined, {
    year: "numeric",
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

function statusLabel(status: string): string {
  const key = (status || "").toLowerCase();
  if (key.includes("deliver")) return "Delivered";
  if (key.includes("transit")) return "In transit";
  if (key.includes("pickup") || key.includes("picked")) return "Picked up";
  if (key.includes("pending") || key.includes("received")) return "Pending";
  if (key === "unknown" || !key) return "Unknown";
  return status.charAt(0).toUpperCase() + status.slice(1);
}

function statusColor(status: string): string {
  const key = (status || "").toLowerCase();
  if (key.includes("deliver")) return "bg-emerald-100 text-emerald-800 border-emerald-200";
  if (key.includes("transit")) return "bg-sky-100 text-sky-800 border-sky-200";
  if (key.includes("pickup") || key.includes("picked"))
    return "bg-amber-100 text-amber-800 border-amber-200";
  return "bg-slate-100 text-slate-700 border-slate-200";
}

export default function TrackShipment() {
  const params = useParams<{ number?: string }>();
  const navigate = useNavigate();
  const initialNumber = (params.number || "").trim();

  const [input, setInput] = useState(initialNumber);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [result, setResult] = useState<DhlTrackingResult | null>(null);

  const [notifications, setNotifications] = useState<PublicShipmentNotification[]>([]);
  const [notifLoading, setNotifLoading] = useState(false);
  const [notifError, setNotifError] = useState<string | null>(null);

  const load = useCallback(async (trackingNumber: string) => {
    if (!trackingNumber) return;
    setLoading(true);
    setError(null);
    try {
      const data = await trackShipment(trackingNumber);
      setResult(data);
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e));
      setResult(null);
    } finally {
      setLoading(false);
    }
  }, []);

  const loadNotifications = useCallback(async (trackingNumber: string) => {
    if (!trackingNumber) return;
    setNotifLoading(true);
    setNotifError(null);
    try {
      const data = await getShipmentNotifications(trackingNumber);
      setNotifications(data.items || []);
    } catch (e) {
      // Notifications are a secondary detail on the page — surface the
      // error inline but do not block the main tracking timeline.
      setNotifError(e instanceof Error ? e.message : String(e));
      setNotifications([]);
    } finally {
      setNotifLoading(false);
    }
  }, []);

  useEffect(() => {
    if (initialNumber) {
      load(initialNumber);
      loadNotifications(initialNumber);
    }
  }, [initialNumber, load, loadNotifications]);

  const onSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const trimmed = input.trim();
    if (!trimmed) return;
    navigate(`/shop/track/${encodeURIComponent(trimmed)}`);
    load(trimmed);
    loadNotifications(trimmed);
  };

  const lastSentNotification = notifications.find((n) => n.sent) || null;

  return (
    <SiteLayout>
      <div className="min-h-[70vh] bg-slate-50">
        <div className="mx-auto max-w-3xl px-4 py-10 sm:py-14">
          <div className="flex items-center gap-3 mb-6">
            <div className="p-2 rounded-lg bg-[#0b6e3e]/10 text-[#0b6e3e]">
              <Truck className="w-6 h-6" />
            </div>
            <div>
              <h1 className="text-2xl sm:text-3xl font-bold text-slate-900">Track your shipment</h1>
              <p className="text-sm text-slate-600 mt-1">
                Enter your DHL tracking number to see the latest status and delivery timeline.
              </p>
            </div>
          </div>

          <form
            onSubmit={onSubmit}
            className="flex flex-col sm:flex-row gap-2 bg-white rounded-xl border border-slate-200 p-2 shadow-sm"
          >
            <div className="flex items-center flex-1 gap-2 px-3">
              <Search className="w-4 h-4 text-slate-400" />
              <input
                type="text"
                value={input}
                onChange={(e) => setInput(e.target.value)}
                placeholder="e.g. DHL1234567890"
                className="flex-1 bg-transparent py-2 text-sm text-slate-900 placeholder:text-slate-400 focus:outline-none"
                aria-label="Tracking number"
              />
            </div>
            <button
              type="submit"
              disabled={loading || !input.trim()}
              className="inline-flex items-center justify-center gap-2 rounded-lg bg-[#0b6e3e] px-5 py-2 text-sm font-semibold text-white hover:bg-[#0a5f36] disabled:opacity-60"
            >
              {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Search className="w-4 h-4" />}
              Track
            </button>
          </form>

          {error && (
            <div className="mt-6 flex items-start gap-2 rounded-lg border border-rose-200 bg-rose-50 p-4 text-sm text-rose-800">
              <AlertCircle className="w-4 h-4 mt-0.5" />
              <span>{error}</span>
            </div>
          )}

          {result && (
            <div className="mt-6 space-y-6">
              <div className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <div className="flex flex-wrap items-center justify-between gap-3">
                  <div>
                    <div className="flex items-center gap-2 text-slate-500 text-xs uppercase tracking-wide">
                      <Package className="w-3.5 h-3.5" />
                      Tracking number
                    </div>
                    <div className="mt-1 font-mono text-lg text-slate-900">
                      {result.tracking_number}
                    </div>
                  </div>
                  <span
                    className={`inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-semibold ${statusColor(
                      result.status
                    )}`}
                  >
                    <CheckCircle2 className="w-3.5 h-3.5" />
                    {statusLabel(result.status)}
                  </span>
                </div>

                {result.order && (result.order.order_number || result.order.status) && (
                  <div className="mt-4 grid grid-cols-2 sm:grid-cols-4 gap-3 text-sm">
                    {result.order.order_number && (
                      <div>
                        <div className="text-xs text-slate-500">Order</div>
                        <div className="font-medium text-slate-900">
                          #{result.order.order_number}
                        </div>
                      </div>
                    )}
                    {result.order.status && (
                      <div>
                        <div className="text-xs text-slate-500">Order status</div>
                        <div className="font-medium text-slate-900 capitalize">
                          {result.order.status}
                        </div>
                      </div>
                    )}
                    {typeof result.order.total === "number" && (
                      <div>
                        <div className="text-xs text-slate-500">Total</div>
                        <div className="font-medium text-slate-900">
                          {result.order.total.toFixed(2)} {result.order.currency || ""}
                        </div>
                      </div>
                    )}
                  </div>
                )}

                {lastSentNotification && (
                  <div className="mt-4 flex items-start gap-2 rounded-md border border-emerald-200 bg-emerald-50 p-3 text-xs text-emerald-800">
                    <MailCheck className="w-4 h-4 mt-0.5 flex-shrink-0" />
                    <div>
                      <div className="font-medium">
                        We emailed you about the latest status update
                      </div>
                      <div className="text-emerald-700/80 mt-0.5">
                        Sent to {lastSentNotification.recipient_masked || "your email on file"}
                        {lastSentNotification.created_at
                          ? ` · ${formatTs(lastSentNotification.created_at)}`
                          : ""}
                        .
                      </div>
                    </div>
                  </div>
                )}

                {result.stub && (
                  <div className="mt-4 rounded-md bg-amber-50 border border-amber-200 text-amber-800 text-xs p-2">
                    Showing demo tracking data — this shipment has not yet been booked with a live
                    DHL account.
                  </div>
                )}
              </div>

              <div className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <h2 className="text-sm font-semibold text-slate-900 mb-4">Shipment history</h2>
                {result.events.length === 0 ? (
                  <div className="text-sm text-slate-500 flex items-center gap-2">
                    <Clock className="w-4 h-4" />
                    No events yet. Please check back shortly.
                  </div>
                ) : (
                  <ol className="relative border-l-2 border-slate-200 ml-3 space-y-5">
                    {result.events
                      .slice()
                      .reverse()
                      .map((evt, idx) => (
                        <li key={`${evt.timestamp || "t"}-${idx}`} className="ml-5">
                          <span
                            className={`absolute -left-[11px] flex h-5 w-5 items-center justify-center rounded-full border-2 ${
                              idx === 0
                                ? "bg-[#0b6e3e] border-[#0b6e3e] text-white"
                                : "bg-white border-slate-300 text-slate-400"
                            }`}
                            aria-hidden
                          >
                            {idx === 0 ? (
                              <CheckCircle2 className="w-3 h-3" />
                            ) : (
                              <Clock className="w-3 h-3" />
                            )}
                          </span>
                          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1">
                            <div className="font-medium text-slate-900 text-sm">
                              {evt.description}
                            </div>
                            <div className="text-xs text-slate-500">{formatTs(evt.timestamp)}</div>
                          </div>
                          {evt.location && (
                            <div className="mt-1 flex items-center gap-1 text-xs text-slate-500">
                              <MapPin className="w-3 h-3" />
                              {evt.location}
                            </div>
                          )}
                        </li>
                      ))}
                  </ol>
                )}
              </div>

              <div className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
                <div className="flex items-center justify-between mb-4">
                  <h2 className="text-sm font-semibold text-slate-900 flex items-center gap-2">
                    <Mail className="w-4 h-4 text-slate-500" />
                    Email notifications
                  </h2>
                  {notifLoading && <Loader2 className="w-4 h-4 animate-spin text-slate-400" />}
                </div>

                {notifError ? (
                  <div className="text-xs text-slate-500">
                    We couldn&rsquo;t load the notification history right now. Your shipment
                    timeline above is still up to date.
                  </div>
                ) : notifications.length === 0 ? (
                  <div className="text-sm text-slate-500 flex items-center gap-2">
                    <Mail className="w-4 h-4" />
                    No status emails have been sent for this shipment yet. We&rsquo;ll notify
                    you as soon as the status changes.
                  </div>
                ) : (
                  <ol className="relative border-l-2 border-slate-200 ml-3 space-y-5">
                    {notifications.map((n, idx) => {
                      const failed = !n.sent;
                      return (
                        <li key={`${n.created_at || "n"}-${idx}`} className="ml-5">
                          <span
                            className={`absolute -left-[11px] flex h-5 w-5 items-center justify-center rounded-full border-2 ${
                              failed
                                ? "bg-white border-rose-300 text-rose-500"
                                : idx === 0
                                ? "bg-emerald-600 border-emerald-600 text-white"
                                : "bg-white border-emerald-300 text-emerald-500"
                            }`}
                            aria-hidden
                          >
                            {failed ? (
                              <MailWarning className="w-3 h-3" />
                            ) : (
                              <MailCheck className="w-3 h-3" />
                            )}
                          </span>
                          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1">
                            <div className="font-medium text-slate-900 text-sm capitalize">
                              {statusLabel(n.new_status)}
                              {n.previous_status ? (
                                <span className="text-slate-400 font-normal">
                                  {" "}
                                  · from {statusLabel(n.previous_status)}
                                </span>
                              ) : null}
                            </div>
                            <div className="text-xs text-slate-500">
                              {formatTs(n.created_at)}
                            </div>
                          </div>
                          <div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-slate-500">
                            {n.sent ? (
                              <span className="inline-flex items-center gap-1 text-emerald-700">
                                <MailCheck className="w-3 h-3" />
                                Sent{n.recipient_masked ? ` to ${n.recipient_masked}` : ""}
                              </span>
                            ) : (
                              <span className="inline-flex items-center gap-1 text-rose-700">
                                <MailWarning className="w-3 h-3" />
                                Not delivered
                              </span>
                            )}
                            {n.event_description && (
                              <span className="text-slate-500">· {n.event_description}</span>
                            )}
                            {n.event_location && (
                              <span className="inline-flex items-center gap-1">
                                <MapPin className="w-3 h-3" />
                                {n.event_location}
                              </span>
                            )}
                          </div>
                        </li>
                      );
                    })}
                  </ol>
                )}
              </div>
            </div>
          )}
        </div>
      </div>
    </SiteLayout>
  );
}