import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { client, type CreateUserSshKey } from "@/client";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Terminal, Trash2 } from "lucide-react";

export default function SettingsSshKeysPage() {
  const qc = useQueryClient();
  const [newTitle, setNewTitle] = useState("");
  const [newKey, setNewKey] = useState("");

  const { data: keys = [], isLoading } = useQuery({
    queryKey: ["user", "ssh-keys"],
    queryFn: async () => {
      const res = await client.userListSshKeys();
      return res.data;
    },
    retry: false,
  });

  const addKey = useMutation({
    mutationFn: async (data: CreateUserSshKey) => {
      const res = await client.userAddSshKey(data);
      return res.data;
    },
    onSuccess: () => {
      setNewTitle("");
      setNewKey("");
      qc.invalidateQueries({ queryKey: ["user", "ssh-keys"] });
    },
  });

  const revokeKey = useMutation({
    mutationFn: async (id: number) => {
      await client.userRevokeSshKey(id);
    },
    onSuccess: () => qc.invalidateQueries({ queryKey: ["user", "ssh-keys"] }),
  });

  const activeKeys = keys.filter((k) => !k.is_revoked);

  return (
    <div className="px-8 py-10">
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-xl font-heading font-bold text-foreground">SSH Keys</h1>
          <p className="mt-1 text-sm text-muted-foreground">Manage SSH keys for Git operations and secure access</p>
        </div>
        <Dialog onOpenChange={(open) => { if (!open) { setNewTitle(""); setNewKey(""); } }}>
          <DialogTrigger render={<Button size="sm">Add SSH key</Button>} />
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Add SSH key</DialogTitle>
            </DialogHeader>
            <form
              className="space-y-3"
              onSubmit={(e) => {
                e.preventDefault();
                addKey.mutate({ title: newTitle, public_key: newKey });
              }}
            >
              <div>
                <Label>Title</Label>
                <Input
                  className="mt-1 h-9"
                  placeholder="e.g. Laptop key"
                  value={newTitle}
                  onChange={(e) => setNewTitle(e.target.value)}
                />
              </div>
              <div>
                <Label>Public key</Label>
                <textarea
                  className="mt-1 w-full rounded-lg border border-input bg-transparent px-3 py-2 text-sm font-mono focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50"
                  placeholder="ssh-ed25519 AAAA..."
                  rows={4}
                  value={newKey}
                  onChange={(e) => setNewKey(e.target.value)}
                />
              </div>
              <Button size="sm" type="submit" disabled={!newTitle || !newKey}>Add key</Button>
            </form>
          </DialogContent>
        </Dialog>
      </div>

      <div className="mt-8">
        {isLoading ? (
          <div className="space-y-3">
            {Array.from({ length: 2 }).map((_, i) => (
              <div className="h-12 animate-pulse rounded-lg bg-muted" key={i} />
            ))}
          </div>
        ) : activeKeys.length > 0 ? (
          <div className="space-y-3">
            {activeKeys.map((key) => (
              <Card key={key.id}>
                <CardContent className="flex items-center justify-between">
                  <div className="flex items-center gap-3 min-w-0">
                    <Terminal className="size-4 text-muted-foreground shrink-0" />
                    <div className="min-w-0">
                      <p className="font-heading font-medium text-foreground">{key.title}</p>
                      <p className="font-mono text-xs text-muted-foreground">
                        {key.key_type} {key.key_bits ?? "?"}bit · {key.fingerprint.slice(0, 24)}
                        {key.is_verified ? " · Verified" : " · Unverified"}
                        · Added {new Date(key.created_at).toLocaleDateString()}
                      </p>
                    </div>
                  </div>
                  <Button
                    className="size-8 text-destructive hover:text-destructive"
                    onClick={() => revokeKey.mutate(key.id)}
                    size="icon"
                    variant="ghost"
                  >
                    <Trash2 className="size-4" />
                  </Button>
                </CardContent>
              </Card>
            ))}
          </div>
        ) : (
          <div className="py-10 text-center">
            <Terminal className="mx-auto size-6 text-muted-foreground/30" />
            <p className="mt-4 text-sm text-muted-foreground">No SSH keys added</p>
          </div>
        )}
      </div>
    </div>
  );
}