"use client";

import { useCallback } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslations, useLocale } from "next-intl";
import { apiGet, apiPost } from "@/lib/api/client";
import type { QueueBoard, QueueTicket, QueueTicketStatus } from "@/lib/api/types";
import { useAuthStore } from "@/lib/stores/auth.store";
import { useBranchStore } from "@/lib/stores/branch.store";
import { PageHeader } from "@/components/layout/page-header";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import { useState } from "react";
import { Link } from "@/i18n/routing";
import { Monitor } from "lucide-react";
import { formatNumber } from "@/lib/format";

const statusVariant: Record<QueueTicketStatus, string> = {
  Waiting: "bg-amber-100 text-amber-900 border-amber-200",
  Called: "bg-blue-100 text-blue-900 border-blue-200",
  Done: "bg-slate-100 text-slate-600 border-slate-200",
  Cancelled: "bg-red-50 text-red-800 border-red-200",
};

export function QueueScreen() {
  const t = useTranslations("queue");
  const tCommon = useTranslations("common");
  const locale = useLocale();
  const numberLocale = locale === "en" ? "en-US" : "fa-IR";
  const cafeId = useAuthStore((s) => s.user?.cafeId);
  const branchId = useBranchStore((s) => s.branchId);
  const queryClient = useQueryClient();
  const [label, setLabel] = useState("");
  const branchQuery = branchId ? `?branchId=${encodeURIComponent(branchId)}` : "";

  const { data: board, isLoading } = useQuery({
    queryKey: ["queue-today", cafeId, branchId],
    queryFn: () =>
      apiGet<QueueBoard>(`/api/cafes/${cafeId}/queue/today${branchQuery}`),
    enabled: !!cafeId,
    refetchInterval: 10_000,
  });

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

  const issueNext = useMutation({
    mutationFn: () =>
      apiPost<QueueTicket>(`/api/cafes/${cafeId}/queue/next`, {
        branchId: branchId ?? undefined,
        customerLabel: label.trim() || undefined,
      }),
    onSuccess: () => {
      setLabel("");
      refresh();
    },
  });

  const callNext = useMutation({
    mutationFn: () =>
      apiPost<QueueBoard>(`/api/cafes/${cafeId}/queue/call-next${branchQuery}`, {}),
    onSuccess: () => refresh(),
  });

  if (!cafeId) return null;

  const displayHref = branchId
    ? `/queue/display?branchId=${encodeURIComponent(branchId)}`
    : "/queue/display";

  return (
    <div className="space-y-6">
      <PageHeader
        title={t("title")}
        subtitle={t("subtitle")}
        action={
          <Button variant="outline" size="sm" asChild>
            <Link href={displayHref} target="_blank" rel="noopener noreferrer">
              <Monitor className="h-4 w-4 me-2" aria-hidden />
              {t("openDisplay")}
            </Link>
          </Button>
        }
      />
      <div className="grid gap-4 lg:grid-cols-3">
        <Card className="rounded-xl border-2 border-primary/30 bg-primary/5 lg:col-span-1">
          <CardContent className="flex flex-col items-center justify-center gap-2 pt-8 pb-8">
            <p className="text-sm text-muted-foreground">{t("nowServing")}</p>
            <p className="text-6xl font-bold tabular-nums text-primary">
              {board?.nowServing != null
                ? formatNumber(board.nowServing, numberLocale)
                : "—"}
            </p>
            <p className="text-xs text-muted-foreground">
              {t("lastIssued")}: {formatNumber(board?.lastIssued ?? 0, numberLocale)}
            </p>
            <p className="text-xs text-muted-foreground">
              {t("waitingCount", { count: board?.waitingCount ?? 0 })}
            </p>
          </CardContent>
        </Card>

        <Card className="rounded-xl lg:col-span-2">
          <CardContent className="space-y-4 pt-6">
            <div className="flex flex-wrap gap-2">
              <Input
                value={label}
                onChange={(e) => setLabel(e.target.value)}
                placeholder={t("customerLabelPlaceholder")}
                className="min-w-[12rem] flex-1"
                onKeyDown={(e) => {
                  if (e.key === "Enter" && !issueNext.isPending) {
                    e.preventDefault();
                    issueNext.mutate();
                  }
                }}
              />
              <Button
                onClick={() => issueNext.mutate()}
                disabled={issueNext.isPending}
              >
                {issueNext.isPending ? "..." : t("issueNext")}
              </Button>
              <Button
                variant="outline"
                onClick={() => callNext.mutate()}
                disabled={callNext.isPending || (board?.waitingCount ?? 0) === 0}
              >
                {callNext.isPending ? "..." : t("callNext")}
              </Button>
            </div>
            <p className="text-xs text-muted-foreground">{t("dailyResetHint")}</p>
          </CardContent>
        </Card>
      </div>

      {isLoading ? (
        <p className="text-sm text-muted-foreground">{tCommon("loading")}</p>
      ) : !board?.tickets.length ? (
        <p className="text-sm text-muted-foreground">{t("empty")}</p>
      ) : (
        <div className="grid gap-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6">
          {board.tickets.map((ticket) => (
            <Card
              key={ticket.id}
              className={cn(
                "rounded-lg border",
                ticket.status === "Called" && "ring-2 ring-primary"
              )}
            >
              <CardContent className="flex items-center justify-between gap-2 pt-4 pb-4">
                <span className="text-2xl font-bold tabular-nums">
                  {formatNumber(ticket.number, numberLocale)}
                </span>
                <Badge
                  variant="outline"
                  className={cn("text-[10px]", statusVariant[ticket.status])}
                >
                  {t(`status.${ticket.status}`)}
                </Badge>
              </CardContent>
              {ticket.customerLabel ? (
                <p className="truncate px-4 pb-3 text-xs text-muted-foreground">
                  {ticket.customerLabel}
                </p>
              ) : null}
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}
