"use client";

import { useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { ShieldCheck } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
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 { revealPortalSecrets, rotatePortalSecrets } from "@/services/portal";
import type { PortalSecrets, PortalStore } from "@/types/portal";

/**
 * The two keys: one signs what the store sends us, the other verifies what we send the store.
 *
 * Neither is ever in the settings answer — the server withholds them until the password is given
 * again — so they are held in component state only, for as long as the owner chooses to leave them
 * showing. Navigating away or pressing Hide drops them.
 *
 * Rotating is safe to do mid-trade: the old pair keeps working for a day, and the card says until
 * when, so the owner can see their window rather than having to remember it.
 */
export function SecretsCard({ store }: { store: PortalStore }) {
  const t = useT();
  const { locale } = useI18n();
  const queryClient = useQueryClient();

  const secrets = store.secrets;

  const [mode, setMode] = useState<"reveal" | "rotate" | null>(null);
  const [shown, setShown] = useState<PortalSecrets | null>(null);

  async function confirm(password: string) {
    const response = mode === "rotate" ? await rotatePortalSecrets(password) : await revealPortalSecrets(password);
    setShown(response.Model);
    if (mode === "rotate") {
      toast.success(t("portal.integration.rotatedToast"));
      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">
        <ShieldCheck className="h-4 w-4" aria-hidden />
        {t("portal.integration.secretsTitle")}
      </h3>
      <p className="mt-1 text-xs text-muted-foreground">{t("portal.integration.secretsHint")}</p>

      <div className="mt-4 space-y-1.5 text-sm text-muted-foreground">
        {secrets?.rotated_at ? (
          <p>{t("portal.integration.secretsRotatedAt", { date: formatDateTime(secrets.rotated_at, locale) })}</p>
        ) : null}
        {secrets?.previous_valid_until ? (
          <p className="text-warning">
            {t("portal.integration.secretsOverlap", { date: formatDateTime(secrets.previous_valid_until, locale) })}
          </p>
        ) : null}
      </div>

      {shown ? (
        <div className="mt-4 space-y-3">
          <CopyField label={t("portal.integration.signingSecret")} value={shown.signing_secret} />
          <CopyField label={t("portal.integration.webhookSecret")} value={shown.webhook_secret} />
        </div>
      ) : null}

      <div className="mt-4 flex flex-wrap gap-2">
        {shown ? (
          <Button size="sm" variant="outline" onClick={() => setShown(null)}>
            {t("portal.integration.hide")}
          </Button>
        ) : (
          <Button size="sm" variant="outline" onClick={() => setMode("reveal")}>
            {t("portal.integration.reveal")}
          </Button>
        )}
        <Button size="sm" variant="outline" onClick={() => setMode("rotate")}>
          {t("portal.integration.rotate")}
        </Button>
      </div>

      <PasswordConfirmDialog
        open={mode !== null}
        onOpenChange={(open) => (open ? null : setMode(null))}
        title={mode === "rotate" ? t("portal.integration.rotateTitle") : t("portal.integration.revealTitle")}
        description={mode === "rotate" ? t("portal.integration.rotateBody") : t("portal.integration.revealBody")}
        actionLabel={mode === "rotate" ? t("portal.integration.rotate") : t("portal.integration.confirm")}
        onConfirm={confirm}
      />
    </Card>
  );
}
