'use client';
import React, {useContext, useState} from 'react';
import {SpellTagProps} from "@/lib/types/spell";
import {defaultTagColors} from "@/lib/constants/spell";
import SpellTagChip from "@/components/book/settings/spells/SpellTagChip";
import InputField from "@/components/form/InputField";
import TextInput from "@/components/form/TextInput";
import Modal from "@/components/ui/Modal";
import {Pencil, Plus, Tag, Trash2} from 'lucide-react';
import {useTranslations} from '@/lib/i18n';
import {AlertContext, AlertContextProps} from "@/context/AlertContext";
import IconContainer from '@/components/ui/IconContainer';
import Button from '@/components/ui/Button';
import IconButton from '@/components/ui/IconButton';
import {dynamicBg} from '@/lib/utils/dynamicStyles';

interface SpellTagManagerProps {
    tags: SpellTagProps[];
    onCreateTag: (name: string, color: string) => Promise<SpellTagProps | null>;
    onUpdateTag: (tagId: string, name: string, color: string) => Promise<boolean>;
    onDeleteTag: (tagId: string) => Promise<boolean>;
}

export default function SpellTagManager(
    {
        tags,
        onCreateTag,
        onUpdateTag,
        onDeleteTag,
    }: SpellTagManagerProps) {
    const t = useTranslations();
    const {successMessage}: AlertContextProps = useContext<AlertContextProps>(AlertContext);
    
    const [newTagName, setNewTagName] = useState<string>('');
    const [newTagColor, setNewTagColor] = useState<string>(defaultTagColors[0]);
    const [editingTag, setEditingTag] = useState<SpellTagProps | null>(null);
    const [editTagName, setEditTagName] = useState<string>('');
    const [editTagColor, setEditTagColor] = useState<string>('');
    const [showEditModal, setShowEditModal] = useState<boolean>(false);
    const [tagToDelete, setTagToDelete] = useState<SpellTagProps | null>(null);
    const [showDeleteConfirm, setShowDeleteConfirm] = useState<boolean>(false);
    
    async function handleAddTag(): Promise<void> {
        if (!newTagName.trim()) {
            return;
        }
        const newTag: SpellTagProps | null = await onCreateTag(newTagName.trim(), newTagColor);
        if (newTag) {
            setNewTagName('');
            setNewTagColor(defaultTagColors[0]);
            successMessage(t("spellTagManager.successAdd"));
        }
    }
    
    function handleEditClick(tag: SpellTagProps): void {
        setEditingTag(tag);
        setEditTagName(tag.name);
        setEditTagColor(tag.color || defaultTagColors[0]);
        setShowEditModal(true);
    }
    
    async function handleUpdateTag(): Promise<void> {
        if (!editingTag || !editTagName.trim()) {
            return;
        }
        const success: boolean = await onUpdateTag(editingTag.id, editTagName.trim(), editTagColor);
        if (success) {
            setShowEditModal(false);
            setEditingTag(null);
            successMessage(t("spellTagManager.successUpdate"));
        }
    }
    
    function handleDeleteClick(tag: SpellTagProps): void {
        setTagToDelete(tag);
        setShowDeleteConfirm(true);
    }
    
    async function handleDeleteTag(): Promise<void> {
        if (!tagToDelete) {
            return;
        }
        const success: boolean = await onDeleteTag(tagToDelete.id);
        if (success) {
            setShowDeleteConfirm(false);
            setTagToDelete(null);
            successMessage(t("spellTagManager.successDelete"));
        }
    }
    
    return (
        <div className="space-y-4 p-4">
            <div className="space-y-4">
                <div className="bg-tertiary rounded-xl p-4">
                    <h3 className="text-text-primary font-semibold mb-3">{t("spellTagManager.addTag")}</h3>
                    <div className="space-y-3">
                        <InputField
                            fieldName={t("spellTagManager.tagName")}
                            input={
                                <TextInput
                                    value={newTagName}
                                    setValue={(e) => setNewTagName(e.target.value)}
                                    placeholder={t("spellTagManager.tagNamePlaceholder")}
                                />
                            }
                        />
                        <div>
                            <span
                                className="text-text-primary text-sm font-medium mb-2 block">{t("spellTagManager.tagColor")}</span>
                            <div className="flex flex-wrap gap-2">
                                {defaultTagColors.map((color: string) => (
                                    <button
                                        key={color}
                                        onClick={() => setNewTagColor(color)}
                                        className={`w-10 h-10 rounded-full transition-all duration-200 ${newTagColor === color ? 'ring-2 ring-offset-2 ring-primary' : 'hover:ring-1 hover:ring-primary/50'} ${dynamicBg(color)}`}
                                    />
                                ))}
                            </div>
                        </div>
                        <Button variant="primary" icon={Plus} onClick={handleAddTag} disabled={!newTagName.trim()}
                                fullWidth>
                            {t("spellTagManager.addTag")}
                        </Button>
                    </div>
                </div>
                
                <div className="overflow-y-auto max-h-[calc(100vh-500px)]">
                    {tags.length === 0 ? (
                        <div className="flex flex-col items-center justify-center py-12 text-center">
                            <IconContainer icon={Tag} size="lg" shape="circle"/>
                            <p className="text-muted text-sm">{t("spellTagManager.noTags")}</p>
                        </div>
                    ) : (
                        <div className="space-y-2">
                            {tags.map((tag: SpellTagProps) => (
                                <div
                                    key={tag.id}
                                    className="flex items-center justify-between p-3 bg-secondary rounded-xl"
                                >
                                    <SpellTagChip tag={tag}/>
                                    <div className="flex items-center gap-2">
                                        <IconButton icon={Pencil} variant="ghost" size="sm"
                                                    onClick={() => handleEditClick(tag)}/>
                                        <IconButton icon={Trash2} variant="danger" size="sm"
                                                    onClick={() => handleDeleteClick(tag)}/>
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            </div>
            
            {showEditModal && editingTag && (
                <Modal
                    title={t("spellTagManager.editTag")}
                    size="sm"
                    onClose={() => setShowEditModal(false)}
                    onConfirm={handleUpdateTag}
                    confirmText={t("common.confirm")}
                    cancelText={t("common.cancel")}
                >
                    <div className="p-6 space-y-4">
                        <InputField
                            fieldName={t("spellTagManager.tagName")}
                            input={
                                <TextInput
                                    value={editTagName}
                                    setValue={(e) => setEditTagName(e.target.value)}
                                    placeholder={t("spellTagManager.tagNamePlaceholder")}
                                />
                            }
                        />
                        <div>
                            <span
                                className="text-text-primary text-sm font-medium mb-2 block">{t("spellTagManager.tagColor")}</span>
                            <div className="flex flex-wrap gap-2">
                                {defaultTagColors.map((color: string) => (
                                    <button
                                        key={color}
                                        onClick={() => setEditTagColor(color)}
                                        className={`w-10 h-10 rounded-full transition-all duration-200 ${editTagColor === color ? 'ring-2 ring-offset-2 ring-primary' : 'hover:ring-1 hover:ring-primary/50'} ${dynamicBg(color)}`}
                                    />
                                ))}
                            </div>
                        </div>
                        <div className="pt-2">
                            <span className="text-text-secondary text-sm">{t("spellTagManager.preview")}</span>
                            <div className="mt-2">
                                <SpellTagChip tag={{
                                    id: editingTag.id,
                                    name: editTagName || editingTag.name,
                                    color: editTagColor
                                }}/>
                            </div>
                        </div>
                    </div>
                </Modal>
            )}
            
            {showDeleteConfirm && tagToDelete && (
                <Modal
                    title={t("spellTagManager.deleteTagTitle")}
                    size="sm"
                    onClose={() => setShowDeleteConfirm(false)}
                    onConfirm={handleDeleteTag}
                    confirmText={t("spellTagManager.delete")}
                    cancelText={t("common.cancel")}
                >
                    <div className="p-6">
                        <p className="text-text-secondary">{t("spellTagManager.confirmDelete")}</p>
                        <div className="mt-4">
                            <SpellTagChip tag={tagToDelete}/>
                        </div>
                    </div>
                </Modal>
            )}
        </div>
    );
}
