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

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

import { SectionHeading } from './primitives';

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

  const [addOpen, setAddOpen] = useState(false);
  const [publicKey, setPublicKey] = useState('');
  const [keyId, setKeyId] = useState('');

  const addMutation = useMutation({
    mutationFn: () =>
      UserService.userAddGpgKey({ requestBody: { public_key: publicKey, key_id: keyId } }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['user', 'gpg-keys'] });
      setAddOpen(false);
      setPublicKey('');
      setKeyId('');
    },
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) => UserService.userDeleteGpgKey({ keyId: id }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['user', 'gpg-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 GPG 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="GPG Keys"
          description="Manage GPG keys used for signing commits and tags."
        />
        <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 GPG Key</h3>
          <div className="space-y-3">
            <div>
              <label
                htmlFor="gpg-key-id"
                className="mb-1 block text-[13px] font-medium text-foreground"
              >
                Key ID
              </label>
              <input
                id="gpg-key-id"
                type="text"
                value={keyId}
                onChange={(e) => setKeyId(e.target.value)}
                placeholder="Short key ID or full fingerprint"
                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="gpg-key"
                className="mb-1 block text-[13px] font-medium text-foreground"
              >
                ASCII-armored public key
              </label>
              <textarea
                id="gpg-key"
                rows={6}
                value={publicKey}
                onChange={(e) => setPublicKey(e.target.value)}
                placeholder="-----BEGIN PGP PUBLIC KEY BLOCK-----\n\n-----END PGP PUBLIC KEY BLOCK-----"
                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={!publicKey.trim() || !keyId.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">
          <Shield className="mx-auto size-8 text-border" />
          <p className="mt-2 text-[14px] text-muted-foreground">No GPG keys added.</p>
          <p className="mt-1 text-[12px] text-muted-foreground/60">
            Add a GPG key to sign your commits and tags.
          </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"
            >
              <Shield className="size-5 shrink-0 text-muted-foreground" />
              <div className="min-w-0 flex-1">
                <p className="text-[14px] font-medium text-foreground">
                  {key.primary_email ?? 'No email'}
                </p>
                <p className="mt-0.5 text-[12px] font-mono text-muted-foreground">
                  Fingerprint: {key.fingerprint}
                </p>
                <p className="mt-0.5 text-[12px] text-muted-foreground/60">
                  Key ID: {key.key_id}
                  {key.created_at
                    ? ` · Added ${new Date(key.created_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>
  );
}
