'use client';
import React, {useState} from 'react';
import {defaultTagColors, SpellEditState, spellPowerLevels, SpellTagProps} from '@/lib/models/Spell';
import {SeriesSpellDetailResponse} from '@/lib/models/Series';
import {SelectBoxProps} from '@/shared/interface';
import CollapsableArea from '@/components/CollapsableArea';
import InputField from '@/components/form/InputField';
import TextInput from '@/components/form/TextInput';
import TexteAreaInput from '@/components/form/TexteAreaInput';
import SelectBox from '@/components/form/SelectBox';
import SpellTagChip from '@/components/book/settings/spells/SpellTagChip';
import SyncFieldWrapper from '@/components/form/SyncFieldWrapper';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {
    faBolt,
    faBook,
    faEye,
    faHatWizard,
    faPlus,
    faPuzzlePiece,
    faStickyNote,
    faTags,
    faTriangleExclamation
} from '@fortawesome/free-solid-svg-icons';
import {useTranslations} from 'next-intl';

interface SpellSettingsEditProps {
    spell: SpellEditState;
    availableTags: SpellTagProps[];
    onSpellChange: (key: keyof SpellEditState, value: string | string[] | null) => void;
    onCreateTag: (name: string, color: string) => Promise<SpellTagProps | null>;
    seriesSpell?: SeriesSpellDetailResponse | null;
    onSyncComplete?: () => void;
}

/**
 * SpellSettingsEdit - Vue édition pour BookSetting/SerieSetting
 * Tous les champs avec SyncFieldWrapper
 * Gestion des tags inline
 * PAS de scroll interne (géré par parent)
 */
export default function SpellSettingsEdit({
    spell,
    availableTags,
    onSpellChange,
    onCreateTag,
    seriesSpell,
    onSyncComplete,
}: SpellSettingsEditProps): React.JSX.Element {
    const t = useTranslations();

    const [tagSearchQuery, setTagSearchQuery] = useState<string>('');
    const [isCreatingTag, setIsCreatingTag] = useState<boolean>(false);
    const [newTagColor, setNewTagColor] = useState<string>(defaultTagColors[0]);

    function handleAddTag(tagId: string): void {
        if (!spell.tags.includes(tagId)) {
            onSpellChange('tags', [...spell.tags, tagId]);
        }
        setTagSearchQuery('');
    }

    function handleRemoveTag(tagId: string): void {
        onSpellChange('tags', spell.tags.filter(function (id: string): boolean {
            return id !== tagId;
        }));
    }

    function getFilteredAvailableTags(): SpellTagProps[] {
        return availableTags.filter(function (tag: SpellTagProps): boolean {
            const notAlreadyAdded: boolean = !spell.tags.includes(tag.id);
            const matchesSearch: boolean = tag.name.toLowerCase().includes(tagSearchQuery.toLowerCase());
            return notAlreadyAdded && matchesSearch;
        });
    }

    function getSelectedTags(): SpellTagProps[] {
        return availableTags.filter(function (tag: SpellTagProps): boolean {
            return spell.tags.includes(tag.id);
        });
    }

    async function handleCreateTag(): Promise<void> {
        if (!tagSearchQuery.trim()) return;
        const newTag: SpellTagProps | null = await onCreateTag(tagSearchQuery.trim(), newTagColor);
        if (newTag) {
            handleAddTag(newTag.id);
            setIsCreatingTag(false);
            setNewTagColor(defaultTagColors[0]);
        }
    }

    function getLocalizedPowerLevels(): SelectBoxProps[] {
        return spellPowerLevels.map(function (level: SelectBoxProps): SelectBoxProps {
            return {
                value: level.value,
                label: t(level.label),
            };
        });
    }

    const filteredTags: SpellTagProps[] = getFilteredAvailableTags();
    const selectedTags: SpellTagProps[] = getSelectedTags();
    const showCreateOption: boolean = Boolean(
        tagSearchQuery.trim() &&
        !availableTags.some(function (tag: SpellTagProps): boolean {
            return tag.name.toLowerCase() === tagSearchQuery.toLowerCase();
        })
    );

    return (
        <div className="space-y-4 px-2 pb-4">
            {/* Informations de base */}
            <CollapsableArea title={t('spellDetail.basicInfo')} icon={faHatWizard}>
                <div className="space-y-4 p-4 bg-secondary/20 rounded-xl border border-secondary/30">
                    <InputField
                        fieldName={t('spellDetail.name')}
                        input={
                            <SyncFieldWrapper
                                seriesElementId={spell.seriesSpellId}
                                seriesValue={seriesSpell?.name || ''}
                                currentValue={spell.name}
                                bookElementId={spell.id || ''}
                                field="name"
                                elementType="spell"
                                onDownload={function (): void { onSpellChange('name', seriesSpell?.name || ''); }}
                                onSyncComplete={onSyncComplete}
                            >
                                <TextInput
                                    value={spell.name}
                                    setValue={function (e: React.ChangeEvent<HTMLInputElement>): void {
                                        onSpellChange('name', e.target.value);
                                    }}
                                    placeholder={t('spellDetail.namePlaceholder')}
                                />
                            </SyncFieldWrapper>
                        }
                    />

                    <InputField
                        fieldName={t('spellDetail.description')}
                        icon={faBook}
                        input={
                            <SyncFieldWrapper
                                seriesElementId={spell.seriesSpellId}
                                seriesValue={seriesSpell?.description || ''}
                                currentValue={spell.description}
                                bookElementId={spell.id || ''}
                                field="description"
                                elementType="spell"
                                onDownload={function (): void { onSpellChange('description', seriesSpell?.description || ''); }}
                                onSyncComplete={onSyncComplete}
                            >
                                <TexteAreaInput
                                    value={spell.description}
                                    setValue={function (e: React.ChangeEvent<HTMLTextAreaElement>): void {
                                        onSpellChange('description', e.target.value);
                                    }}
                                    placeholder={t('spellDetail.descriptionPlaceholder')}
                                />
                            </SyncFieldWrapper>
                        }
                    />

                    <InputField
                        fieldName={t('spellDetail.appearance')}
                        icon={faEye}
                        input={
                            <SyncFieldWrapper
                                seriesElementId={spell.seriesSpellId}
                                seriesValue={seriesSpell?.appearance || ''}
                                currentValue={spell.appearance}
                                bookElementId={spell.id || ''}
                                field="appearance"
                                elementType="spell"
                                onDownload={function (): void { onSpellChange('appearance', seriesSpell?.appearance || ''); }}
                                onSyncComplete={onSyncComplete}
                            >
                                <TexteAreaInput
                                    value={spell.appearance}
                                    setValue={function (e: React.ChangeEvent<HTMLTextAreaElement>): void {
                                        onSpellChange('appearance', e.target.value);
                                    }}
                                    placeholder={t('spellDetail.appearancePlaceholder')}
                                />
                            </SyncFieldWrapper>
                        }
                    />
                </div>
            </CollapsableArea>

            {/* Tags */}
            <CollapsableArea title={t('spellDetail.tags')} icon={faTags}>
                <div className="space-y-4 p-4 bg-secondary/20 rounded-xl border border-secondary/30">
                    {selectedTags.length > 0 && (
                        <div className="flex flex-wrap gap-2 mb-3">
                            {selectedTags.map(function (tag: SpellTagProps): React.JSX.Element {
                                return (
                                    <SpellTagChip
                                        key={tag.id}
                                        tag={tag}
                                        onRemove={function (): void { handleRemoveTag(tag.id); }}
                                    />
                                );
                            })}
                        </div>
                    )}

                    <TextInput
                        value={tagSearchQuery}
                        setValue={function (e: React.ChangeEvent<HTMLInputElement>): void {
                            setTagSearchQuery(e.target.value);
                        }}
                        placeholder={t('spellDetail.addTag')}
                    />

                    {filteredTags.length > 0 && (
                        <div className="flex flex-wrap gap-2">
                            {filteredTags.map(function (tag: SpellTagProps): React.JSX.Element {
                                return (
                                    <button
                                        key={tag.id}
                                        onClick={function (): void { handleAddTag(tag.id); }}
                                        className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm transition-all duration-200 hover:scale-105 hover:shadow-md border"
                                        style={{
                                            backgroundColor: `${tag.color || '#3B82F6'}20`,
                                            borderColor: `${tag.color || '#3B82F6'}50`,
                                            color: tag.color || '#3B82F6'
                                        }}
                                    >
                                        <FontAwesomeIcon icon={faPlus} className="w-3 h-3"/>
                                        {tag.name}
                                    </button>
                                );
                            })}
                        </div>
                    )}

                    {showCreateOption && !isCreatingTag && (
                        <button
                            onClick={function (): void { setIsCreatingTag(true); }}
                            className="w-full flex items-center gap-2 px-4 py-2.5 bg-tertiary hover:bg-secondary/50 transition-colors text-left rounded-xl border border-secondary/50"
                        >
                            <FontAwesomeIcon icon={faPlus} className="text-primary w-3 h-3"/>
                            <span className="text-primary font-medium">
                                {t('spellDetail.createTag', {name: tagSearchQuery})}
                            </span>
                        </button>
                    )}

                    {isCreatingTag && (
                        <div className="p-4 bg-tertiary rounded-xl border border-secondary/50">
                            <p className="text-text-secondary text-sm mb-3">
                                {t('spellDetail.createTag', {name: tagSearchQuery})}
                            </p>
                            <div className="flex flex-wrap gap-2 mb-3">
                                {defaultTagColors.map(function (color: string): React.JSX.Element {
                                    return (
                                        <button
                                            key={color}
                                            onClick={function (): void { setNewTagColor(color); }}
                                            className={`w-8 h-8 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 className="flex gap-2">
                                <button
                                    onClick={function (): void { setIsCreatingTag(false); }}
                                    className="flex-1 py-2 px-3 bg-secondary/50 text-text-primary rounded-lg hover:bg-secondary transition-colors"
                                >
                                    {t('common.cancel')}
                                </button>
                                <button
                                    onClick={handleCreateTag}
                                    className="flex-1 py-2 px-3 bg-primary text-text-primary rounded-lg hover:bg-primary-dark transition-colors"
                                >
                                    {t('common.confirm')}
                                </button>
                            </div>
                        </div>
                    )}
                </div>
            </CollapsableArea>

            {/* Niveau de puissance */}
            <CollapsableArea title={t('spellDetail.powerLevel')} icon={faBolt}>
                <div className="space-y-4 p-4 bg-secondary/20 rounded-xl border border-secondary/30">
                    <SyncFieldWrapper
                        seriesElementId={spell.seriesSpellId}
                        seriesValue={seriesSpell?.powerLevel || 'none'}
                        currentValue={spell.powerLevel || 'none'}
                        bookElementId={spell.id || ''}
                        field="powerLevel"
                        elementType="spell"
                        onDownload={function (): void { onSpellChange('powerLevel', seriesSpell?.powerLevel || null); }}
                        onSyncComplete={onSyncComplete}
                    >
                        <SelectBox
                            defaultValue={spell.powerLevel || 'none'}
                            onChangeCallBack={function (e: React.ChangeEvent<HTMLSelectElement>): void {
                                onSpellChange('powerLevel', e.target.value === 'none' ? null : e.target.value);
                            }}
                            data={getLocalizedPowerLevels()}
                        />
                    </SyncFieldWrapper>
                </div>
            </CollapsableArea>

            {/* Composants */}
            <CollapsableArea title={t('spellDetail.components')} icon={faPuzzlePiece}>
                <div className="space-y-4 p-4 bg-secondary/20 rounded-xl border border-secondary/30">
                    <SyncFieldWrapper
                        seriesElementId={spell.seriesSpellId}
                        seriesValue={seriesSpell?.components || ''}
                        currentValue={spell.components || ''}
                        bookElementId={spell.id || ''}
                        field="components"
                        elementType="spell"
                        onDownload={function (): void { onSpellChange('components', seriesSpell?.components || null); }}
                        onSyncComplete={onSyncComplete}
                    >
                        <TexteAreaInput
                            value={spell.components || ''}
                            setValue={function (e: React.ChangeEvent<HTMLTextAreaElement>): void {
                                onSpellChange('components', e.target.value || null);
                            }}
                            placeholder={t('spellDetail.componentsPlaceholder')}
                        />
                    </SyncFieldWrapper>
                </div>
            </CollapsableArea>

            {/* Limitations */}
            <CollapsableArea title={t('spellDetail.limitations')} icon={faTriangleExclamation}>
                <div className="space-y-4 p-4 bg-secondary/20 rounded-xl border border-secondary/30">
                    <SyncFieldWrapper
                        seriesElementId={spell.seriesSpellId}
                        seriesValue={seriesSpell?.limitations || ''}
                        currentValue={spell.limitations || ''}
                        bookElementId={spell.id || ''}
                        field="limitations"
                        elementType="spell"
                        onDownload={function (): void { onSpellChange('limitations', seriesSpell?.limitations || null); }}
                        onSyncComplete={onSyncComplete}
                    >
                        <TexteAreaInput
                            value={spell.limitations || ''}
                            setValue={function (e: React.ChangeEvent<HTMLTextAreaElement>): void {
                                onSpellChange('limitations', e.target.value || null);
                            }}
                            placeholder={t('spellDetail.limitationsPlaceholder')}
                        />
                    </SyncFieldWrapper>
                </div>
            </CollapsableArea>

            {/* Notes */}
            <CollapsableArea title={t('spellDetail.notes')} icon={faStickyNote}>
                <div className="space-y-4 p-4 bg-secondary/20 rounded-xl border border-secondary/30">
                    <SyncFieldWrapper
                        seriesElementId={spell.seriesSpellId}
                        seriesValue={seriesSpell?.notes || ''}
                        currentValue={spell.notes || ''}
                        bookElementId={spell.id || ''}
                        field="notes"
                        elementType="spell"
                        onDownload={function (): void { onSpellChange('notes', seriesSpell?.notes || null); }}
                        onSyncComplete={onSyncComplete}
                    >
                        <TexteAreaInput
                            value={spell.notes || ''}
                            setValue={function (e: React.ChangeEvent<HTMLTextAreaElement>): void {
                                onSpellChange('notes', e.target.value || null);
                            }}
                            placeholder={t('spellDetail.notesPlaceholder')}
                        />
                    </SyncFieldWrapper>
                </div>
            </CollapsableArea>
        </div>
    );
}
