"use client";

import { useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { KeyRound } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { CopyField } from "@/features/portal/integration/copy-field";
import { PasswordConfirmDialog } from "@/features/portal/integration/password-confirm-dialog";
import { useI18n, useT } from "@/i18n";
import { formatDateTime } from "@/lib/format";
import { queryKeys } from "@/lib/query-keys";
import { generatePortalToken } from "@/services/portal";
import type { PortalStore } from "@/types/portal";

/**
 * The token the store's servers send with every request.
 *
 * **The plaintext is held in component state and nowhere else** — not the query cache, not
 * storage — and it is shown exactly once, because the server keeps only a hash and could not show
 * it again if it wanted to. Closing the dialog loses it. That is the point, and the dialog says so
 * before anybody closes it.
 *
 * Generating **replaces** the current token, so the warning comes before the password prompt, not
 * after: the person pressing the button should know their servers will stop working until the new
 * token is deployed.
 */
export function TokenCard({ store }: { store: PortalStore }) {
  const t = useT();
  const { locale } = useI18n();
  const queryClient = useQueryClient();

  const token = store.token;
  const hasToken = token?.has_token === true;

  const [confirming, setConfirming] = useState(false);
  const [issued, setIssued] = useState<string | null>(null);

  async function generate(password: string) {
    const response = await generatePortalToken(password);
    setIssued(response.Model?.token ?? null);
    void queryClient.invalidateQueries({ queryKey: queryKeys.portal.settings });
  }

  return (
    <Card className="p-5 sm:p-6">
      <h3 className="flex items-center gap-2 text-sm font-semibold text-foreground">
        <KeyRound className="h-4 w-4" aria-hidden />
        {t("portal.integration.tokenTitle")}
      </h3>
      <p className="mt-1 text-xs text-muted-foreground">{t("portal.integration.tokenHint")}</p>

      <dl className="mt-4 space-y-1.5 text-sm">
        {hasToken ? (
          <>
            <div className="text-foreground">
              {t("portal.integration.tokenIssued", { date: formatDateTime(token?.issued_at ?? null, locale) })}
            </div>
            <div className="text-muted-foreground">
              {token?.last_used_at
                ? t("portal.integration.tokenLastUsed", { date: formatDateTime(token.last_used_at, locale) })
                : t("portal.integration.tokenNeverUsed")}
            </div>
          </>
        ) : (
          <div className="text-muted-foreground">{t("portal.integration.tokenNone")}</div>
        )}
      </dl>

      <div className="mt-4">
        <Button size="sm" variant={hasToken ? "outline" : "default"} onClick={() => setConfirming(true)}>
          {hasToken ? t("portal.integration.tokenRegenerate") : t("portal.integration.tokenGenerate")}
        </Button>
      </div>

      <PasswordConfirmDialog
        open={confirming}
        onOpenChange={setConfirming}
        title={t("portal.integration.tokenConfirmTitle")}
        description={hasToken ? t("portal.integration.tokenConfirmBody") : t("portal.integration.tokenConfirmFirst")}
        actionLabel={t("portal.integration.tokenGenerate")}
        onConfirm={async (password) => {
          await generate(password);
          toast.success(t("portal.integration.tokenShownTitle"));
        }}
      />

      {/* The one place the plaintext is ever on screen. */}
      <Dialog open={issued !== null} onOpenChange={(open) => (open ? null : setIssued(null))}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{t("portal.integration.tokenShownTitle")}</DialogTitle>
            <DialogDescription>{t("portal.integration.tokenShownBody")}</DialogDescription>
          </DialogHeader>
          {issued ? <CopyField value={issued} /> : null}
          <DialogFooter>
            <Button onClick={() => setIssued(null)}>{t("common.close")}</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </Card>
  );
}
