"use client";

interface TimelineEvent {
  _id: string;
  eventType: string;
  source: string;
  fromStatus?: string;
  toStatus?: string;
  createdAt: number;
}

interface Props {
  events: TimelineEvent[];
}

const STATUS_LABELS: Record<string, string> = {
  pending: "Pending",
  confirmed: "Confirmed",
  processing: "Processing",
  shipped: "Shipped",
  delivered: "Delivered",
  cancelled: "Cancelled",
  refunded: "Refunded",
};

function getEventLabel(event: TimelineEvent): string {
  switch (event.eventType) {
    case "status_change":
      if (event.toStatus) {
        return `Order ${STATUS_LABELS[event.toStatus] ?? event.toStatus}`;
      }
      return "Status updated";
    case "customer_cancel":
      return "Order cancelled by you";
    case "return_requested":
      return "Return requested";
    case "return_received":
      return "Return received";
    case "refund":
      return "Refund issued";
    case "tracking_update":
      return "Tracking updated";
    case "label_created":
      return "Shipping label created";
    default:
      return "Order updated";
  }
}

function getEventDescription(event: TimelineEvent): string | null {
  if (
    event.eventType === "status_change" &&
    event.fromStatus &&
    event.toStatus
  ) {
    return `${STATUS_LABELS[event.fromStatus] ?? event.fromStatus} → ${STATUS_LABELS[event.toStatus] ?? event.toStatus}`;
  }
  if (event.eventType === "return_requested") {
    return "Our team will review and contact you with next steps.";
  }
  if (event.eventType === "refund") {
    return "Your refund has been processed. Allow 5–10 business days.";
  }
  return null;
}

function getDotColor(eventType: string): string {
  switch (eventType) {
    case "customer_cancel":
      return "bg-[#f2705a]";
    case "return_requested":
    case "return_received":
      return "bg-[#f4a13a]";
    case "refund":
      return "bg-green-500";
    default:
      return "bg-[#38a99f]";
  }
}

function formatTimestamp(ts: number): string {
  return new Intl.DateTimeFormat("en-GB", {
    day: "numeric",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  }).format(new Date(ts));
}

export function OrderTimeline({ events }: Props) {
  if (events.length === 0) return null;

  return (
    <section className="rounded-xl border border-gray-200 bg-white p-6">
      <h2 className="mb-4 text-sm font-semibold text-[#1a2e2d]">
        Order Timeline
      </h2>
      <ol className="relative space-y-0">
        {events.map((event, index) => {
          const isLast = index === events.length - 1;
          return (
            <li key={event._id} className="relative flex gap-4">
              {/* Vertical line + dot */}
              <div className="flex flex-col items-center">
                <div
                  className={`mt-1 size-2.5 shrink-0 rounded-full ${getDotColor(event.eventType)}`}
                />
                {!isLast && (
                  <div className="mt-1 w-px flex-1 bg-gray-200" />
                )}
              </div>

              {/* Content */}
              <div className={`pb-6 ${isLast ? "pb-0" : ""}`}>
                <p className="text-sm font-medium text-[#1a2e2d]">
                  {getEventLabel(event)}
                </p>
                {getEventDescription(event) && (
                  <p className="mt-0.5 text-xs text-gray-500">
                    {getEventDescription(event)}
                  </p>
                )}
                <time className="mt-1 block text-xs text-gray-400">
                  {formatTimestamp(event.createdAt)}
                </time>
              </div>
            </li>
          );
        })}
      </ol>
    </section>
  );
}
