import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Key, Plus, Trash2, Copy, Check } from 'lucide-react';
import { format } from 'date-fns';
import axios from '@/services/authApi';
import { toast } from 'sonner';

interface ApiToken {
    id: string;
    name: string;
    prefix: string;
    lastUsedAt?: string;
    expiresAt?: string;
    createdAt: string;
    isActive: boolean;
}

export function ApiTokenManager() {
    const [tokens, setTokens] = useState<ApiToken[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [showCreateModal, setShowCreateModal] = useState(false);
    const [newTokenName, setNewTokenName] = useState('');
    const [newTokenExpiry, setNewTokenExpiry] = useState<number | ''>('');
    const [generatedToken, setGeneratedToken] = useState<string | null>(null);
    const [isCreating, setIsCreating] = useState(false);
    const [copied, setCopied] = useState(false);
    const [tokenToRevoke, setTokenToRevoke] = useState<ApiToken | null>(null);

    useEffect(() => {
        fetchTokens();
    }, []);

    const fetchTokens = async () => {
        try {
            setIsLoading(true);
            const response = await axios.get('/api-tokens');
            setTokens(response.data.data.tokens);
        } catch (error) {
            console.error('Failed to fetch API tokens:', error);
            toast.error('Failed to load API tokens');
        } finally {
            setIsLoading(false);
        }
    };

    const handleCreateToken = async () => {
        if (!newTokenName.trim()) return;

        try {
            setIsCreating(true);
            const payload: any = { name: newTokenName };
            if (newTokenExpiry) {
                payload.expiresInDays = Number(newTokenExpiry);
            }

            const response = await axios.post('/api-tokens', payload);
            setGeneratedToken(response.data.data.token);
            toast.success('API Token created successfully');
            fetchTokens(); // Refresh list
        } catch (error) {
            console.error('Failed to create token:', error);
            toast.error('Failed to create API token');
        } finally {
            setIsCreating(false);
        }
    };

    const handleRevokeToken = (token: ApiToken) => {
        setTokenToRevoke(token);
    };

    const confirmRevokeToken = async () => {
        if (!tokenToRevoke) return;


        try {
            await axios.delete(`/api-tokens/${tokenToRevoke.id}`);
            toast.success('Token revoked successfully');
            setTokens(tokens.filter(t => t.id !== tokenToRevoke.id));
            setTokenToRevoke(null);
        } catch (error) {
            console.error('Failed to revoke token:', error);
            toast.error('Failed to revoke token');
        }
    };

    const copyToClipboard = () => {
        if (generatedToken) {
            navigator.clipboard.writeText(generatedToken);
            setCopied(true);
            setTimeout(() => setCopied(false), 2000);
            toast.success('Token copied to clipboard');
        }
    };

    const resetCreateModal = () => {
        setShowCreateModal(false);
        setNewTokenName('');
        setNewTokenExpiry('');
        setGeneratedToken(null);
    };

    return (
        <div className="space-y-6">
            <div className="flex items-center justify-between">
                <div>
                    <h3 className="text-lg font-medium text-gray-900">API Tokens</h3>
                    <p className="text-sm text-gray-500">Manage personal access tokens for external integrations</p>
                </div>
                <Button onClick={() => setShowCreateModal(true)} size="sm" className="bg-re-green hover:bg-re-green/90 text-white">
                    <Plus className="w-4 h-4 mr-2" />
                    Generate
                </Button>
            </div>
            {isLoading ? (
                <div className="text-center py-4 text-gray-500">Loading tokens...</div>
            ) : tokens.length === 0 ? (
                <div className="text-center py-8 bg-gray-50 rounded-lg border border-dashed border-gray-300">
                    <Key className="w-10 h-10 text-gray-300 mx-auto mb-2" />
                    <p className="text-gray-500 font-medium">No API tokens found</p>
                    <p className="text-gray-400 text-sm mt-1">Generate a token to access the API programmatically</p>
                </div>
            ) : (
                <div className="rounded-md border">
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead>Name</TableHead>
                                <TableHead>Prefix</TableHead>
                                <TableHead>Last Used</TableHead>
                                <TableHead>Expires</TableHead>
                                <TableHead className="text-right">Actions</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {tokens.map((token) => (
                                <TableRow key={token.id}>
                                    <TableCell className="font-medium">{token.name}</TableCell>
                                    <TableCell className="font-mono text-xs bg-slate-100 rounded px-2 py-1 w-fit">{token.prefix}...</TableCell>
                                    <TableCell className="text-gray-500 text-sm">
                                        {token.lastUsedAt ? format(new Date(token.lastUsedAt), 'MMM d, yyyy') : 'Never'}
                                    </TableCell>
                                    <TableCell className="text-gray-500 text-sm">
                                        {token.expiresAt ? format(new Date(token.expiresAt), 'MMM d, yyyy') : 'No Expiry'}
                                    </TableCell>
                                    <TableCell className="text-right">
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            onClick={() => handleRevokeToken(token)}
                                            className="text-red-600 hover:text-red-700 hover:bg-red-50"
                                        >
                                            <Trash2 className="w-4 h-4" />
                                            <span className="sr-only">Revoke</span>
                                        </Button>
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                </div>
            )}

            {/* Create Token Modal */}
            <Dialog open={showCreateModal} onOpenChange={(open) => !open && resetCreateModal()}>
                <DialogContent className="sm:max-w-md">
                    <DialogHeader>
                        <DialogTitle>Generate API Token</DialogTitle>
                        <DialogDescription>
                            Create a new token to access the API. Treat this token like a password.
                        </DialogDescription>
                    </DialogHeader>

                    {!generatedToken ? (
                        <div className="space-y-4 py-4">
                            <div className="space-y-2">
                                <Label htmlFor="token-name">Token Name</Label>
                                <Input
                                    id="token-name"
                                    placeholder="e.g., CI/CD Pipeline, Prometheus"
                                    value={newTokenName}
                                    onChange={(e) => setNewTokenName(e.target.value)}
                                />
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="token-expiry">Expiration (Days)</Label>
                                <Input
                                    id="token-expiry"
                                    type="number"
                                    min="1"
                                    placeholder="Leave empty for no expiry"
                                    value={newTokenExpiry}
                                    onChange={(e) => {
                                        const val = e.target.value;
                                        if (val === '') {
                                            setNewTokenExpiry('');
                                        } else {
                                            const num = parseInt(val);
                                            // Prevent negative numbers
                                            if (!isNaN(num) && num >= 1) {
                                                setNewTokenExpiry(num);
                                            }
                                        }
                                    }}
                                />
                            </div>
                        </div>
                    ) : (
                        <div className="space-y-4 py-4">
                            <Alert className="bg-green-50 border-green-200">
                                <Check className="h-4 w-4 text-green-600" />
                                <AlertTitle className="text-green-800">Token Generated Successfully</AlertTitle>
                                <AlertDescription className="text-green-700">
                                    Please copy your token now. You won't be able to see it again!
                                </AlertDescription>
                            </Alert>

                            <div className="relative">
                                <div className="p-4 bg-slate-900 rounded-md font-mono text-sm text-green-400 break-all pr-10">
                                    {generatedToken}
                                </div>
                                <Button
                                    size="icon"
                                    variant="ghost"
                                    className="absolute top-1 right-1 text-gray-400 hover:text-white hover:bg-slate-800"
                                    onClick={copyToClipboard}
                                >
                                    {copied ? <Check className="w-4 h-4 text-green-500" /> : <Copy className="w-4 h-4" />}
                                </Button>
                            </div>
                        </div>
                    )}

                    <DialogFooter>
                        {!generatedToken ? (
                            <>
                                <Button variant="outline" onClick={resetCreateModal}>Cancel</Button>
                                <Button onClick={handleCreateToken} disabled={!newTokenName.trim() || isCreating}>
                                    {isCreating ? 'Generating...' : 'Generate Token'}
                                </Button>
                            </>
                        ) : (
                            <Button onClick={resetCreateModal}>Done</Button>
                        )}
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            <AlertDialog open={!!tokenToRevoke} onOpenChange={(open) => !open && setTokenToRevoke(null)}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>Revoke API Token</AlertDialogTitle>
                        <AlertDialogDescription>
                            Are you sure you want to revoke the token <strong>{tokenToRevoke?.name}</strong>?
                            This action cannot be undone and any applications using this token will lose access immediately.
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel>Cancel</AlertDialogCancel>
                        <AlertDialogAction onClick={confirmRevokeToken} className="bg-red-600 hover:bg-red-700 text-white">
                            Revoke Token
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </div>
    );
}
