"use client";

import { useState } from "react";
import { api } from "@/lib/api";
import { MUTATE_API_KEY_REGENERATE } from "@/lib/api-endpoints";
import { extractApiError } from "@/lib/error";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogBody,
  DialogFooter,
} from "@/components/ui/dialog";
import { toast } from "sonner";
import { ApiKey, ApiKeyResponse } from "@/lib/types/api-key";
import { ApiKeyCreatedDialog } from "./ApiKeyCreatedDialog";

interface RegenerateApiKeyModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  apiKey: ApiKey | null;
  onSaved?: () => void;
}

export function RegenerateApiKeyModal({
  open,
  onOpenChange,
  apiKey,
  onSaved,
}: RegenerateApiKeyModalProps) {
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [newKey, setNewKey] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const handleClose = (nextOpen: boolean) => {
    if (!nextOpen) {
      setNewKey(null);
      setError(null);
    }
    onOpenChange(nextOpen);
  };

  const handleSubmit = async () => {
    if (!apiKey) return;
    setIsSubmitting(true);
    setError(null);
    try {
      const res = await api.post<ApiKeyResponse>(
        MUTATE_API_KEY_REGENERATE(apiKey.id)
      );
      setNewKey(res.key);
      toast.success("API key baru telah dibuat.");
      onSaved?.();
    } catch (err: any) {
      setError(extractApiError(err, "Gagal regenerate API key."));
    } finally {
      setIsSubmitting(false);
    }
  };

  if (!apiKey) return null;

  return (
    <>
      <Dialog open={open && !newKey} onOpenChange={handleClose}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Regenerate API Key</DialogTitle>
            <p className="text-sm text-muted-foreground">
              Key lama akan langsung <strong>tidak valid</strong> dan key baru
              akan dibuat untuk menggantikan. Klien (muscab, hipmi_web, dll.)
              yang masih menggunakan key lama akan mendapat error 401.
            </p>
          </DialogHeader>

          <DialogBody className="space-y-3">
            <div className="rounded-md border border-amber-200 bg-amber-50 p-3 text-sm text-amber-900">
              <strong>Pastikan</strong> Anda sudah memberi tahu pemilik klien untuk
              siap update <code>.env</code> mereka sebelum regenerate. Downtime
              sesaat akan terjadi.
            </div>
            {error && (
              <div className="rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-700">
                {error}
              </div>
            )}
            <div className="space-y-1">
              <label className="text-sm font-medium">Key saat ini</label>
              <code className="block px-3 py-2 bg-slate-50 border border-slate-200 rounded-md font-mono text-xs text-muted-foreground">
                {apiKey.key_masked}
              </code>
            </div>
          </DialogBody>

          <DialogFooter>
            <Button variant="outline" onClick={() => handleClose(false)} disabled={isSubmitting}>
              Batal
            </Button>
            <Button onClick={handleSubmit} disabled={isSubmitting}>
              {isSubmitting ? "Membuat key baru..." : "Regenerate"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <ApiKeyCreatedDialog
        open={!!newKey}
        onOpenChange={(next) => {
          if (!next) {
            setNewKey(null);
            handleClose(false);
          }
        }}
        title="API Key Berhasil Di-regenerate"
        description={`Key untuk "${apiKey.name}" telah diganti. Salin key baru dan update konfigurasi klien segera.`}
        plaintextKey={newKey ?? ""}
      />
    </>
  );
}
