"use client";

import { useState } from "react";
import { GenerateKeyOptions } from "@/lib/api";
import { Button } from "@/components/ui";

const KEY_SIZES: Record<string, number[]> = {
    rsa: [2048, 3072, 4096],
    ecdsa: [256, 384, 521],
};

const DEFAULT_SIZE: Record<string, number> = {
    rsa: 4096,
    ecdsa: 256,
};

export function GenerateKeyModal({ onClose, onSubmit, isPending }: { onClose: () => void; onSubmit: (opts: GenerateKeyOptions) => void; isPending: boolean }) {
    const [label, setLabel] = useState("");
    const [keyType, setKeyType] = useState<"ed25519" | "rsa" | "ecdsa">("ed25519");
    const [keySize, setKeySize] = useState<number>(4096);
    const [passphrase, setPassphrase] = useState("");
    const [comment, setComment] = useState("");

    function handleKeyTypeChange(t: "ed25519" | "rsa" | "ecdsa") {
        setKeyType(t);
        if (t !== "ed25519") {
            setKeySize(DEFAULT_SIZE[t]);
        }
    }

    function handleSubmit(e: React.FormEvent) {
        e.preventDefault();
        onSubmit({
            label: label || "generated",
            key_type: keyType,
            key_size: keyType !== "ed25519" ? keySize : undefined,
            passphrase: passphrase || undefined,
            comment: comment || undefined,
        });
    }

    const sizes = KEY_SIZES[keyType];

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center">
            <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={onClose} />
            <div className="relative z-10 w-full max-w-md rounded-xl border border-border bg-surface p-6 shadow-2xl">
                <div className="mb-5 flex items-center justify-between">
                    <h2 className="text-lg font-semibold text-text-primary">Generate SSH Key</h2>
                    <button onClick={onClose} className="rounded-md p-1 text-text-secondary transition-colors hover:text-text-primary">
                        <svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>

                <form onSubmit={handleSubmit} className="space-y-4">
                    <div>
                        <label className="mb-1.5 block text-sm font-medium text-text-secondary">
                            Label <span className="text-text-tertiary">(used as the key name in Vantage)</span>
                        </label>
                        <input
                            type="text"
                            value={label}
                            onChange={(e) => setLabel(e.target.value)}
                            placeholder="e.g. server-deploy-key"
                            className="w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-tertiary focus:border-accent/50 focus:outline-none focus:ring-1 focus:ring-accent/30"
                        />
                    </div>

                    <div>
                        <label className="mb-1.5 block text-sm font-medium text-text-secondary">Key Type</label>
                        <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
                            {(["ed25519", "rsa", "ecdsa"] as const).map((t) => (
                                <button
                                    key={t}
                                    type="button"
                                    onClick={() => handleKeyTypeChange(t)}
                                    className={`rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${
                                        keyType === t ? "border-accent bg-accent/10 text-accent" : "border-border bg-surface-2 text-text-secondary hover:border-accent/40 hover:text-text-primary"
                                    }`}
                                >
                                    {t}
                                </button>
                            ))}
                        </div>
                        {keyType === "ed25519" && <p className="mt-1.5 text-xs text-text-tertiary">Modern, fast, and secure. Recommended for new keys.</p>}
                        {keyType === "rsa" && <p className="mt-1.5 text-xs text-text-tertiary">Widely compatible with older systems.</p>}
                        {keyType === "ecdsa" && <p className="mt-1.5 text-xs text-text-tertiary">Elliptic curve shorter keys, good compatibility.</p>}
                    </div>

                    {sizes && (
                        <div>
                            <label className="mb-1.5 block text-sm font-medium text-text-secondary">Key Size (bits)</label>
                            <select
                                value={keySize}
                                onChange={(e) => setKeySize(Number(e.target.value))}
                                className="w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary focus:border-accent/50 focus:outline-none focus:ring-1 focus:ring-accent/30"
                            >
                                {sizes.map((s) => (
                                    <option key={s} value={s}>
                                        {s}
                                    </option>
                                ))}
                            </select>
                        </div>
                    )}

                    <div>
                        <label className="mb-1.5 block text-sm font-medium text-text-secondary">
                            Comment <span className="text-text-tertiary">(embedded in the public key)</span>
                        </label>
                        <input
                            type="text"
                            value={comment}
                            onChange={(e) => setComment(e.target.value)}
                            placeholder="e.g. user@hostname"
                            className="w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-tertiary focus:border-accent/50 focus:outline-none focus:ring-1 focus:ring-accent/30"
                        />
                    </div>

                    <div>
                        <label className="mb-1.5 block text-sm font-medium text-text-secondary">
                            Passphrase <span className="text-text-tertiary">(leave blank for no passphrase)</span>
                        </label>
                        <input
                            type="password"
                            value={passphrase}
                            onChange={(e) => setPassphrase(e.target.value)}
                            placeholder="Optional passphrase"
                            autoComplete="new-password"
                            className="w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder:text-text-tertiary focus:border-accent/50 focus:outline-none focus:ring-1 focus:ring-accent/30"
                        />
                    </div>

                    <div className="flex gap-3 pt-1">
                        <Button type="submit" variant="primary" loading={isPending} className="flex-1">
                            Generate Key
                        </Button>
                        <Button type="button" variant="ghost" onClick={onClose}>
                            Cancel
                        </Button>
                    </div>
                </form>
            </div>
        </div>
    );
}
