"use client";

import { useEffect, useState } from "react";
import { api } from "@/lib/api";
import { MUTATE_API_KEY_DETAIL } from "@/lib/api-endpoints";
import { extractApiError } from "@/lib/error";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogBody,
  DialogFooter,
} from "@/components/ui/dialog";
import { toast } from "sonner";
import { ApiKey, ApiKeyScope } from "@/lib/types/api-key";

interface EditApiKeyModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  apiKey: ApiKey | null;
  onSaved?: () => void;
  existingNames?: string[];
}

const SCOPE_OPTIONS: { value: ApiKeyScope; label: string; description: string }[] = [
  {
    value: "public:read",
    label: "public:read",
    description: "Baca endpoint publik",
  },
  {
    value: "internal:write",
    label: "internal:write",
    description: "Tulis endpoint internal",
  },
];

export function EditApiKeyModal({ open, onOpenChange, apiKey, onSaved, existingNames = [] }: EditApiKeyModalProps) {
  const [name, setName] = useState("");
  const [scopes, setScopes] = useState<ApiKeyScope[]>([]);
  const [isActive, setIsActive] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [nameError, setNameError] = useState<string | null>(null);

  useEffect(() => {
    if (apiKey) {
      setName(apiKey.name);
      setScopes(apiKey.scopes);
      setIsActive(apiKey.is_active);
      setNameError(null);
    }
  }, [apiKey]);

  const handleClose = (nextOpen: boolean) => {
    if (!nextOpen && apiKey) {
      setName(apiKey.name);
      setScopes(apiKey.scopes);
      setIsActive(apiKey.is_active);
      setNameError(null);
    }
    onOpenChange(nextOpen);
  };

  const toggleScope = (scope: ApiKeyScope) => {
    setScopes((prev) =>
      prev.includes(scope) ? prev.filter((s) => s !== scope) : [...prev, scope]
    );
  };

  const handleNameChange = (value: string) => {
    setName(value);
    if (apiKey && value.trim().toLowerCase() === apiKey.name.toLowerCase()) {
      setNameError(null);
    } else if (value.trim() && existingNames.some((n) => n.toLowerCase() === value.trim().toLowerCase())) {
      setNameError("Nama API key sudah digunakan.");
    } else {
      setNameError(null);
    }
  };

  const handleSubmit = async () => {
    if (!apiKey) return;
    if (!name.trim()) {
      toast.warning("Nama harus diisi.");
      return;
    }
    if (scopes.length === 0) {
      toast.warning("Pilih minimal 1 scope.");
      return;
    }
    if (name.trim().toLowerCase() !== apiKey.name.toLowerCase() &&
        existingNames.some((n) => n.toLowerCase() === name.trim().toLowerCase())) {
      setNameError("Nama API key sudah digunakan.");
      return;
    }

    setIsSubmitting(true);
    try {
      await api.put(MUTATE_API_KEY_DETAIL(apiKey.id), {
        name: name.trim(),
        scopes,
        is_active: isActive,
      });
      toast.success("API key berhasil diperbarui.");
      onSaved?.();
      onOpenChange(false);
    } catch (err: any) {
      const errMsg = extractApiError(err, "Gagal memperbarui API key.");
      if (errMsg.toLowerCase().includes("sudah ada") || errMsg.toLowerCase().includes("already exists")) {
        setNameError(errMsg);
      } else {
        toast.error(errMsg);
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  if (!apiKey) return null;

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Edit API Key</DialogTitle>
          <p className="text-sm text-muted-foreground">
            Ubah nama, scope, atau status aktif. Untuk mendapatkan nilai key baru,
            gunakan tombol <strong>Regenerate</strong> di halaman utama.
          </p>
        </DialogHeader>

        <DialogBody className="space-y-4">
          <div className="space-y-2">
            <label className="text-sm font-medium">Key (tidak dapat dilihat)</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>

          <div className="space-y-2">
            <label className="text-sm font-medium">Nama</label>
            <Input
              value={name}
              onChange={(e) => handleNameChange(e.target.value)}
              className={nameError ? "border-red-500 focus-visible:ring-red-500" : ""}
            />
            {nameError && <p className="text-xs text-red-500">{nameError}</p>}
          </div>

          <div className="space-y-2">
            <label className="text-sm font-medium">Scope</label>
            <div className="space-y-2">
              {SCOPE_OPTIONS.map((opt) => (
                <label
                  key={opt.value}
                  className="flex items-start gap-3 p-3 border border-slate-200 rounded-md cursor-pointer hover:bg-slate-50"
                >
                  <input
                    type="checkbox"
                    className="w-4 h-4 mt-0.5"
                    checked={scopes.includes(opt.value)}
                    onChange={() => toggleScope(opt.value)}
                  />
                  <div>
                    <div className="text-sm font-medium font-mono">{opt.label}</div>
                    <div className="text-xs text-muted-foreground">
                      {opt.description}
                    </div>
                  </div>
                </label>
              ))}
            </div>
          </div>

          <div className="space-y-2">
            <label className="flex items-center gap-2 text-sm cursor-pointer">
              <input
                type="checkbox"
                className="w-4 h-4"
                checked={isActive}
                onChange={(e) => setIsActive(e.target.checked)}
              />
              <span>Aktif (jika nonaktif, key tidak akan diterima oleh API)</span>
            </label>
          </div>
        </DialogBody>

        <DialogFooter>
          <Button variant="outline" onClick={() => handleClose(false)} disabled={isSubmitting}>
            Batal
          </Button>
          <Button onClick={handleSubmit} disabled={isSubmitting || !!nameError}>
            {isSubmitting ? "Menyimpan..." : "Simpan"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
