'use client';
import React, {useCallback, useContext, useMemo, useState} from 'react';
import {useSpells, UseSpellsConfig} from '@/hooks/settings/useSpells';
import {useTranslations} from 'next-intl';
import {SpellEditState, SpellListItem, SpellTagProps} from '@/lib/models/Spell';
import {SeriesSpellListItem} from '@/lib/models/Series';
import {BookContext} from '@/context/BookContext';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faSpinner, faToggleOn} from '@fortawesome/free-solid-svg-icons';

import ToolDetailHeader from '@/components/book/settings/ToolDetailHeader';
import InputField from '@/components/form/InputField';
import ToggleSwitch from '@/components/form/ToggleSwitch';
import SeriesImportSelector from '@/components/form/SeriesImportSelector';
import AlertBox from '@/components/AlertBox';
import SpellTagManager from '@/components/book/settings/spells/SpellTagManager';

import SpellSettingsList from './SpellSettingsList';
import SpellSettingsDetail from './SpellSettingsDetail';
import SpellSettingsEdit from './SpellSettingsEdit';

interface SpellSettingsProps {
    entityType?: 'book' | 'series';
    entityId?: string;
    showToggle?: boolean;
}

/**
 * SpellSettings - Orchestrateur pour BookSetting/SerieSetting
 * Gère le viewMode (list/detail/edit) et coordonne les sous-composants
 * Inclut: toggle tool, import from series, tag manager
 */
export default function SpellSettings({
    entityType = 'book',
    entityId,
    showToggle = true,
}: SpellSettingsProps): React.JSX.Element {
    const t = useTranslations();
    const {book} = useContext(BookContext);
    const [showDeleteConfirm, setShowDeleteConfirm] = useState<boolean>(false);

    const resolvedEntityId: string = entityId || book?.bookId || '';

    const config: UseSpellsConfig = useMemo(function (): UseSpellsConfig {
        return {
            entityType,
            entityId: resolvedEntityId,
        };
    }, [entityType, resolvedEntityId]);

    const {
        spells,
        seriesSpells,
        tags,
        selectedSpell,
        selectedSeriesSpell,
        toolEnabled,
        isLoading,
        isSeriesMode,
        bookSeriesId,
        showTagManager,
        viewMode,
        saveSpell,
        deleteSpell,
        updateSpellField,
        toggleTool,
        importFromSeries,
        exportToSeries,
        refreshSeriesSpells,
        setSelectedSpell,
        setShowTagManager,
        enterDetailMode,
        enterEditMode,
        exitEditMode,
        backToList,
        addNewSpell,
        createTag,
        updateTag,
        deleteTag,
        handleSyncComplete,
    } = useSpells(config);

    const availableSeriesSpells = useMemo(function (): SeriesSpellListItem[] {
        return seriesSpells.filter(function (ss: SeriesSpellListItem): boolean {
            return !spells.some(function (s: SpellListItem): boolean {
                return s.seriesSpellId === ss.id;
            });
        });
    }, [seriesSpells, spells]);

    const handleSpellChange = useCallback(function (key: keyof SpellEditState, value: string | string[] | null): void {
        updateSpellField(key, value);
    }, [updateSpellField]);

    async function handleSave(): Promise<void> {
        await exitEditMode(true);
    }

    function handleCancel(): void {
        exitEditMode(false);
    }

    async function handleDelete(): Promise<void> {
        if (selectedSpell?.id) {
            await deleteSpell(selectedSpell.id);
            setShowDeleteConfirm(false);
            backToList();
        }
    }

    if (isLoading) {
        return (
            <div className="flex items-center justify-center py-12">
                <FontAwesomeIcon icon={faSpinner} className="w-8 h-8 text-primary animate-spin"/>
            </div>
        );
    }

    const isNew: boolean = selectedSpell?.id === null;
    const canExport: boolean = Boolean(bookSeriesId && selectedSpell?.id && !selectedSpell.seriesSpellId);

    return (
        <div className="flex flex-col h-full">
            {/* Header - uniquement pour detail/edit */}
            <ToolDetailHeader
                title={selectedSpell?.name || ''}
                defaultTitle={t('spellDetail.newSpell')}
                viewMode={viewMode}
                isNew={isNew}
                onBack={backToList}
                onEdit={enterEditMode}
                onSave={handleSave}
                onCancel={handleCancel}
                onDelete={function (): void { setShowDeleteConfirm(true); }}
                onExport={canExport ? exportToSeries : undefined}
                showExport={canExport}
                showDelete={Boolean(selectedSpell?.id)}
            />

            {/* Contenu principal */}
            <div className="flex-1 overflow-y-auto">
                {viewMode === 'list' && (
                    <div className="space-y-5 p-4">
                        {/* Toggle tool */}
                        {showToggle && !isSeriesMode && (
                            <div className="bg-secondary/20 rounded-xl p-5 shadow-inner border border-secondary/30">
                                <InputField
                                    icon={faToggleOn}
                                    fieldName={t('spellComponent.enableTool')}
                                    input={
                                        <ToggleSwitch
                                            checked={toolEnabled}
                                            onChange={toggleTool}
                                        />
                                    }
                                />
                                <p className="text-muted text-sm mt-2">
                                    {t('spellComponent.enableToolDescription')}
                                </p>
                            </div>
                        )}

                        {/* Contenu si outil activé */}
                        {(toolEnabled || isSeriesMode) && (
                            <>
                                {/* Import from series */}
                                {!isSeriesMode && bookSeriesId && availableSeriesSpells.length > 0 && (
                                    <SeriesImportSelector
                                        availableItems={availableSeriesSpells.map(function (ss: SeriesSpellListItem) {
                                            return {
                                                id: ss.id,
                                                name: ss.name
                                            };
                                        })}
                                        onImport={importFromSeries}
                                        placeholder={t('seriesImport.selectElement')}
                                        label={t('seriesImport.importFromSeries')}
                                    />
                                )}

                                {/* Liste des sorts */}
                                <SpellSettingsList
                                    spells={spells}
                                    tags={tags}
                                    onSpellClick={enterDetailMode}
                                    onAddSpell={addNewSpell}
                                    onManageTags={function (): void { setShowTagManager(true); }}
                                />
                            </>
                        )}
                    </div>
                )}

                {viewMode === 'detail' && selectedSpell && (
                    <div className="p-4">
                        <SpellSettingsDetail
                            spell={selectedSpell}
                            availableTags={tags}
                            seriesSpell={selectedSeriesSpell}
                        />
                    </div>
                )}

                {viewMode === 'edit' && selectedSpell && (
                    <div className="p-4">
                        <SpellSettingsEdit
                            spell={selectedSpell}
                            availableTags={tags}
                            onSpellChange={handleSpellChange}
                            onCreateTag={createTag}
                            seriesSpell={selectedSeriesSpell}
                            onSyncComplete={handleSyncComplete}
                        />
                    </div>
                )}
            </div>

            {/* Modal de confirmation de suppression */}
            {showDeleteConfirm && selectedSpell?.id && (
                <AlertBox
                    title={t('spellDetail.deleteTitle')}
                    message={t('spellDetail.deleteMessage', {name: selectedSpell.name})}
                    type="danger"
                    confirmText={t('common.delete')}
                    cancelText={t('common.cancel')}
                    onConfirm={handleDelete}
                    onCancel={function (): void { setShowDeleteConfirm(false); }}
                />
            )}

            {/* Tag Manager Modal */}
            {showTagManager && (
                <SpellTagManager
                    tags={tags}
                    onBack={function (): void { setShowTagManager(false); }}
                    onCreateTag={createTag}
                    onUpdateTag={updateTag}
                    onDeleteTag={deleteTag}
                />
            )}
        </div>
    );
}
