"use client";

import { useEffect, useState, useCallback } from "react";
import { useTranslations } from "next-intl";
import * as signalR from "@microsoft/signalr";
import { Check } from "lucide-react";
import { fetchOrderTrack, type QrOrderTrack } from "@/lib/api/qr-public";
import { cn } from "@/lib/utils";
import { formatCurrency } from "@/lib/format";
import { Button } from "@/components/ui/button";

type QrOrderTrackProps = {
  orderId: string;
  trackingToken: string;
  primary: string;
  onBack?: () => void;
};

export function QrOrderTrack({ orderId, trackingToken, primary, onBack }: QrOrderTrackProps) {
  const t = useTranslations("qrMenu.tracking");
  const [track, setTrack] = useState<QrOrderTrack | null>(null);
  const [error, setError] = useState(false);

  const load = useCallback(async () => {
    try {
      const data = await fetchOrderTrack(orderId, trackingToken);
      setTrack(data);
      setError(false);
    } catch {
      setError(true);
    }
  }, [orderId, trackingToken]);

  useEffect(() => {
    void load();
    const id = setInterval(() => void load(), 8000);
    return () => clearInterval(id);
  }, [load]);

  useEffect(() => {
    const baseUrl = process.env.NEXT_PUBLIC_API_URL ?? "https://localhost:7208";
    const connection = new signalR.HubConnectionBuilder()
      .withUrl(`${baseUrl}/hubs/guest-order`)
      .withAutomaticReconnect()
      .build();

    connection
      .start()
      .then(() => connection.invoke("JoinOrder", orderId, trackingToken))
      .catch(() => undefined);

    connection.on("OrderTrackUpdated", (payload: QrOrderTrack) => {
      setTrack(payload);
    });

    return () => {
      void connection.stop();
    };
  }, [orderId, trackingToken]);

  if (error) {
    return (
      <p className="p-6 text-center text-sm qr-muted">{t("loadError")}</p>
    );
  }

  if (!track) {
    return (
      <div className="flex justify-center p-8">
        <div
          className="size-8 animate-spin rounded-full border-2 border-t-transparent"
          style={{ borderColor: primary, borderTopColor: "transparent" }}
        />
      </div>
    );
  }

  const statusKey = track.statusLabelKey;

  return (
    <div className="space-y-4 p-4">
      {onBack ? (
        <Button variant="ghost" size="sm" onClick={onBack}>
          ← {t("back")}
        </Button>
      ) : null}
      <div className="rounded-xl border qr-border qr-surface p-4 text-center">
        <p className="text-[11px] uppercase tracking-[0.06em] qr-muted">
          {t("orderNumber")}
        </p>
        <p className="text-lg font-bold qr-text">{track.orderNumber}</p>
        <p className="mt-2 text-sm font-medium" style={{ color: primary }}>
          {t(`status.${statusKey}`)}
        </p>
        <p className="mt-1 text-xs qr-muted">
          {formatCurrency(track.total, "fa-IR")}
          {track.tableNumber ? ` · ${t("table")} ${track.tableNumber}` : ""}
        </p>
      </div>

      <ol className="space-y-0 rounded-xl border qr-border qr-surface p-4">
        {track.steps.map((step) => (
          <li key={step.key} className="flex gap-3 pb-4 last:pb-0">
            <div
              className={cn(
                "flex size-8 shrink-0 items-center justify-center rounded-full border-2",
                step.isComplete ? "border-transparent text-white" : "qr-border qr-fill-muted"
              )}
              style={step.isComplete ? { backgroundColor: primary } : undefined}
            >
              {step.isComplete ? <Check className="size-4" /> : null}
            </div>
            <div className="min-w-0 pt-1">
              <p
                className={cn(
                  "text-sm font-medium",
                  step.isCurrent && "qr-text",
                  !step.isCurrent && !step.isComplete && "qr-muted"
                )}
              >
                {t(`steps.${step.labelKey}`)}
              </p>
              {step.isCurrent ? (
                <p className="text-xs qr-muted">{t("currentStep")}</p>
              ) : null}
            </div>
          </li>
        ))}
      </ol>

      {statusKey === "ready" ? (
        <p
          className="rounded-lg px-3 py-2 text-center text-sm font-medium"
          style={{ backgroundColor: `color-mix(in srgb, ${primary} 12%, #fff)`, color: primary }}
        >
          {t("readyHint")}
        </p>
      ) : null}
    </div>
  );
}
