import React, { useState } from 'react';
import { X, Plus, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from '@/components/ui/popover';
import {
    Command,
    CommandEmpty,
    CommandGroup,
    CommandInput,
    CommandItem,
    CommandList,
    CommandSeparator,
} from '@/components/ui/command';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogFooter,
} from '@/components/ui/dialog';
import { useContactTags, useTags } from '@/hooks/useContactTags';
import { useTagsManagement } from '@/hooks/useTags';
import type { Tag } from '@/hooks/useContact';

interface ContactTagsManagerProps {
    contactId: string;
    currentTags: Tag[];
}

const TAG_COLORS = [
    '#6366f1', '#8b5cf6', '#a855f7', '#d946ef',
    '#ec4899', '#f43f5e', '#ef4444', '#f97316',
    '#f59e0b', '#eab308', '#84cc16', '#22c55e',
    '#10b981', '#14b8a6', '#06b6d4', '#0ea5e9',
    '#3b82f6', '#6366f1',
];

export function ContactTagsManager({ contactId, currentTags }: ContactTagsManagerProps) {
    const [open, setOpen] = useState(false);
    const [showCreateDialog, setShowCreateDialog] = useState(false);
    const [newTagName, setNewTagName] = useState('');
    const [newTagColor, setNewTagColor] = useState(TAG_COLORS[0]);
    const [searchValue, setSearchValue] = useState('');

    const { data: allTags = [], isLoading: isLoadingTags } = useTags();
    const { addTag, removeTag, isAdding, isRemoving } = useContactTags(contactId);
    const { createTag, isCreating } = useTagsManagement();

    const currentTagIds = new Set(currentTags.map((t) => t.id));
    const availableTags = allTags.filter((t) => !currentTagIds.has(t.id));

    const handleAddTag = async (tagId: string, tagName: string) => {
        await addTag(tagId, tagName);
        setOpen(false);
        setSearchValue('');
    };

    const handleRemoveTag = async (tagId: string, tagName: string) => {
        await removeTag(tagId, tagName);
    };

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

        try {
            const newTag = await createTag({
                name: trimmedName,
                color: newTagColor,
            });

            // Pass the name directly since allTags cache hasn't refreshed yet
            await addTag(newTag.id, trimmedName);

            // Reset all state
            setNewTagName('');
            setNewTagColor(TAG_COLORS[0]);
            setSearchValue('');
            setShowCreateDialog(false);
            setOpen(false);
        } catch (error) {
            // Error is handled by the hook
        }
    };

    const handleCreateClick = () => {
        setNewTagName(searchValue);
        setShowCreateDialog(true);
    };

    const handleDialogClose = (isOpen: boolean) => {
        setShowCreateDialog(isOpen);
        if (!isOpen) {
            setNewTagName('');
            setNewTagColor(TAG_COLORS[0]);
        }
    };

    const handlePopoverClose = (isOpen: boolean) => {
        setOpen(isOpen);
        if (!isOpen) {
            setSearchValue('');
        }
    };

    return (
        <div className="space-y-3">
            <div className="flex items-center justify-between">
                <label className="text-sm font-medium text-muted-foreground">Tags</label>
                <Popover open={open} onOpenChange={handlePopoverClose}>
                    <PopoverTrigger asChild>
                        <Button
                            variant="ghost"
                            size="sm"
                            className="h-7 text-xs gap-1"
                            disabled={isLoadingTags}
                        >
                            <Plus className="h-3 w-3" />
                            Add Tag
                        </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-56 p-0" align="end">
                        <Command>
                            <CommandInput
                                placeholder="Search or create tag..."
                                value={searchValue}
                                onValueChange={setSearchValue}
                            />
                            <CommandList>
                                <CommandEmpty>
                                    {searchValue.trim() ? (
                                        <button
                                            onClick={handleCreateClick}
                                            className="w-full px-2 py-3 text-sm text-left hover:bg-accent transition-colors flex items-center gap-2"
                                        >
                                            <Plus className="h-4 w-4" />
                                            Create "{searchValue.trim()}"
                                        </button>
                                    ) : (
                                        <p className="py-3 text-center text-sm text-muted-foreground">
                                            No tags found
                                        </p>
                                    )}
                                </CommandEmpty>
                                {availableTags.length > 0 && (
                                    <CommandGroup>
                                        {availableTags.map((tag) => (
                                            <CommandItem
                                                key={tag.id}
                                                onSelect={() => handleAddTag(tag.id, tag.name)}
                                                className="cursor-pointer"
                                                disabled={isAdding}
                                            >
                                                <div className="flex items-center gap-2 flex-1">
                                                    <div
                                                        className="h-3 w-3 rounded-full shrink-0"
                                                        style={{ backgroundColor: tag.color }}
                                                    />
                                                    <span className="truncate">{tag.name}</span>
                                                </div>
                                                {isAdding && (
                                                    <Loader2 className="h-3 w-3 animate-spin" />
                                                )}
                                            </CommandItem>
                                        ))}
                                    </CommandGroup>
                                )}
                                <CommandSeparator />
                                <CommandGroup>
                                    <CommandItem
                                        onSelect={handleCreateClick}
                                        className="cursor-pointer"
                                    >
                                        <Plus className="h-4 w-4 mr-2" />
                                        Create new tag
                                    </CommandItem>
                                </CommandGroup>
                            </CommandList>
                        </Command>
                    </PopoverContent>
                </Popover>
            </div>

            <div className="flex flex-wrap gap-2">
                {currentTags.length === 0 ? (
                    <p className="text-sm text-muted-foreground">No tags</p>
                ) : (
                    currentTags.map((tag) => (
                        <Badge
                            key={tag.id}
                            variant="outline"
                            className="gap-1 pr-1"
                            style={{
                                borderColor: tag.color,
                                backgroundColor: `${tag.color}15`,
                                color: tag.color,
                            }}
                        >
                            {tag.name}
                            <button
                                onClick={() => handleRemoveTag(tag.id, tag.name)}
                                disabled={isRemoving}
                                className="ml-1 hover:bg-black/10 rounded p-0.5 transition-colors disabled:opacity-50"
                                aria-label={`Remove ${tag.name} tag`}
                            >
                                {isRemoving ? (
                                    <Loader2 className="h-3 w-3 animate-spin" />
                                ) : (
                                    <X className="h-3 w-3" />
                                )}
                            </button>
                        </Badge>
                    ))
                )}
            </div>

            {/* Create New Tag Dialog */}
            <Dialog open={showCreateDialog} onOpenChange={handleDialogClose}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>Create New Tag</DialogTitle>
                    </DialogHeader>
                    <div className="space-y-4 py-4">
                        <div className="space-y-2">
                            <Label htmlFor="tagName">Tag Name</Label>
                            <Input
                                id="tagName"
                                value={newTagName}
                                onChange={(e) => setNewTagName(e.target.value)}
                                placeholder="Enter tag name"
                                autoFocus
                                onKeyDown={(e) => {
                                    if (e.key === 'Enter' && newTagName.trim()) {
                                        e.preventDefault();
                                        handleCreateTag();
                                    }
                                }}
                            />
                        </div>
                        <div className="space-y-2">
                            <Label>Color</Label>
                            <div className="flex flex-wrap gap-2">
                                {TAG_COLORS.map((color) => (
                                    <button
                                        key={color}
                                        type="button"
                                        onClick={() => setNewTagColor(color)}
                                        className={`h-6 w-6 rounded-full transition-all ${newTagColor === color
                                                ? 'ring-2 ring-offset-2 ring-primary scale-110'
                                                : 'hover:scale-105'
                                            }`}
                                        style={{ backgroundColor: color }}
                                        aria-label={`Select color ${color}`}
                                    />
                                ))}
                            </div>
                        </div>
                        <div className="pt-2">
                            <Label>Preview</Label>
                            <div className="mt-2">
                                <Badge
                                    variant="outline"
                                    style={{
                                        borderColor: newTagColor,
                                        backgroundColor: `${newTagColor}15`,
                                        color: newTagColor,
                                    }}
                                >
                                    {newTagName.trim() || 'Tag Name'}
                                </Badge>
                            </div>
                        </div>
                    </div>
                    <DialogFooter>
                        <Button
                            variant="outline"
                            onClick={() => handleDialogClose(false)}
                            disabled={isCreating}
                        >
                            Cancel
                        </Button>
                        <Button
                            onClick={handleCreateTag}
                            disabled={isCreating || !newTagName.trim()}
                        >
                            {isCreating ? (
                                <>
                                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                                    Creating...
                                </>
                            ) : (
                                'Create & Add'
                            )}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </div>
    );
}