THIS IS MY CURRENT CODE:
'use client'

import { useState, useEffect, useRef } from 'react';
import { Tag, TagType, TAG_TYPES } from '@/types/tag';
import { Button } from "@/components/ui/button";
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import { 
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Switch } from "@/components/ui/switch";
import { Checkbox } from "@/components/ui/checkbox";
import { Plus, X, Check, Trash2, Edit3 } from 'lucide-react';
import { Badge } from "@/components/ui/badge";
import { toast } from "@/components/ui/use-toast";

// Shared colors between both components
export const MODERN_COLORS = [
    '#E91E63', // Bright pink
    '#EC407A', // Light pink
    '#AB47BC', // Purple
    '#5E35B1', // Deep purple
    '#3949AB', // Indigo
    '#1E88E5', // Blue
    '#00BFA5', // Teal
    '#7CB342', // Light green
    '#FDD835', // Yellow
    '#FF9800', // Orange
    '#FF7043', // Deep orange
    '#EC407A', // Pink
    '#AB47BC', // Light purple
    '#795548', // Brown
];

export default function TagsPage() {
    const [tags, setTags] = useState<Tag[]>([]);
    const [selectedTags, setSelectedTags] = useState<number[]>([]);
    const [editMode, setEditMode] = useState(false);
    const [editingTag, setEditingTag] = useState<{id: number, newName: string} | null>(null);
    const [showDeleteDialog, setShowDeleteDialog] = useState(false);
    const [showEditDialog, setShowEditDialog] = useState(false);
    const [newTagName, setNewTagName] = useState('');
    const [selectedType, setSelectedType] = useState<TagType>('TRADE_JOURNAL');
    const [isCreating, setIsCreating] = useState(false);

    const generateTagColor = (): string => {
        return MODERN_COLORS[Math.floor(Math.random() * MODERN_COLORS.length)];
    };

    // New function to handle tag deletion
    const handleDeleteTags = async () => {
        try {
            for (const tagId of selectedTags) {
                await fetch(`/api/tags/${tagId}`, {
                    method: 'DELETE',
                });
            }
            toast({
                title: "Success",
                description: "Selected tags have been deleted",
            });
            setSelectedTags([]);
            fetchTags();
        } catch (error) {
            toast({
                title: "Error",
                description: "Failed to delete tags",
                variant: "destructive"
            });
        }
        setShowDeleteDialog(false);
    };

    // New function to handle tag name update
    const handleUpdateTagName = async () => {
        if (!editingTag) return;

        try {
            const response = await fetch(`/api/tags/${editingTag.id}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ name: editingTag.newName }),
            });

            if (!response.ok) throw new Error('Failed to update tag');
            
            toast({
                title: "Success",
                description: "Tag name updated successfully",
            });
            fetchTags();
        } catch (error) {
            toast({
                title: "Error",
                description: "Failed to update tag name",
                variant: "destructive"
            });
        }
        setEditingTag(null);
        setShowEditDialog(false);
    };

    const getContrastColor = (bgColor: string): string => {
        const hex = bgColor.replace('#', '');
        const r = parseInt(hex.slice(0, 2), 16);
        const g = parseInt(hex.slice(2, 4), 16);
        const b = parseInt(hex.slice(4, 6), 16);
        const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
        return luminance > 0.5 ? '#000000' : '#ffffff';
    };

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

    const handleTypeChange = (value: string) => {
        setSelectedType(value as TagType);
    };

    const fetchTags = async () => {
        try {
            const response = await fetch('/api/tags?includeInactive=true');
            if (!response.ok) throw new Error('Failed to fetch tags');
            const fetchedTags = await response.json();
            setTags(fetchedTags);
        } catch (error) {
            console.error('Error fetching tags:', error);
            toast({
                title: "Error",
                description: "Failed to fetch tags",
                variant: "destructive"
            });
        }
    };

    const createTag = async () => {
        if (!newTagName.trim()) return;

        try {
            const response = await fetch('/api/tags', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    name: newTagName,
                    type: selectedType,
                    color: generateTagColor(),
                }),
            });

            if (!response.ok) throw new Error('Failed to create tag');

            setNewTagName('');
            setIsCreating(false);
            await fetchTags();

            toast({
                title: "Success",
                description: "Tag created successfully",
            });
        } catch (error) {
            console.error('Error creating tag:', error);
            toast({
                title: "Error",
                description: "Failed to create tag",
                variant: "destructive"
            });
        }
    };

    const toggleTagActive = async (tagId: number, active: boolean) => {
        try {
            const response = await fetch(`/api/tags/${tagId}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ active }),
            });

            if (!response.ok) throw new Error('Failed to update tag');
            await fetchTags();
        } catch (error) {
            console.error('Error toggling tag:', error);
            toast({
                title: "Error",
                description: "Failed to update tag",
                variant: "destructive"
            });
        }
    };

    const groupedTags = tags.reduce((acc, tag) => {
        if (!acc[tag.type]) {
            acc[tag.type] = [];
        }
        acc[tag.type].push(tag);
        return acc;
    }, {} as Record<string, Tag[]>);

    return (
        <div className="container mx-auto py-6">
            <div className="flex flex-col gap-4 mb-6">
                {/* Management Controls */}
                <div className="flex justify-between items-center">
                    <h1 className="text-2xl font-bold">Tag Management</h1>
                    <div className="flex items-center gap-4">
                        <div className="flex items-center gap-2">
                            <span>Edit Mode</span>
                            <Switch
                                checked={editMode}
                                onCheckedChange={setEditMode}
                            />
                        </div>
                        {selectedTags.length > 0 && (
                            <Button
                                variant="destructive"
                                onClick={() => setShowDeleteDialog(true)}
                                className="flex items-center gap-2"
                            >
                                <Trash2 className="w-4 h-4" />
                                Delete Selected ({selectedTags.length})
                            </Button>
                        )}
                        <Button 
                            onClick={() => setIsCreating(true)} 
                            className="flex items-center gap-2"
                        >
                            <Plus className="w-4 h-4" /> Add New Tag
                        </Button>
                    </div>
                </div>

            {isCreating && (
                <Card className="mb-6">
                    <CardHeader>
                        <CardTitle>Create New Tag</CardTitle>
                        <CardDescription>Add a new tag to organize your trades and journal entries</CardDescription>
                    </CardHeader>
                    <CardContent>
                        <div className="flex gap-4">
                            <Input
                                value={newTagName}
                                onChange={(e) => setNewTagName(e.target.value)}
                                placeholder="Enter tag name..."
                                className="flex-1 rounded-full"
                            />
                            <Select value={selectedType} onValueChange={handleTypeChange}>
                                <SelectTrigger className="w-[200px] rounded-full">
                                    <SelectValue placeholder="Select type" />
                                </SelectTrigger>
                                <SelectContent>
                                    {Object.values(TAG_TYPES).map((type) => (
                                        <SelectItem key={type} value={type}>
                                            {type.replace(/_/g, ' ')}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <Button onClick={createTag} className="rounded-full">Create</Button>
                            <Button variant="ghost" onClick={() => setIsCreating(false)} className="rounded-full">Cancel</Button>
                        </div>
                    </CardContent>
                </Card>
            )}

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {Object.entries(groupedTags).map(([type, tagsList]) => (
                    <Card key={type}>
                        <CardHeader>
                            <CardTitle>{type.replace(/_/g, ' ')}</CardTitle>
                            <CardDescription>{tagsList.length} tags</CardDescription>
                        </CardHeader>
                        <CardContent>
                            <div className="flex flex-wrap gap-2">
                                {tagsList.map(tag => (
                                    <Badge
                                        key={tag.id}
                                        variant={tag.active ? "default" : "secondary"}
                                        className="flex items-center gap-2 px-4 py-1.5 rounded-full transition-all duration-200 hover:scale-105 hover:shadow-lg"
                                        style={{
                                            backgroundColor: tag.active ? tag.color || '#e5e7eb' : '#e5e7eb',
                                            color: tag.active && tag.color ? getContrastColor(tag.color) : '#666',
                                            fontSize: '0.875rem',
                                            fontWeight: '600',
                                            letterSpacing: '0.02em',
                                            border: 'none',
                                            boxShadow: tag.active ? '0 2px 4px rgba(0,0,0,0.1)' : 'none',
                                            textShadow: tag.active ? '0 1px 1px rgba(0,0,0,0.1)' : 'none',
                                            fontFamily: 'Inter, system-ui, sans-serif'
                                        }}
                                    >
                                        {tag.name}
                                        <button
                                            onClick={() => toggleTagActive(tag.id, !tag.active)}
                                            className="hover:scale-110 transition-transform ml-1 bg-black/10 rounded-full p-1"
                                            style={{
                                                opacity: 0.8,
                                                display: 'flex',
                                                alignItems: 'center',
                                                justifyContent: 'center'
                                            }}
                                        >
                                            <X className="w-3.5 h-3.5" />
                                        </button>
                                    </Badge>
                                ))}
                            </div>
                        </CardContent>
                    </Card>
                ))}
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {Object.entries(groupedTags).map(([type, tagsList]) => (
                    <Card key={type}>
                        <CardHeader>
                            <CardTitle>{type.replace(/_/g, ' ')}</CardTitle>
                            <CardDescription>{tagsList.length} tags</CardDescription>
                        </CardHeader>
                        <CardContent>
                            <div className="flex flex-wrap gap-2">
                                {tagsList.map(tag => (
                                    <div key={tag.id} className="flex items-center gap-2">
                                        {editMode && (
                                            <Checkbox
                                                checked={selectedTags.includes(tag.id)}
                                                onCheckedChange={(checked) => {
                                                    if (checked) {
                                                        setSelectedTags(prev => [...prev, tag.id]);
                                                    } else {
                                                        setSelectedTags(prev => prev.filter(id => id !== tag.id));
                                                    }
                                                }}
                                            />
                                        )}
                                        <Badge
                                            variant={tag.active ? "default" : "secondary"}
                                            className="flex items-center gap-2 px-4 py-1.5 rounded-full transition-all duration-200 hover:scale-105 hover:shadow-lg"
                                            style={{
                                                backgroundColor: tag.active ? tag.color || '#e5e7eb' : '#e5e7eb',
                                                color: tag.active && tag.color ? getContrastColor(tag.color) : '#666',
                                                fontSize: '0.875rem',
                                                fontWeight: '600',
                                                letterSpacing: '0.02em',
                                                border: 'none',
                                                boxShadow: tag.active ? '0 2px 4px rgba(0,0,0,0.1)' : 'none',
                                                textShadow: tag.active ? '0 1px 1px rgba(0,0,0,0.1)' : 'none',
                                                cursor: editMode ? 'pointer' : 'default'
                                            }}
                                            onDoubleClick={() => {
                                                if (editMode) {
                                                    setEditingTag({ id: tag.id, newName: tag.name });
                                                }
                                            }}
                                        >
                                            {editingTag?.id === tag.id ? (
                                                <>
                                                    <input
                                                        type="text"
                                                        value={editingTag.newName}
                                                        onChange={(e) => setEditingTag(prev => ({
                                                            ...prev!,
                                                            newName: e.target.value
                                                        }))}
                                                        className="bg-transparent border-none focus:outline-none"
                                                        autoFocus
                                                    />
                                                    <div className="flex items-center gap-1">
                                                        <button
                                                            onClick={() => setShowEditDialog(true)}
                                                            className="hover:scale-110 transition-transform"
                                                        >
                                                            <Check className="w-4 h-4 text-green-500" />
                                                        </button>
                                                        <button
                                                            onClick={() => setEditingTag(null)}
                                                            className="hover:scale-110 transition-transform"
                                                        >
                                                            <X className="w-4 h-4 text-red-500" />
                                                        </button>
                                                    </div>
                                                </>
                                            ) : (
                                                <>
                                                    {tag.name}
                                                    {!editMode && (
                                                        <button
                                                            onClick={() => toggleTagActive(tag.id, !tag.active)}
                                                            className="hover:scale-110 transition-transform ml-1 bg-black/10 rounded-full p-1"
                                                        >
                                                            <X className="w-3.5 h-3.5" />
                                                        </button>
                                                    )}
                                                </>
                                            )}
                                        </Badge>
                                    </div>
                                ))}
                            </div>
                        </CardContent>
                    </Card>
                ))}
            </div>

            {/* Delete Confirmation Dialog */}
            <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
                        <AlertDialogDescription>
                            This will permanently delete the selected tags and remove them from all trades.
                            This action cannot be undone.
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel>Cancel</AlertDialogCancel>
                        <AlertDialogAction onClick={handleDeleteTags} className="bg-red-500 hover:bg-red-600">
                            Delete Tags
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>

            {/* Edit Confirmation Dialog */}
            <AlertDialog open={showEditDialog} onOpenChange={setShowEditDialog}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>Confirm Tag Name Change</AlertDialogTitle>
                        <AlertDialogDescription>
                            Are you sure you want to change the tag name from "{tags.find(t => t.id === editingTag?.id)?.name}" to "{editingTag?.newName}"?
                            This will update the tag name everywhere it's used.
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel onClick={() => setEditingTag(null)}>Cancel</AlertDialogCancel>
                        <AlertDialogAction onClick={handleUpdateTagName}>
                            Update Name
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </div>
    );
}
        </div>
    );
}


PLEASE FOLLOWING THE NEXT INSTRUCTIONS UPDATE MY CODE AND RETURN THE FULL CODE BACK TO ME, ONLY RETURN THE FULLY UPDATED CODE, NOCOMMENTS!
BE EXTREMELY CAREFUL ON UPDATING IT DO NOT OMIT IMPORTA OR FUNCTIONS AND NO CHANGE CHANGE ANYTHING ELSE BESIDES THE INSTRUCTIONS:

'use client'

import { useState, useEffect } from 'react';
import { Tag, TagType, TAG_TYPES } from '@/types/tag';
import { Button } from "@/components/ui/button";
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import { 
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Switch } from "@/components/ui/switch";
import { Checkbox } from "@/components/ui/checkbox";
import { Plus, X, Check, Trash2 } from 'lucide-react';
import { Badge } from "@/components/ui/badge";
import { toast } from "@/components/ui/use-toast";
import API from '@/app/services/api';

export const MODERN_COLORS = [
    '#E91E63', // Bright pink
    '#EC407A', // Light pink
    '#AB47BC', // Purple
    '#5E35B1', // Deep purple
    '#3949AB', // Indigo
    '#1E88E5', // Blue
    '#00BFA5', // Teal
    '#7CB342', // Light green
    '#FDD835', // Yellow
    '#FF9800', // Orange
    '#FF7043', // Deep orange
    '#EC407A', // Pink
    '#AB47BC', // Light purple
    '#795548', // Brown
];

export default function TagsPage() {
    const [tags, setTags] = useState<Tag[]>([]);
    const [selectedTags, setSelectedTags] = useState<number[]>([]);
    const [editMode, setEditMode] = useState(false);
    const [editingTag, setEditingTag] = useState<{id: number, newName: string} | null>(null);
    const [showDeleteDialog, setShowDeleteDialog] = useState(false);
    const [showEditDialog, setShowEditDialog] = useState(false);
    const [newTagName, setNewTagName] = useState('');
    const [selectedType, setSelectedType] = useState<TagType>('TRADE_JOURNAL');
    const [isCreating, setIsCreating] = useState(false);

    const generateTagColor = (): string => {
        return MODERN_COLORS[Math.floor(Math.random() * MODERN_COLORS.length)];
    };

    const getContrastColor = (bgColor: string): string => {
        const hex = bgColor.replace('#', '');
        const r = parseInt(hex.slice(0, 2), 16);
        const g = parseInt(hex.slice(2, 4), 16);
        const b = parseInt(hex.slice(4, 6), 16);
        const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
        return luminance > 0.5 ? '#000000' : '#ffffff';
    };

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

    const handleTypeChange = (value: string) => {
        setSelectedType(value as TagType);
    };

    const fetchTags = async () => {
        try {
            const fetchedTags = await API.tags.getAll();
            setTags(fetchedTags);
        } catch (error) {
            console.error('Error fetching tags:', error);
            toast({
                title: "Error",
                description: "Failed to fetch tags",
                variant: "destructive"
            });
        }
    };

    const createTag = async () => {
        if (!newTagName.trim()) return;

        try {
            await API.tags.create({
                name: newTagName,
                type: selectedType,
                color: generateTagColor()
            });

            setNewTagName('');
            setIsCreating(false);
            await fetchTags();

            toast({
                title: "Success",
                description: "Tag created successfully",
            });
        } catch (error) {
            toast({
                title: "Error",
                description: "Failed to create tag",
                variant: "destructive"
            });
        }
    };

    const handleDeleteTags = async () => {
        try {
            for (const tagId of selectedTags) {
                await API.tags.delete(tagId);
            }
            toast({
                title: "Success",
                description: "Selected tags have been deleted",
            });
            setSelectedTags([]);
            fetchTags();
        } catch (error) {
            toast({
                title: "Error",
                description: "Failed to delete tags",
                variant: "destructive"
            });
        }
        setShowDeleteDialog(false);
    };

    const handleUpdateTagName = async () => {
        if (!editingTag) return;

        try {
            await API.tags.update(editingTag.id, { name: editingTag.newName });
            
            toast({
                title: "Success",
                description: "Tag name updated successfully",
            });
            fetchTags();
        } catch (error) {
            toast({
                title: "Error",
                description: "Failed to update tag name",
                variant: "destructive"
            });
        }
        setEditingTag(null);
        setShowEditDialog(false);
    };

    const toggleTagActive = async (tagId: number, active: boolean) => {
        try {
            await API.tags.update(tagId, { active });
            await fetchTags();
        } catch (error) {
            toast({
                title: "Error",
                description: "Failed to update tag",
                variant: "destructive"
            });
        }
    };

    const groupedTags = tags.reduce((acc, tag) => {
        if (!acc[tag.type]) {
            acc[tag.type] = [];
        }
        acc[tag.type].push(tag);
        return acc;
    }, {} as Record<string, Tag[]>);

    // ... [keep your existing return JSX but remove the duplicate grid section] ...

    return (
        <div className="container mx-auto py-6">
            {/* ... [keep your existing management controls and create tag card] ... */}

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {Object.entries(groupedTags).map(([type, tagsList]) => (
                    <Card key={type}>
                        <CardHeader>
                            <CardTitle>{type.replace(/_/g, ' ')}</CardTitle>
                            <CardDescription>{tagsList.length} tags</CardDescription>
                        </CardHeader>
                        <CardContent>
                            <div className="flex flex-wrap gap-2">
                                {tagsList.map(tag => (
                                    <div key={tag.id} className="flex items-center gap-2">
                                        {editMode && (
                                            <Checkbox
                                                checked={selectedTags.includes(tag.id)}
                                                onCheckedChange={(checked) => {
                                                    if (checked) {
                                                        setSelectedTags(prev => [...prev, tag.id]);
                                                    } else {
                                                        setSelectedTags(prev => prev.filter(id => id !== tag.id));
                                                    }
                                                }}
                                            />
                                        )}
                                        <Badge
                                            variant={tag.active ? "default" : "secondary"}
                                            className="flex items-center gap-2 px-4 py-1.5 rounded-full transition-all duration-200 hover:scale-105 hover:shadow-lg"
                                            style={{
                                                backgroundColor: tag.active ? tag.color || '#e5e7eb' : '#e5e7eb',
                                                color: tag.active && tag.color ? getContrastColor(tag.color) : '#666',
                                                fontSize: '0.875rem',
                                                fontWeight: '600',
                                                letterSpacing: '0.02em',
                                                border: 'none',
                                                boxShadow: tag.active ? '0 2px 4px rgba(0,0,0,0.1)' : 'none',
                                                textShadow: tag.active ? '0 1px 1px rgba(0,0,0,0.1)' : 'none',
                                                cursor: editMode ? 'pointer' : 'default'
                                            }}
                                            onDoubleClick={() => {
                                                if (editMode) {
                                                    setEditingTag({ id: tag.id, newName: tag.name });
                                                }
                                            }}
                                        >
                                            {editingTag?.id === tag.id ? (
                                                <>
                                                    <input
                                                        type="text"
                                                        value={editingTag.newName}
                                                        onChange={(e) => setEditingTag(prev => ({
                                                            ...prev!,
                                                            newName: e.target.value
                                                        }))}
                                                        className="bg-transparent border-none focus:outline-none"
                                                        autoFocus
                                                    />
                                                    <div className="flex items-center gap-1">
                                                        <button
                                                            onClick={() => setShowEditDialog(true)}
                                                            className="hover:scale-110 transition-transform"
                                                        >
                                                            <Check className="w-4 h-4 text-green-500" />
                                                        </button>
                                                        <button
                                                            onClick={() => setEditingTag(null)}
                                                            className="hover:scale-110 transition-transform"
                                                        >
                                                            <X className="w-4 h-4 text-red-500" />
                                                        </button>
                                                    </div>
                                                </>
                                            ) : (
                                                <>
                                                    {tag.name}
                                                    {!editMode && (
                                                        <button
                                                            onClick={() => toggleTagActive(tag.id, !tag.active)}
                                                            className="hover:scale-110 transition-transform ml-1 bg-black/10 rounded-full p-1"
                                                        >
                                                            <X className="w-3.5 h-3.5" />
                                                        </button>
                                                    )}
                                                </>
                                            )}
                                        </Badge>
                                    </div>
                                ))}
                            </div>
                        </CardContent>
                    </Card>
                ))}
            </div>

            {/* ... [keep your existing dialogs] ... */}
        </div>
    );
}