"use client";

import { displayValue, formatDateTime } from "@/lib/display-format";

import { useEffect, useId, useRef } from "react";
import { ExternalLink, RefreshCw, Truck, X } from "lucide-react";
import { useOrderDetail } from "../hooks/use-order-detail";
import { ORDER_PROGRESS_STATUSES, ORDER_STATUS_LABELS as STATUS_LABELS } from "@/lib/order-status";


export function OrderTrackingModal({ orderId, onClose }: {
  orderId: string;
  onClose: () => void;
}) {
  const { order, isLoading, error, refetch } = useOrderDetail(orderId);
  const dialogRef = useRef<HTMLDialogElement>(null);
  const titleId = useId();

  useEffect(() => {
    const dialog = dialogRef.current;
    const previousFocus = document.activeElement;
    dialog?.showModal();
    return () => {
      dialog?.close();
      if (previousFocus instanceof HTMLElement && previousFocus.isConnected) previousFocus.focus();
    };
  }, []);

  return (
    <dialog
      ref={dialogRef}
      aria-labelledby={titleId}
      onCancel={onClose}
      onClick={(event) => { if (event.target === event.currentTarget) onClose(); }}
      className="fixed inset-0 m-auto max-h-[90vh] w-[calc(100%-2rem)] max-w-lg overflow-y-auto rounded-2xl border border-gray-200 bg-white p-0 text-left shadow-2xl backdrop:bg-black/50"
    >
      <div className="flex items-center justify-between border-b border-gray-200 px-6 py-4">
        <div className="flex items-center gap-3">
          <Truck className="h-5 w-5 text-blue-600" />
          <div>
            <h2 id={titleId} className="text-lg font-semibold text-gray-900">Track Order</h2>
            {order && <p className="text-xs text-gray-500">{displayValue(order.orderNumber)}</p>}
          </div>
        </div>
        <button type="button" onClick={onClose} aria-label="Close tracking details" className="rounded-lg p-2 text-gray-500 hover:bg-gray-100">
          <X className="h-5 w-5" />
        </button>
      </div>
      <div className="space-y-5 px-6 py-5" aria-busy={isLoading}>
        {isLoading && !order && <p role="status" className="text-sm text-gray-500">Loading tracking details...</p>}
        {error && <p role="alert" className="rounded-lg bg-red-50 p-3 text-sm text-red-700">{error}</p>}
        {!isLoading && !error && !order && <p className="text-sm text-gray-500">Order not found.</p>}
        {order && !error && (
          <>
            <div>
              <p className="text-xs text-gray-500">Current status</p>
              <p className="mt-1 font-semibold text-gray-900">{STATUS_LABELS[order.status]}</p>
              <ol aria-label="Order progress" className="mt-3 grid grid-cols-2 gap-2 sm:grid-cols-4">
                {ORDER_PROGRESS_STATUSES.map((status, index) => (
                  <li key={status} aria-current={status === order.status ? "step" : undefined}
                    className={`rounded-lg border px-2 py-2 text-center text-xs ${index <= ORDER_PROGRESS_STATUSES.findIndex((step) => step === order.status) ? "border-blue-200 bg-blue-50 text-blue-700" : "border-gray-200 text-gray-500"}`}>
                    {STATUS_LABELS[status]}
                  </li>
                ))}
              </ol>
            </div>
            <dl className="space-y-4 rounded-lg bg-gray-50 p-4">
              <div><dt className="text-xs text-gray-500">Courier</dt><dd className="break-words text-sm font-medium text-gray-900">{displayValue(order.courierName)}</dd></div>
              <div><dt className="text-xs text-gray-500">Tracking ID</dt><dd className="break-all text-sm font-medium text-gray-900">{displayValue(order.trackingId)}</dd></div>
              <div>
                <dt className="text-xs text-gray-500">Tracking link</dt>
                <dd className="break-all text-sm">
                  {order.trackingUrl && /^https?:\/\//i.test(order.trackingUrl) ? (
                    <a href={order.trackingUrl} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-blue-700 underline">
                      Open courier tracking <ExternalLink className="h-3.5 w-3.5 shrink-0" />
                    </a>
                  ) : <span className="text-gray-700">{displayValue(order.trackingUrl)}</span>}
                </dd>
              </div>
            </dl>
            {!order.courierName && !order.trackingId && !order.trackingUrl && (
              <p className="text-sm text-gray-500">Tracking details will appear once added by the delivery team.</p>
            )}
            <p className="text-xs text-gray-500">Order last updated: {formatDateTime(order.updatedAt)}</p>
          </>
        )}
        <p className="text-xs text-gray-500">Shows updates entered by the delivery team. Refreshes automatically every 30 seconds while this tab is visible.</p>
      </div>
      <div className="flex justify-end gap-2 border-t border-gray-200 px-6 py-4">
        <button type="button" disabled={isLoading} onClick={() => void refetch()} className="inline-flex items-center gap-2 rounded-lg border border-gray-200 px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 disabled:opacity-50">
          <RefreshCw className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`} /> Refresh
        </button>
        <button type="button" onClick={onClose} className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700">Close</button>
      </div>
    </dialog>
  );
}
