'use client';
import React, {useContext, useState} from 'react';
import {defaultTagColors, SpellTagProps} from "@/lib/models/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/Modal";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faArrowLeft, faEdit, faPlus, faTags, faTrash} from "@fortawesome/free-solid-svg-icons";
import {useTranslations} from "next-intl";
import {AlertContext} from "@/context/AlertContext";

interface SpellTagManagerProps {
    tags: SpellTagProps[];
    onBack: () => void;
    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,
        onBack,
        onCreateTag,
        onUpdateTag,
        onDeleteTag,
    }: SpellTagManagerProps) {
    const t = useTranslations();
    const {successMessage} = useContext(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">
            <div
                className="flex justify-between items-center p-4 border-b border-secondary/50 bg-tertiary/50 backdrop-blur-sm">
                <button
                    onClick={onBack}
                    className="flex items-center gap-2 bg-secondary/50 py-2 px-4 rounded-xl border border-secondary/50 hover:bg-secondary hover:border-secondary hover:shadow-md hover:scale-105 transition-all duration-200"
                >
                    <FontAwesomeIcon icon={faArrowLeft} className="text-primary w-4 h-4"/>
                    <span className="text-text-primary font-medium">{t("spellTagManager.back")}</span>
                </button>
                <span className="text-text-primary font-semibold text-lg flex items-center gap-2">
                    <FontAwesomeIcon icon={faTags} className="text-primary w-5 h-5"/>
                    {t("spellTagManager.title")}
                </span>
                <div className="w-24"/>
            </div>
            
            <div className="px-4 space-y-4">
                <div className="bg-secondary/20 rounded-xl p-4 border border-secondary/30">
                    <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 scale-110' : 'hover:scale-110'}`}
                                        style={{backgroundColor: color}}
                                    />
                                ))}
                            </div>
                        </div>
                        <button
                            onClick={handleAddTag}
                            disabled={!newTagName.trim()}
                            className="w-full flex items-center justify-center gap-2 py-2.5 bg-primary text-text-primary rounded-xl hover:bg-primary-dark transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            <FontAwesomeIcon icon={faPlus} className="w-4 h-4"/>
                            {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">
                            <div className="w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mb-4">
                                <FontAwesomeIcon icon={faTags} className="text-primary w-8 h-8"/>
                            </div>
                            <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/30 rounded-xl border border-secondary/50"
                                >
                                    <SpellTagChip tag={tag}/>
                                    <div className="flex items-center gap-2">
                                        <button
                                            onClick={() => handleEditClick(tag)}
                                            className="p-2 bg-secondary/50 rounded-lg hover:bg-secondary hover:scale-110 transition-all duration-200"
                                        >
                                            <FontAwesomeIcon icon={faEdit} className="text-primary w-4 h-4"/>
                                        </button>
                                        <button
                                            onClick={() => handleDeleteClick(tag)}
                                            className="p-2 bg-error/10 rounded-lg hover:bg-error/20 hover:scale-110 transition-all duration-200"
                                        >
                                            <FontAwesomeIcon icon={faTrash} className="text-error w-4 h-4"/>
                                        </button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            </div>
            
            {showEditModal && editingTag && (
                <Modal
                    title={t("spellTagManager.editTag")}
                    size="small"
                    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 scale-110' : 'hover:scale-110'}`}
                                        style={{backgroundColor: 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="small"
                    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>
    );
}
