import { useQuery } from '@tanstack/react-query';
import { Copy, Key, Shield, Loader2, AlertTriangle } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { listSshKeys, listAccessKeys } from '@/client';
import { toast } from 'sonner';

export function SecurityTab() {
    const { data: sshKeys, isLoading: sshLoading } = useQuery({
        queryKey: ['my-ssh-keys'],
        queryFn: async () => {
            const resp = await listSshKeys();
            return resp.data?.data?.keys ?? [];
        },
        retry: false,
    });

    const { data: accessKeys, isLoading: accessLoading } = useQuery({
        queryKey: ['my-access-keys'],
        queryFn: async () => {
            const resp = await listAccessKeys();
            return resp.data?.data?.access_keys ?? [];
        },
        retry: false,
    });

    const isLoading = sshLoading || accessLoading;

    const copyFingerprint = (fingerprint: string) => {
        navigator.clipboard.writeText(fingerprint).then(() => {
            toast.success('Copied fingerprint');
        });
    };

    if (isLoading) {
        return (
            <Card className="border-border/40">
                <CardContent className="flex items-center justify-center gap-2 py-12 text-sm text-muted-foreground">
                    <Loader2 className="h-4 w-4 animate-spin" />
                    Loading security settings...
                </CardContent>
            </Card>
        );
    }

    return (
        <div className="space-y-6">
            {/* SSH Keys */}
            <Card className="border-border/40">
                <CardHeader className="pb-3">
                    <CardTitle className="flex items-center gap-2 text-sm font-medium">
                        <Key className="h-4 w-4" />
                        SSH Keys
                    </CardTitle>
                </CardHeader>
                <CardContent className="space-y-2">
                    {(sshKeys ?? []).length === 0 ? (
                        <p className="py-4 text-center text-sm text-muted-foreground">No SSH keys added</p>
                    ) : (
                        (sshKeys ?? []).map((key: {
                            id: number;
                            title: string;
                            fingerprint: string;
                            key_type: string;
                            is_revoked: boolean;
                            created_at: string;
                        }) => (
                            <div
                                key={key.id}
                                className="flex items-center justify-between rounded-lg border border-border/40 p-3"
                            >
                                <div className="min-w-0 flex-1">
                                    <div className="flex items-center gap-2">
                                        <p className="text-sm font-medium">{key.title}</p>
                                        <span className="rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium uppercase">{key.key_type}</span>
                                        {key.is_revoked && (
                                            <span className="flex items-center gap-1 text-[10px] text-red-500">
                                                <AlertTriangle className="h-3 w-3" /> Revoked
                                            </span>
                                        )}
                                    </div>
                                    <button
                                        onClick={() => copyFingerprint(key.fingerprint)}
                                        className="mt-1 flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
                                    >
                                        {key.fingerprint}
                                        <Copy className="h-3 w-3" />
                                    </button>
                                </div>
                            </div>
                        ))
                    )}
                    <Button variant="outline" size="sm" className="mt-2 w-full" onClick={() => window.location.href = '/settings/keys'}>
                        Manage SSH Keys
                    </Button>
                </CardContent>
            </Card>

            {/* Personal Access Tokens */}
            <Card className="border-border/40">
                <CardHeader className="pb-3">
                    <CardTitle className="flex items-center gap-2 text-sm font-medium">
                        <Shield className="h-4 w-4" />
                        Personal Access Tokens
                    </CardTitle>
                </CardHeader>
                <CardContent className="space-y-2">
                    {(accessKeys ?? []).length === 0 ? (
                        <p className="py-4 text-center text-sm text-muted-foreground">No access tokens created</p>
                    ) : (
                        (accessKeys ?? []).map((key: {
                            id: number;
                            name: string;
                            scopes: string[];
                            is_revoked: boolean;
                            created_at: string;
                        }) => (
                            <div
                                key={key.id}
                                className="flex items-center justify-between rounded-lg border border-border/40 p-3"
                            >
                                <div className="min-w-0 flex-1">
                                    <div className="flex items-center gap-2">
                                        <p className="text-sm font-medium">{key.name}</p>
                                        {key.is_revoked && (
                                            <span className="flex items-center gap-1 text-[10px] text-red-500">
                                                <AlertTriangle className="h-3 w-3" /> Revoked
                                            </span>
                                        )}
                                    </div>
                                    <div className="mt-1 flex flex-wrap gap-1">
                                        {(key.scopes ?? []).map((scope: string) => (
                                            <span key={scope} className="rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">
                                                {scope}
                                            </span>
                                        ))}
                                    </div>
                                </div>
                            </div>
                        ))
                    )}
                    <Button variant="outline" size="sm" className="mt-2 w-full" onClick={() => window.location.href = '/settings/tokens'}>
                        Manage Access Tokens
                    </Button>
                </CardContent>
            </Card>
        </div>
    );
}
