import { useState } from 'react';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Separator } from '@/components/ui/separator';
import { Textarea } from '@/components/ui/textarea';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Key, Plus, Trash2 } from 'lucide-react';
import { toast } from 'sonner';
import { addSshKey, deleteSshKey, listSshKeys } from '@/client';
import {getApiErrorMessage} from '@/lib/api-error';

export function SettingsSshKeys() {
    const queryClient = useQueryClient();
    const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
    const [deleteKeyId, setDeleteKeyId] = useState<number | null>(null);
    const [newKeyTitle, setNewKeyTitle] = useState('');
    const [newKeyContent, setNewKeyContent] = useState('');

    // Fetch SSH keys
    const { data: sshKeysData, isLoading } = useQuery({
        queryKey: ['sshKeys'],
        queryFn: async () => {
            const resp = await listSshKeys();
            return resp.data?.data ?? null;
        },
    });

    // Add SSH key mutation
    const addKeyMutation = useMutation({
        mutationFn: async () => {
            await addSshKey({
                body: {
                    title: newKeyTitle,
                    public_key: newKeyContent,
                },
            });
        },
        onSuccess: () => {
            toast.success('SSH key added successfully');
            queryClient.invalidateQueries({ queryKey: ['sshKeys'] });
            setIsAddDialogOpen(false);
            setNewKeyTitle('');
            setNewKeyContent('');
        },
        onError: (err: unknown) => {
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            toast.error(getApiErrorMessage(err, 'Failed to add SSH key'));
        },
    });

    const deleteKeyMutation = useMutation({
        mutationFn: async (keyId: number) => {
            await deleteSshKey({ path: { key_id: keyId } });
        },
        onSuccess: () => {
            toast.success('SSH key deleted successfully');
            queryClient.invalidateQueries({ queryKey: ['sshKeys'] });
            setDeleteKeyId(null);
        },
        onError: (err: unknown) => {
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            toast.error(getApiErrorMessage(err, 'Failed to delete SSH key'));
        },
    });

    const handleAddKey = () => {
        if (!newKeyTitle.trim()) {
            toast.error('Please enter a title for the SSH key');
            return;
        }
        if (!newKeyContent.trim()) {
            toast.error('Please enter the SSH public key');
            return;
        }
        addKeyMutation.mutate();
    };

    const formatDate = (dateString: string) => {
        return new Date(dateString).toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'short',
            day: 'numeric',
        });
    };

    const sshKeys = sshKeysData?.keys || [];

    return (
        <div className="flex-1 lg:max-w-4xl space-y-6 p-4 md:p-8 pt-6">
            <div className="flex flex-col space-y-8 lg:flex-row lg:items-center lg:justify-between lg:space-y-0">
                <div className="space-y-0.5">
                    <h2 className="text-2xl font-bold tracking-tight">SSH Keys</h2>
                    <p className="text-muted-foreground">Manage your SSH keys for repository access.</p>
                </div>
                <Button onClick={() => setIsAddDialogOpen(true)}>
                    <Plus className="h-4 w-4 mr-2" />
                    Add SSH Key
                </Button>
            </div>
            <Separator className="my-6" />

            <Card>
                <CardHeader>
                    <CardTitle>Your SSH Keys</CardTitle>
                    <p className="text-sm text-muted-foreground">
                        {sshKeys.length === 0
                            ? 'No SSH keys configured yet.'
                            : `You have ${sshKeys.length} SSH key${sshKeys.length > 1 ? 's' : ''} configured.`}
                    </p>
                </CardHeader>
                <CardContent className="px-0 md:px-6">
                    {isLoading ? (
                        <div className="text-center py-8">
                            <p className="text-muted-foreground">Loading SSH keys...</p>
                        </div>
                    ) : sshKeys.length === 0 ? (
                        <div className="text-center py-12 border-t border-dashed">
                            <div className="bg-muted/50 rounded-full p-4 w-fit mx-auto mb-4">
                                <Key className="h-8 w-8 text-muted-foreground" />
                            </div>
                            <h3 className="text-lg font-medium mb-2">No SSH Keys</h3>
                            <p className="text-muted-foreground mb-6 max-w-sm mx-auto">
                                SSH keys allow you to establish a secure connection between your computer and the
                                server.
                            </p>
                            <Button onClick={() => setIsAddDialogOpen(true)}>
                                <Plus className="h-4 w-4 mr-2" />
                                Add Your First SSH Key
                            </Button>
                        </div>
                    ) : (
                        <div className="space-y-1">
                            {sshKeys.map((key, index) => {
                                const keyId = key.id || index;
                                return (
                                    <div key={keyId}>
                                        {index > 0 && <Separator />}
                                        <div className="py-4 px-4 hover:bg-muted/30 transition-colors flex flex-col md:flex-row md:items-start justify-between gap-4 group">
                                            <div className="flex min-w-0 items-start gap-4">
                                                <div className="mt-1">
                                                    <Key className="h-6 w-6 text-muted-foreground/70" />
                                                </div>
                                                <div className="min-w-0 space-y-1.5">
                                                    <div className="flex items-center gap-2 flex-wrap">
                                                        <h3 className="font-semibold text-base">{key.title || 'Untitled'}</h3>
                                                        <Badge
                                                            variant="outline"
                                                            className="text-green-600 border-green-200 bg-green-50 dark:bg-green-900/20 dark:border-green-800 dark:text-green-400"
                                                        >
                                                            Active
                                                        </Badge>
                                                    </div>
                                                    <div className="max-w-full overflow-hidden rounded bg-muted/50 px-2 py-1 font-mono text-xs text-muted-foreground break-all">
                                                        {key.fingerprint || 'No fingerprint available'}
                                                    </div>
                                                    <div className="flex items-center gap-4 text-xs text-muted-foreground">
                                                        <span className="flex items-center gap-1">
                                                            Added{' '}
                                                            <span className="font-medium text-foreground">
                                                                {key.created_at ? formatDate(key.created_at) : 'Unknown'}
                                                            </span>
                                                        </span>
                                                        <span>•</span>
                                                        <span>
                                                            {key.key_type || 'ssh-rsa'}{' '}
                                                            {key.key_bits ? `${key.key_bits} bits` : ''}
                                                        </span>
                                                        {key.last_used_at && (
                                                            <>
                                                                <span>•</span>
                                                                <span className="flex items-center gap-1">
                                                                    Last used{' '}
                                                                    <span className="font-medium text-foreground">
                                                                        {formatDate(key.last_used_at)}
                                                                    </span>
                                                                </span>
                                                            </>
                                                        )}
                                                    </div>
                                                </div>
                                            </div>
                                            <div className="flex items-center self-end md:self-center">
                                                <Button
                                                    variant="ghost"
                                                    size="sm"
                                                    className="text-destructive hover:text-destructive hover:bg-destructive/10 opacity-0 group-hover:opacity-100 transition-opacity"
                                                    onClick={() => setDeleteKeyId(keyId)}
                                                    disabled={deleteKeyMutation.isPending}
                                                >
                                                    <Trash2 className="h-4 w-4 mr-2" />
                                                    Delete
                                                </Button>
                                            </div>
                                        </div>
                                    </div>
                                );
                            })}
                        </div>
                    )}
                </CardContent>
            </Card>

            {/* Add SSH Key Dialog */}
            <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
                <DialogContent className="sm:max-w-[600px]">
                    <DialogHeader>
                        <DialogTitle>Add SSH Key</DialogTitle>
                        <DialogDescription>
                            Add a new SSH public key to your account for authenticating with Git repositories.
                        </DialogDescription>
                    </DialogHeader>
                    <div className="space-y-4">
                        <div className="space-y-2">
                            <Label htmlFor="key-title">Title</Label>
                            <Input
                                id="key-title"
                                placeholder="e.g., Work Laptop, Home Desktop"
                                value={newKeyTitle}
                                onChange={(e) => setNewKeyTitle(e.target.value)}
                            />
                            <p className="text-xs text-muted-foreground">Choose a descriptive name for this key</p>
                        </div>
                        <div className="space-y-2">
                            <Label htmlFor="key-content">Public Key</Label>
                            <Textarea
                                id="key-content"
                                placeholder="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD..."
                                value={newKeyContent}
                                onChange={(e) => setNewKeyContent(e.target.value)}
                                rows={8}
                                className="w-full min-w-0 resize-y break-all font-mono text-xs"
                            />
                            <p className="text-xs text-muted-foreground">
                                Paste your SSH public key (typically from ~/.ssh/id_rsa.pub or ~/.ssh/id_ed25519.pub)
                            </p>
                        </div>
                    </div>
                    <DialogFooter>
                        <Button
                            variant="outline"
                            onClick={() => setIsAddDialogOpen(false)}
                            disabled={addKeyMutation.isPending}
                        >
                            Cancel
                        </Button>
                        <Button onClick={handleAddKey} disabled={addKeyMutation.isPending}>
                            {addKeyMutation.isPending ? 'Adding...' : 'Add SSH Key'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            {/* Delete Confirmation Dialog */}
            <AlertDialog open={deleteKeyId !== null} onOpenChange={(open) => !open && setDeleteKeyId(null)}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>Delete SSH Key</AlertDialogTitle>
                        <AlertDialogDescription>
                            Are you sure you want to delete this SSH key? This action cannot be undone and you will
                            need to add the key again if you want to use it in the future.
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel disabled={deleteKeyMutation.isPending}>Cancel</AlertDialogCancel>
                        <AlertDialogAction
                            onClick={() => deleteKeyId && deleteKeyMutation.mutate(deleteKeyId)}
                            disabled={deleteKeyMutation.isPending}
                            className="bg-destructive hover:bg-destructive/90"
                        >
                            {deleteKeyMutation.isPending ? 'Deleting...' : 'Delete'}
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </div>
    );
}
