"use client";

import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { apiDelete, apiGet } from "@/lib/api/client";
import { useAuthStore } from "@/lib/stores/auth.store";
import { getOrCreateTerminalId } from "@/lib/terminal";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { notify } from "@/lib/notify";

type TerminalsResponse = {
  terminals: { terminalId: string }[];
  max: number;
};

export function SettingsTerminalsPanel() {
  const t = useTranslations("settings.terminals");
  const cafeId = useAuthStore((s) => s.user?.cafeId);
  const qc = useQueryClient();
  const thisDevice = getOrCreateTerminalId();

  const { data, isLoading } = useQuery({
    queryKey: ["terminals", cafeId],
    queryFn: () => apiGet<TerminalsResponse>(`/api/cafes/${cafeId}/terminals`),
    enabled: !!cafeId,
  });

  const revoke = useMutation({
    mutationFn: (terminalId: string) =>
      apiDelete(`/api/cafes/${cafeId}/terminals/${encodeURIComponent(terminalId)}`),
    onSuccess: () => {
      void qc.invalidateQueries({ queryKey: ["terminals", cafeId] });
      notify.success(t("revoked"));
    },
  });

  const list = data?.terminals ?? [];
  const max = data?.max ?? 1;

  return (
    <Card className="rounded-xl border border-border/80">
      <CardHeader>
        <CardTitle className="text-base">{t("title")}</CardTitle>
        <p className="text-sm text-muted-foreground">{t("hint", { max })}</p>
      </CardHeader>
      <CardContent className="space-y-2">
        <p className="text-xs text-muted-foreground">
          {t("thisDevice")}: <span className="font-mono">{thisDevice}</span>
        </p>
        {isLoading ? (
          <p className="text-sm text-muted-foreground">{t("loading")}</p>
        ) : list.length === 0 ? (
          <p className="text-sm text-muted-foreground">{t("empty")}</p>
        ) : (
          <ul className="space-y-2">
            {list.map((row) => (
              <li
                key={row.terminalId}
                className="flex items-center justify-between gap-2 rounded-lg border border-border px-3 py-2 text-sm"
              >
                <span className="font-mono text-xs">{row.terminalId}</span>
                <Button
                  size="sm"
                  variant="outline"
                  disabled={revoke.isPending}
                  onClick={() => revoke.mutate(row.terminalId)}
                >
                  {t("revoke")}
                </Button>
              </li>
            ))}
          </ul>
        )}
      </CardContent>
    </Card>
  );
}
