"use client";

import { useEffect, useState, useCallback } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslations, useLocale } from "next-intl";
import * as signalR from "@microsoft/signalr";
import { apiGet, apiPatch } from "@/lib/api/client";
import type { LiveOrder } from "@/lib/api/types";
import { useAuthStore } from "@/lib/stores/auth.store";
import { formatCurrency, formatNumber } from "@/lib/format";
import { formatOrderNumber } from "@/lib/order-number";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { cn } from "@/lib/utils";

const STATUS_FLOW: Record<string, string> = {
  Pending: "Confirmed",
  Confirmed: "Preparing",
  Preparing: "Ready",
  Ready: "Delivered",
};

const statusColors: Record<string, string> = {
  Pending: "border-yellow-400 bg-yellow-50",
  Confirmed: "border-yellow-400 bg-yellow-50",
  Preparing: "border-blue-400 bg-blue-50",
  Ready: "border-green-400 bg-green-50",
};

type KdsT = ReturnType<typeof useTranslations<"kds">>;

function statusLabel(t: KdsT, status: string): string {
  switch (status) {
    case "Pending":
      return t("status.Pending");
    case "Confirmed":
      return t("status.Confirmed");
    case "Preparing":
      return t("status.Preparing");
    case "Ready":
      return t("status.Ready");
    case "Delivered":
      return t("status.Delivered");
    case "Cancelled":
      return t("status.Cancelled");
    default:
      return status;
  }
}

function advanceLabel(t: KdsT, nextStatus: string): string {
  switch (nextStatus) {
    case "Confirmed":
      return t("advanceTo.Confirmed");
    case "Preparing":
      return t("advanceTo.Preparing");
    case "Ready":
      return t("advanceTo.Ready");
    case "Delivered":
      return t("advanceTo.Delivered");
    default:
      return t("advance");
  }
}

export function KdsScreen() {
  const t = useTranslations("kds");
  const locale = useLocale();
  const numberLocale = locale === "en" ? "en-US" : "fa-IR";
  const cafeId = useAuthStore((s) => s.user?.cafeId);
  const queryClient = useQueryClient();
  const [connected, setConnected] = useState(false);

  const { data: orders = [], isLoading } = useQuery({
    queryKey: ["orders-live", cafeId],
    queryFn: () => apiGet<LiveOrder[]>(`/api/cafes/${cafeId}/orders/live`),
    enabled: !!cafeId,
    refetchInterval: 30_000,
  });

  const refresh = useCallback(() => {
    queryClient.invalidateQueries({ queryKey: ["orders-live", cafeId] });
  }, [queryClient, cafeId]);

  useEffect(() => {
    if (!cafeId) return;

    const token =
      typeof window !== "undefined"
        ? localStorage.getItem("meezi_access_token")
        : null;

    const baseUrl =
      process.env.NEXT_PUBLIC_API_URL ?? "https://localhost:7208";

    const connection = new signalR.HubConnectionBuilder()
      .withUrl(`${baseUrl}/hubs/kds`, {
        accessTokenFactory: () => token ?? "",
      })
      .withAutomaticReconnect()
      .build();

    connection
      .start()
      .then(() => connection.invoke("JoinCafe", cafeId))
      .then(() => setConnected(true))
      .catch(() => setConnected(false));

    connection.on("OrderCreated", () => refresh());
    connection.on("OrderStatusChanged", () => refresh());

    return () => {
      void connection.stop();
    };
  }, [cafeId, refresh]);

  const advanceStatus = useMutation({
    mutationFn: async ({ orderId, status }: { orderId: string; status: string }) =>
      apiPatch(`/api/cafes/${cafeId}/orders/${orderId}/status`, { status }),
    onSuccess: () => refresh(),
  });

  if (!cafeId) return null;

  const columns = [
    { key: "Pending", label: t("pending"), statuses: ["Pending", "Confirmed"] },
    { key: "Preparing", label: t("preparing"), statuses: ["Preparing"] },
    { key: "Ready", label: t("ready"), statuses: ["Ready"] },
  ];

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-bold">{t("title")}</h2>
        <span className="text-xs text-muted-foreground">
          {connected ? `● ${t("live")}` : `○ ${t("polling")}`}
        </span>
      </div>

      {isLoading ? (
        <p className="text-muted-foreground">{t("loading")}</p>
      ) : orders.length === 0 ? (
        <p className="text-muted-foreground">{t("noOrders")}</p>
      ) : (
        <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
          {columns.map((col) => (
            <div key={col.key} className="space-y-3">
              <h3 className="font-semibold">{col.label}</h3>
              {orders
                .filter((o) => col.statuses.includes(o.status))
                .map((order) => {
                  const nextStatus = STATUS_FLOW[order.status];
                  return (
                    <Card
                      key={order.id}
                      className={cn("border-2", statusColors[order.status] ?? "")}
                    >
                      <CardHeader className="pb-2">
                        <CardTitle className="flex justify-between gap-2 text-base">
                          <span className="min-w-0">
                            #{formatOrderNumber(order)}
                            {" · "}
                            {order.tableNumber
                              ? `${t("table")} ${formatNumber(order.tableNumber, numberLocale)}`
                              : "—"}
                          </span>
                          <span className="shrink-0 text-sm font-normal">
                            {formatCurrency(order.total, numberLocale)}
                          </span>
                        </CardTitle>
                        <span className="mt-1 inline-flex w-fit rounded-md border border-border/80 bg-card/80 px-2 py-0.5 text-[11px] font-medium text-muted-foreground">
                          {statusLabel(t, order.status)}
                        </span>
                      </CardHeader>
                      <CardContent className="space-y-2">
                        <ul className="text-sm">
                          {order.items.map((item) => (
                            <li key={item.id}>
                              {formatNumber(item.quantity, numberLocale)}×{" "}
                              {item.menuItemName}
                            </li>
                          ))}
                        </ul>
                        {nextStatus ? (
                          <Button
                            size="sm"
                            className="w-full"
                            disabled={advanceStatus.isPending}
                            onClick={() =>
                              advanceStatus.mutate({
                                orderId: order.id,
                                status: nextStatus,
                              })
                            }
                          >
                            {advanceLabel(t, nextStatus)}
                          </Button>
                        ) : null}
                      </CardContent>
                    </Card>
                  );
                })}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
