"use client";

import { useState, useEffect, useRef } from "react";
import { Plus, Tag as TagIcon, X, Check, Loader2 } from "lucide-react";
import {
    getEmployerTags,
    createEmployerTag,
    attachTagToApplication,
    removeTagFromApplication
} from "@/app/actions/tagActions";

interface TagSelectorProps {
    applicationId: string;
    currentTags: any[];
}

const DEFAULT_COLORS = [
    "#e2e8f0", // slate-200
    "#fecaca", // red-200
    "#fed7aa", // orange-200
    "#fef08a", // yellow-200
    "#bbf7d0", // green-200
    "#bfdbfe", // blue-200
    "#e9d5ff", // purple-200
    "#fbcfe8", // pink-200
];

export function TagSelector({ applicationId, currentTags: initialTags }: TagSelectorProps) {
    const [isOpen, setIsOpen] = useState(false);
    const [allTags, setAllTags] = useState<any[]>([]);
    const [searchQuery, setSearchQuery] = useState("");
    const [isLoading, setIsLoading] = useState(false);
    const [isMutating, setIsMutating] = useState<string | null>(null);
    const [selectedColor, setSelectedColor] = useState(DEFAULT_COLORS[0]);

    // Optimistic UI state
    const [activeTags, setActiveTags] = useState<any[]>(initialTags);
    const dropdownRef = useRef<HTMLDivElement>(null);

    // Sync if props change
    useEffect(() => {
        setActiveTags(initialTags);
    }, [initialTags]);

    useEffect(() => {
        if (isOpen && allTags.length === 0) {
            loadTags();
        }
    }, [isOpen]);

    // Close on click outside
    useEffect(() => {
        function handleClickOutside(event: MouseEvent) {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
                setIsOpen(false);
            }
        }
        if (isOpen) {
            document.addEventListener("mousedown", handleClickOutside);
        }
        return () => document.removeEventListener("mousedown", handleClickOutside);
    }, [isOpen]);

    const loadTags = async () => {
        setIsLoading(true);
        try {
            const res = await getEmployerTags();
            if (res.success) setAllTags(res.tags ?? []);
        } catch (e) {
            console.error(e);
        } finally {
            setIsLoading(false);
        }
    };

    const toggleTag = async (tag: any) => {
        const isAttached = activeTags.some(t => t.tag.id === tag.id);
        setIsMutating(tag.id);

        try {
            if (isAttached) {
                // Optimistic remove
                setActiveTags(prev => prev.filter(t => t.tag.id !== tag.id));
                const res = await removeTagFromApplication(applicationId, tag.id);
                if (!res.success) {
                    // Revert
                    setActiveTags(prev => [...prev, { tag }]);
                }
            } else {
                // Optimistic add
                setActiveTags(prev => [...prev, { tag }]);
                const res = await attachTagToApplication(applicationId, tag.id);
                if (!res.success) {
                    // Revert
                    setActiveTags(prev => prev.filter(t => t.tag.id !== tag.id));
                }
            }
        } catch (e) {
            console.error("Mutation failed", e);
            // Re-sync on failure implies reloading, but let's keep it simple
            loadTags();
        } finally {
            setIsMutating(null);
        }
    };

    const handleCreateTag = async (e: React.FormEvent) => {
        e.preventDefault();
        const normalized = searchQuery.trim();
        if (!normalized) return;

        setIsMutating("new");
        try {
            const res = await createEmployerTag(normalized, selectedColor);
            if (res.success && res.tag) {
                // Add to local dictionary
                setAllTags(prev => [...prev, res.tag].sort((a, b) => a.name.localeCompare(b.name)));

                // Immediately attach
                await toggleTag(res.tag);

                setSearchQuery("");
                setSelectedColor(DEFAULT_COLORS[0]);
            }
        } catch (e) {
            console.error("Failed to create tag", e);
        } finally {
            setIsMutating(null);
        }
    };

    // Derived lists
    const filteredGlobalTags = allTags.filter(t =>
        t.name.toLowerCase().includes(searchQuery.toLowerCase())
    );
    const isExactMatch = allTags.some(t => t.name.toLowerCase() === searchQuery.trim().toLowerCase());
    const showCreateOption = searchQuery.trim().length > 0 && !isExactMatch;

    return (
        <div className="relative inline-block" ref={dropdownRef}>
            <div className="flex flex-wrap items-center gap-1.5">
                {activeTags.map((t: any) => (
                    <span
                        key={t.tag.id}
                        className="inline-flex items-center gap-1 px-2.5 py-1 text-xs font-bold border rounded-full transition-colors group"
                        style={{
                            backgroundColor: `${t.tag.color}30`,
                            borderColor: `${t.tag.color}50`,
                            color: '#334155' // A dark slate so light colors are legible
                        }}
                    >
                        {t.tag.name}
                        <button
                            onClick={(e) => { e.stopPropagation(); toggleTag(t.tag); }}
                            disabled={isMutating === t.tag.id}
                            className="opacity-0 group-hover:opacity-100 transition-opacity hover:bg-black/10 rounded-full p-0.5"
                        >
                            <X className="w-2.5 h-2.5" />
                        </button>
                    </span>
                ))}

                <button
                    onClick={() => setIsOpen(!isOpen)}
                    className="inline-flex items-center gap-1 px-2 py-1 text-xs font-semibold text-slate-500 hover:text-primary bg-slate-100 hover:bg-slate-200 rounded-full transition-colors"
                    title="Add Tag"
                >
                    <Plus className="w-3.5 h-3.5" />
                    {activeTags.length === 0 && "Add Tag"}
                </button>
            </div>

            {isOpen && (
                <div className="absolute top-full left-0 mt-2 w-64 bg-white rounded-xl shadow-xl border border-slate-200 z-50 overflow-hidden text-sm">
                    {/* Search/Create Header */}
                    <div className="p-3 border-b border-slate-100 bg-slate-50">
                        <form onSubmit={handleCreateTag}>
                            <input
                                type="text"
                                placeholder="Search or create tag..."
                                value={searchQuery}
                                onChange={(e) => setSearchQuery(e.target.value)}
                                className="w-full px-3 py-1.5 bg-white border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                                autoFocus
                            />

                            {showCreateOption && (
                                <div className="mt-3 space-y-3">
                                    <div className="flex flex-wrap gap-1.5 px-1">
                                        {DEFAULT_COLORS.map(color => (
                                            <button
                                                key={color}
                                                type="button"
                                                onClick={() => setSelectedColor(color)}
                                                className={`w-5 h-5 rounded-full flex items-center justify-center border transition-all ${selectedColor === color ? 'border-slate-800 scale-110 shadow-sm' : 'border-transparent hover:scale-110'}`}
                                                style={{ backgroundColor: color }}
                                            >
                                                {selectedColor === color && <Check className="w-3 h-3 text-slate-800" />}
                                            </button>
                                        ))}
                                    </div>
                                    <button
                                        type="submit"
                                        disabled={isMutating === "new"}
                                        className="w-full flex items-center justify-between px-3 py-1.5 bg-primary/10 text-primary hover:bg-primary/20 rounded-lg font-semibold text-xs transition-colors"
                                    >
                                        <span>Create "{searchQuery.trim()}"</span>
                                        {isMutating === "new" ? <Loader2 className="w-3 h-3 animate-spin" /> : <Plus className="w-3.5 h-3.5" />}
                                    </button>
                                </div>
                            )}
                        </form>
                    </div>

                    {/* Tag List */}
                    <div className="max-h-60 overflow-y-auto p-1.5">
                        {isLoading ? (
                            <div className="flex justify-center p-4">
                                <Loader2 className="w-4 h-4 text-slate-300 animate-spin" />
                            </div>
                        ) : filteredGlobalTags.length === 0 && !showCreateOption ? (
                            <div className="p-4 text-center text-slate-400 text-xs text-balance">
                                No tags found. Type above to create one.
                            </div>
                        ) : (
                            <div className="space-y-1">
                                {filteredGlobalTags.map(tag => {
                                    const isAttached = activeTags.some(t => t.tag.id === tag.id);
                                    return (
                                        <button
                                            key={tag.id}
                                            onClick={() => toggleTag(tag)}
                                            disabled={isMutating === tag.id}
                                            className="w-full flex items-center justify-between px-2.5 py-1.5 hover:bg-slate-50 rounded-lg transition-colors group text-left"
                                        >
                                            <div className="flex items-center gap-2">
                                                <div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: tag.color }} />
                                                <span className="text-slate-700 font-medium truncate">{tag.name}</span>
                                            </div>
                                            {isMutating === tag.id ? (
                                                <Loader2 className="w-3.5 h-3.5 text-slate-400 animate-spin" />
                                            ) : isAttached ? (
                                                <Check className="w-4 h-4 text-primary" />
                                            ) : (
                                                <Plus className="w-4 h-4 text-slate-300 opacity-0 group-hover:opacity-100" />
                                            )}
                                        </button>
                                    );
                                })}
                            </div>
                        )}
                    </div>
                </div>
            )}
        </div>
    );
}
