"use client";

import { use, useEffect, useState } from "react";

import Link from "next/link";

import { Clock, MapPin, Package, Ticket } from "lucide-react";

import { OrderTicket } from "@/components/order-ticket/order-ticket";
import { StageBadge } from "@/components/order-ticket/stage-badge";
import { APP_CONFIG } from "@/config/app-config";
import { useT } from "@/lib/i18n";
import { STAGE_LABELS, type Order } from "@/lib/order/types";
import { useOrdersStore } from "@/stores/orders/orders-store";

const CUSTOMER_SAFE_STAGES = [
  "confirmed",
  "held_before_kitchen",
  "sent_to_kitchen",
  "preparing",
  "ready",
  "assigned",
  "out_for_delivery",
  "address_not_found",
  "completed",
] as const;

const CUSTOMER_STAGE_MESSAGES: Record<string, string> = {
  confirmed: "Your order has been received and confirmed.",
  held_before_kitchen: "Your order is confirmed and will be sent to the kitchen shortly.",
  sent_to_kitchen: "Your order is in the kitchen.",
  preparing: "The kitchen is preparing your order.",
  ready: "Your order is ready!",
  assigned: "Your order is packed and assigned.",
  out_for_delivery: "Your order is on its way to you!",
  address_not_found: "Our driver couldn't find the address — they will call you shortly.",
  completed: "Your order has been delivered. Thank you!",
};

export default function TrackOrderPage({ params }: { params: Promise<{ orderId: string }> }) {
  const { orderId } = use(params);
  const t = useT();

  // Read from the store (same data as staff see)
  const orders = useOrdersStore((s) => s.orders);
  const order = orders.find((o) => o.id === orderId);

  if (!order) {
    return (
      <div className="flex min-h-screen flex-col items-center justify-center gap-4 p-6">
        <Package className="size-12 text-muted-foreground opacity-40" />
        <h1 className="font-bold text-xl">Order not found</h1>
        <p className="text-muted-foreground text-sm">No order with ID {orderId}</p>
        <Link href="/login" className="text-primary text-sm hover:underline">
          Back to home
        </Link>
      </div>
    );
  }

  const stageMessage = CUSTOMER_STAGE_MESSAGES[order.stage] ?? "Your order is being processed.";

  // ETA: miles / 20 mph * 60 = minutes. Shown only when out_for_delivery.
  const etaMins =
    order.stage === "out_for_delivery" && order.address?.miles
      ? Math.max(1, Math.round((order.address.miles / 20) * 60))
      : null;

  return (
    <div className="min-h-screen bg-background">
      {/* Top bar */}
      <header className="sticky top-0 z-50 border-b bg-background/80 backdrop-blur-md">
        <div className="mx-auto flex h-14 max-w-lg items-center justify-between px-4">
          <div className="flex items-center gap-2">
            <Ticket className="size-5 shrink-0" />
            <span className="font-bold">{APP_CONFIG.name}</span>
          </div>
          <span className="text-muted-foreground text-xs">Order Tracking</span>
        </div>
      </header>

      <main className="mx-auto max-w-lg px-4 py-6">
        {/* Status banner */}
        <div className="mb-4 rounded-xl border bg-card p-4">
          {etaMins && (
            <div className="mb-3 flex items-center gap-3 rounded-lg bg-violet-600 px-4 py-3 text-white">
              <MapPin className="size-5 shrink-0 animate-bounce" />
              <div>
                <p className="font-bold text-base animate-pulse">{t.track_arriving(etaMins)}</p>
                <p className="text-violet-200 text-xs">{t.track_driver_otw}</p>
              </div>
            </div>
          )}
          <div className="flex items-start justify-between gap-3">
            <div>
              <p className="text-muted-foreground text-xs uppercase tracking-wider">Order Status</p>
              <StageBadge stage={order.stage} type={order.type} className="mt-1" />
              <p className="mt-2 text-sm">{stageMessage}</p>
            </div>
            {order.requestedAt && order.stage !== "completed" && (
              <div className="shrink-0 text-right">
                <p className="text-muted-foreground text-[11px]">Est. ready</p>
                <div className="flex items-center gap-1 font-semibold text-sm">
                  <Clock className="size-3.5" />
                  {new Date(order.requestedAt).toLocaleTimeString("en-GB", {
                    hour: "2-digit",
                    minute: "2-digit",
                  })}
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Lifecycle progress bar */}
        <div className="mb-4 overflow-hidden rounded-xl border bg-card p-4">
          <p className="mb-3 font-medium text-xs uppercase tracking-wider text-muted-foreground">
            Order Progress
          </p>
          <LifecycleBar stage={order.stage} type={order.type} />
        </div>

        {/* Read-only order ticket */}
        <div className="overflow-hidden rounded-xl border">
          <OrderTicket order={order} role="foh" readOnly />
        </div>
      </main>
    </div>
  );
}

function LifecycleBar({ stage, type }: { stage: Order["stage"]; type: Order["type"] }) {
  const stages =
    type === "delivery"
      ? ["confirmed", "sent_to_kitchen", "preparing", "ready", "assigned", "out_for_delivery", "completed"]
      : ["confirmed", "sent_to_kitchen", "preparing", "ready", "assigned", "completed"];

  const currentIdx = stages.indexOf(stage);

  const CUSTOMER_LABELS: Record<string, string> = {
    confirmed: "Confirmed",
    sent_to_kitchen: "In Kitchen",
    preparing: "Cooking",
    ready: "Ready",
    assigned: type === "delivery" ? "Dispatched" : "Ready",
    out_for_delivery: "On the Way",
    completed: "Delivered",
  };

  return (
    <div className="flex items-center gap-1">
      {stages.map((s, idx) => {
        const isPast = idx < currentIdx;
        const isCurrent = idx === currentIdx;
        return (
          <div key={s} className="flex flex-1 flex-col items-center gap-1">
            <div
              className={`h-1.5 w-full rounded-full transition-all ${
                isPast || isCurrent
                  ? "bg-primary"
                  : "bg-muted"
              }`}
            />
            {isCurrent && (
              <span className="text-[9px] font-semibold text-primary text-center leading-tight">
                {CUSTOMER_LABELS[s] ?? s}
              </span>
            )}
          </div>
        );
      })}
    </div>
  );
}
