import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Key, Plus, Trash2 } from 'lucide-react';
import { useState } from 'react';

import { UserService } from '@/client/services/UserService';
import { useSshKeys } from '@/hooks/user/useSshKeys';

import { SectionHeading } from './primitives';

export function SshKeysTab() {
  const { data: keys, isLoading, error } = useSshKeys();
  const queryClient = useQueryClient();

  const [addOpen, setAddOpen] = useState(false);
  const [title, setTitle] = useState('');
  const [publicKey, setPublicKey] = useState('');
  const [keyType, setKeyType] = useState('ed25519');

  const addMutation = useMutation({
    mutationFn: () =>
      UserService.userAddSshKey({
        requestBody: { title, public_key: publicKey, key_type: keyType },
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['user', 'ssh-keys'] });
      setAddOpen(false);
      setTitle('');
      setPublicKey('');
      setKeyType('ed25519');
    },
  });

  const deleteMutation = useMutation({
    mutationFn: (keyId: string) => UserService.userDeleteSshKey({ keyId }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['user', 'ssh-keys'] });
    },
  });

  if (isLoading) {
    return (
      <div className="flex items-center gap-2 p-8 text-[14px] text-muted-foreground">
        <span className="inline-block size-4 animate-spin rounded-full border-2 border-border border-t-muted-foreground" />
        Loading…
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-8">
        <div className="rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-[14px] text-destructive">
          Failed to load SSH keys.
        </div>
      </div>
    );
  }

  const activeKeys = (keys ?? []).filter((k) => !k.revoked_at);

  return (
    <div className="px-8 pt-10 pb-8 max-w-[640px]">
      <div className="flex items-start justify-between gap-4 mb-5">
        <SectionHeading
          title="SSH Keys"
          description="Manage SSH keys used for Git operations over SSH."
        />
        <button
          type="button"
          onClick={() => setAddOpen(true)}
          className="shrink-0 inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-[5px] text-[13px] font-medium text-white hover:bg-primary/85"
        >
          <Plus className="size-3.5" />
          New key
        </button>
      </div>

      {addOpen && (
        <div className="mb-6 rounded-lg border border-primary bg-accent/30 p-4">
          <h3 className="mb-4 text-[14px] font-semibold text-foreground">Add SSH Key</h3>
          <div className="space-y-3">
            <div>
              <label
                htmlFor="ssh-title"
                className="mb-1 block text-[13px] font-medium text-foreground"
              >
                Title
              </label>
              <input
                id="ssh-title"
                type="text"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                placeholder="e.g. Work Laptop"
                className="w-full rounded-md border border-border bg-card px-3 py-[7px] text-[14px] text-foreground outline-none placeholder:text-muted-foreground/60 focus:shadow-[inset_0_0_0_2px_var(--ring)] focus:border-transparent"
              />
            </div>
            <div>
              <label
                htmlFor="ssh-key-type"
                className="mb-1 block text-[13px] font-medium text-foreground"
              >
                Key type
              </label>
              <select
                id="ssh-key-type"
                value={keyType}
                onChange={(e) => setKeyType(e.target.value)}
                className="w-full rounded-md border border-border bg-card px-3 py-[7px] text-[14px] text-foreground outline-none focus:shadow-[inset_0_0_0_2px_var(--ring)] focus:border-transparent"
              >
                <option value="ed25519">Ed25519 (Recommended)</option>
                <option value="rsa">RSA</option>
                <option value="ecdsa">ECDSA</option>
                <option value="dsa">DSA</option>
              </select>
            </div>
            <div>
              <label
                htmlFor="ssh-key"
                className="mb-1 block text-[13px] font-medium text-foreground"
              >
                Public key
              </label>
              <textarea
                id="ssh-key"
                rows={4}
                value={publicKey}
                onChange={(e) => setPublicKey(e.target.value)}
                placeholder="ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA…"
                className="w-full rounded-md border border-border bg-card px-3 py-[7px] text-[13px] font-mono text-foreground outline-none placeholder:text-muted-foreground/60 focus:shadow-[inset_0_0_0_2px_var(--ring)] focus:border-transparent"
              />
            </div>
            {addMutation.error && (
              <p className="text-[13px] text-destructive">
                {(addMutation.error as Error)?.message ?? 'Failed to add key'}
              </p>
            )}
            <div className="flex items-center gap-2">
              <button
                type="button"
                onClick={() => addMutation.mutate()}
                disabled={!title.trim() || !publicKey.trim() || addMutation.isPending}
                className="rounded-md bg-primary px-3 py-[5px] text-[13px] font-medium text-primary-foreground hover:bg-primary/85 disabled:opacity-50"
              >
                {addMutation.isPending ? 'Adding…' : 'Add key'}
              </button>
              <button
                type="button"
                onClick={() => setAddOpen(false)}
                className="rounded-md px-3 py-[5px] text-[13px] text-muted-foreground hover:bg-muted"
              >
                Cancel
              </button>
            </div>
          </div>
        </div>
      )}

      {activeKeys.length === 0 ? (
        <div className="rounded-lg border border-dashed border-border px-4 py-10 text-center">
          <Key className="mx-auto size-8 text-border" />
          <p className="mt-2 text-[14px] text-muted-foreground">No SSH keys added.</p>
          <p className="mt-1 text-[12px] text-muted-foreground/60">
            Add an SSH key to authenticate Git operations.
          </p>
        </div>
      ) : (
        <div className="space-y-2">
          {activeKeys.map((key) => (
            <div
              key={key.id}
              className="flex items-center gap-3 rounded-lg border border-border px-4 py-3 transition-colors hover:bg-muted"
            >
              <Key className="size-5 shrink-0 text-muted-foreground" />
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-2">
                  <p className="text-[14px] font-medium text-foreground">{key.title}</p>
                  <span className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-[11px] text-muted-foreground">
                    {key.key_type}
                  </span>
                </div>
                <p className="mt-0.5 truncate text-[12px] font-mono text-muted-foreground">
                  SHA256:{key.fingerprint_sha256}
                </p>
                {key.last_used_at && (
                  <p className="mt-0.5 text-[12px] text-muted-foreground/60">
                    Last used {new Date(key.last_used_at).toLocaleDateString()}
                  </p>
                )}
              </div>
              <button
                type="button"
                onClick={() => deleteMutation.mutate(key.id)}
                disabled={deleteMutation.isPending}
                className="shrink-0 rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive disabled:opacity-40"
              >
                <Trash2 className="size-4" />
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
