"use client";

import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import Link from "next/link";
import { api, Key } from "@/lib/api";
import { Badge, Button, Card, CardHeader, CardTitle } from "@/components/ui";
import { Table, Thead, Tbody, Tr, Th, Td } from "@/components/ui";

function UploadKeyModal({ onClose }: { onClose: () => void }) {
    const queryClient = useQueryClient();
    const [label, setLabel] = useState("");
    const [publicKey, setPublicKey] = useState("");
    const [privateKey, setPrivateKey] = useState("");
    const [passphrase, setPassphrase] = useState("");

    const {
        mutate: upload,
        isPending,
        error,
    } = useMutation({
        mutationFn: () => api.uploadKey(label.trim(), publicKey.trim(), privateKey.trim() || undefined, passphrase || undefined),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["keys"] });
            onClose();
        },
    });

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm">
            <div className="w-full max-w-lg rounded-xl border border-border bg-surface p-6">
                <h2 className="mb-4 text-lg font-semibold text-text-primary">Upload SSH Key</h2>

                {error && <div className="mb-4 rounded-lg border border-danger/30 bg-danger/10 px-3 py-2 text-sm text-danger">{(error as Error).message}</div>}

                <div className="space-y-4">
                    <div>
                        <label className="mb-1.5 block text-sm font-medium text-text-secondary">Label</label>
                        <input
                            type="text"
                            value={label}
                            onChange={(e) => setLabel(e.target.value)}
                            placeholder="e.g. dom-macbook"
                            className="w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary placeholder-text-secondary/50 focus:border-accent focus:outline-none focus:ring-1 focus:ring-accent"
                        />
                    </div>
                    <div>
                        <label className="mb-1.5 block text-sm font-medium text-text-secondary">Public Key</label>
                        <textarea
                            value={publicKey}
                            onChange={(e) => setPublicKey(e.target.value)}
                            placeholder="ssh-ed25519 AAAA..."
                            rows={3}
                            className="w-full rounded-lg border border-border bg-surface-2 px-3 py-2 font-mono text-xs text-text-primary placeholder-text-secondary/50 focus:border-accent focus:outline-none focus:ring-1 focus:ring-accent resize-none"
                        />
                    </div>
                    <div>
                        <label className="mb-1.5 block text-sm font-medium text-text-secondary">
                            Private Key <span className="text-text-tertiary font-normal">(optional stored AES-256-GCM encrypted)</span>
                        </label>
                        <textarea
                            value={privateKey}
                            onChange={(e) => setPrivateKey(e.target.value)}
                            placeholder="-----BEGIN OPENSSH PRIVATE KEY-----"
                            rows={3}
                            className="w-full rounded-lg border border-border bg-surface-2 px-3 py-2 font-mono text-xs text-text-primary placeholder-text-secondary/50 focus:border-accent focus:outline-none focus:ring-1 focus:ring-accent resize-none"
                        />
                    </div>
                    <div>
                        <label className="mb-1.5 block text-sm font-medium text-text-secondary">
                            Passphrase <span className="text-text-tertiary font-normal">(optional for an encrypted private key)</span>
                        </label>
                        <input
                            type="password"
                            value={passphrase}
                            onChange={(e) => setPassphrase(e.target.value)}
                            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-secondary/50 focus:border-accent focus:outline-none focus:ring-1 focus:ring-accent"
                        />
                    </div>
                </div>

                <div className="mt-6 flex justify-end gap-3">
                    <Button variant="ghost" onClick={onClose}>
                        Cancel
                    </Button>
                    <Button variant="primary" loading={isPending} disabled={!label.trim() || !publicKey.trim()} onClick={() => upload()}>
                        Upload Key
                    </Button>
                </div>
            </div>
        </div>
    );
}

export default function KeysPage() {
    const [showUpload, setShowUpload] = useState(false);

    const {
        data: keys,
        isLoading,
        error,
    } = useQuery({
        queryKey: ["keys"],
        queryFn: api.listKeys,
    });

    return (
        <div className="p-4 sm:p-6 lg:p-8">
            {showUpload && <UploadKeyModal onClose={() => setShowUpload(false)} />}

            <div className="mb-6 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <div>
                    <h1 className="text-2xl font-bold text-text-primary">SSH Keys</h1>
                    <p className="mt-1 text-sm text-text-secondary">
                        {keys?.length ?? 0} key{keys?.length !== 1 ? "s" : ""} managed
                    </p>
                </div>
                <Button variant="primary" onClick={() => setShowUpload(true)}>
                    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                        <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5" />
                    </svg>
                    Upload Key
                </Button>
            </div>

            <Card padding={false}>
                {isLoading ? (
                    <div className="flex items-center justify-center py-20">
                        <div className="h-8 w-8 animate-spin rounded-full border-2 border-border border-t-accent" />
                    </div>
                ) : error ? (
                    <div className="py-20 text-center text-danger">Failed to load keys. Is the backend running?</div>
                ) : keys && keys.length > 0 ? (
                    <Table>
                        <Thead>
                            <Tr>
                                <Th>Label</Th>
                                <Th>Fingerprint</Th>
                                <Th>Source</Th>
                                <Th>Assignments</Th>
                                <Th>Created</Th>
                                <Th />
                            </Tr>
                        </Thead>
                        <Tbody>
                            {keys.map((key: Key) => (
                                <Tr key={key.key_id}>
                                    <Td label="Label">
                                        <span className="font-medium text-text-primary">{key.label}</span>
                                    </Td>
                                    <Td label="Fingerprint">
                                        <span className="font-mono text-xs text-text-secondary">{key.fingerprint}</span>
                                    </Td>
                                    <Td label="Source">
                                        <Badge variant={key.source === "generated" ? "accent" : "neutral"}>{key.source}</Badge>
                                    </Td>
                                    <Td label="Assignments">
                                        <span className="text-text-secondary">
                                            {key.assigned_count ?? 0} server{(key.assigned_count ?? 0) !== 1 ? "s" : ""}
                                        </span>
                                    </Td>
                                    <Td label="Created">
                                        <span className="text-text-secondary text-xs">{new Date(key.created_at).toLocaleDateString()}</span>
                                    </Td>
                                    <Td>
                                        <Link href={`/keys/${key.key_id}`}>
                                            <Button variant="ghost" size="sm">
                                                View →
                                            </Button>
                                        </Link>
                                    </Td>
                                </Tr>
                            ))}
                        </Tbody>
                    </Table>
                ) : (
                    <div className="py-20 text-center">
                        <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-surface-2">
                            <svg className="h-6 w-6 text-text-secondary" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                                <path
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    d="M15.75 5.25a3 3 0 013 3m3 0a6 6 0 01-7.029 5.912c-.563-.097-1.159.026-1.563.43L10.5 17.25H8.25v2.25H6v2.25H2.25v-2.818c0-.597.237-1.17.659-1.591l6.499-6.499c.404-.404.527-1 .43-1.563A6 6 0 1121.75 8.25z"
                                />
                            </svg>
                        </div>
                        <p className="text-text-secondary">No SSH keys yet.</p>
                        <Button variant="primary" size="sm" className="mt-4" onClick={() => setShowUpload(true)}>
                            Upload your first key
                        </Button>
                    </div>
                )}
            </Card>
        </div>
    );
}
