'use client';
import React, {useCallback, useContext, useMemo, useState} from 'react';
import {useWorlds, UseWorldsConfig} from '@/hooks/settings/useWorlds';
import {useTranslations} from 'next-intl';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faSpinner, faToggleOn} from '@fortawesome/free-solid-svg-icons';
import {BookContext} from '@/context/BookContext';
import {WorldProps} from '@/lib/models/World';
import {SeriesWorldProps} from '@/lib/models/Series';
import InputField from '@/components/form/InputField';
import ToggleSwitch from '@/components/form/ToggleSwitch';
import SeriesImportSelector from '@/components/form/SeriesImportSelector';
import ToolDetailHeader from '@/components/book/settings/ToolDetailHeader';
import AlertBox from '@/components/AlertBox';

import WorldSettingsList from './WorldSettingsList';
import WorldSettingsDetail from './WorldSettingsDetail';
import WorldSettingsEdit from './WorldSettingsEdit';

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

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

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

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

    const {
        worlds,
        seriesWorlds,
        selectedWorldIndex,
        toolEnabled,
        isLoading,
        isSeriesMode,
        bookSeriesId,
        newWorldName,
        viewMode,
        addNewWorld,
        saveWorld,
        updateWorldField,
        toggleTool,
        importFromSeries,
        exportToSeries,
        refreshSeriesWorlds,
        setNewWorldName,
        setWorlds,
        getSeriesWorldForCurrentWorld,
        enterDetailMode,
        enterEditMode,
        exitEditMode,
        backToList,
    } = useWorlds(config);

    const availableSeriesWorlds = useMemo(function (): SeriesWorldProps[] {
        return seriesWorlds.filter(function (sw: SeriesWorldProps): boolean {
            return !worlds.some(function (w: WorldProps): boolean {
                return w.seriesWorldId === sw.id;
            });
        });
    }, [seriesWorlds, worlds]);

    const handleWorldFieldChange = useCallback(function (field: keyof WorldProps, value: string): void {
        updateWorldField(field, value);
    }, [updateWorldField]);

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

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

    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 selectedWorld: WorldProps | undefined = worlds[selectedWorldIndex];
    const canExport: boolean = Boolean(bookSeriesId && selectedWorld && !selectedWorld.seriesWorldId);

    return (
        <div className="flex flex-col h-full">
            {/* Header - uniquement pour detail/edit */}
            <ToolDetailHeader
                title={selectedWorld?.name || ''}
                defaultTitle={t('worldSetting.newWorld')}
                viewMode={viewMode}
                isNew={false}
                onBack={backToList}
                onEdit={enterEditMode}
                onSave={handleSave}
                onCancel={handleCancel}
                onExport={canExport ? exportToSeries : undefined}
                showExport={canExport}
                showDelete={false}
            />

            {/* 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('worldSetting.enableTool')}
                                    input={
                                        <ToggleSwitch
                                            checked={toolEnabled}
                                            onChange={toggleTool}
                                        />
                                    }
                                />
                                <p className="text-muted text-sm mt-2">
                                    {t('worldSetting.enableToolDescription')}
                                </p>
                            </div>
                        )}

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

                                {/* Liste des mondes */}
                                <WorldSettingsList
                                    worlds={worlds}
                                    onWorldClick={enterDetailMode}
                                    onAddWorld={addNewWorld}
                                    newWorldName={newWorldName}
                                    onNewWorldNameChange={setNewWorldName}
                                />
                            </>
                        )}
                    </div>
                )}

                {viewMode === 'detail' && selectedWorld && (
                    <div className="p-4">
                        <WorldSettingsDetail
                            world={selectedWorld}
                            seriesWorld={getSeriesWorldForCurrentWorld()}
                        />
                    </div>
                )}

                {viewMode === 'edit' && selectedWorld && (
                    <div className="p-4">
                        <WorldSettingsEdit
                            world={selectedWorld}
                            worlds={worlds}
                            selectedWorldIndex={selectedWorldIndex}
                            setWorlds={setWorlds}
                            onWorldFieldChange={handleWorldFieldChange}
                            seriesWorld={getSeriesWorldForCurrentWorld()}
                            isSeriesMode={isSeriesMode}
                            onSyncComplete={refreshSeriesWorlds}
                        />
                    </div>
                )}
            </div>
        </div>
    );
}
