'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 {faPlus, 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 ToolDetailHeader from '@/components/book/settings/ToolDetailHeader';
import AlertBox from '@/components/AlertBox';
import InputField from '@/components/form/InputField';
import TextInput from '@/components/form/TextInput';
import ToggleSwitch from '@/components/form/ToggleSwitch';
import SeriesImportSelector from '@/components/form/SeriesImportSelector';

import WorldEditorList from './WorldEditorList';
import WorldEditorDetail from './WorldEditorDetail';
import WorldEditorEdit from './WorldEditorEdit';

/**
 * WorldEditor - Orchestrateur pour ComposerRightBar
 * Mêmes fonctionnalités que WorldSettings, layout condensé
 * Inclut: toggle tool, import from series, export to series
 */
export default function WorldEditor(): React.JSX.Element {
    const t = useTranslations();
    const {book} = useContext(BookContext);
    const [showDeleteConfirm, setShowDeleteConfirm] = useState<boolean>(false);
    const [showAddForm, setShowAddForm] = useState<boolean>(false);

    const config: UseWorldsConfig = useMemo(function (): UseWorldsConfig {
        return {
            entityType: 'book',
            entityId: book?.bookId || '',
        };
    }, [book?.bookId]);

    const {
        worlds,
        seriesWorlds,
        selectedWorldIndex,
        toolEnabled,
        isLoading,
        bookSeriesId,
        newWorldName,
        viewMode,
        saveWorld,
        updateWorldField,
        addNewWorld,
        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]);

    // Wrapper pour convertir WorldProps en worldId
    const handleWorldClick = useCallback(function (world: WorldProps): void {
        enterDetailMode(world.id);
    }, [enterDetailMode]);

    // Gestion de l'ajout
    async function handleAddWorld(): Promise<void> {
        if (newWorldName.trim()) {
            await addNewWorld();
            setShowAddForm(false);
        } else {
            setShowAddForm(true);
        }
    }

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

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

    if (isLoading) {
        return (
            <div className="flex items-center justify-center py-8">
                <FontAwesomeIcon icon={faSpinner} className="w-6 h-6 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">
            <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}
            />

            <div className="flex-1 overflow-y-auto">
                {viewMode === 'list' && (
                    <div className="space-y-3 p-2">
                        {/* Toggle tool */}
                        <div className="bg-secondary/20 rounded-lg p-3 border border-secondary/30">
                            <InputField
                                icon={faToggleOn}
                                fieldName={t('worldSetting.enableTool')}
                                input={
                                    <ToggleSwitch
                                        checked={toolEnabled}
                                        onChange={toggleTool}
                                    />
                                }
                            />
                        </div>

                        {toolEnabled && (
                            <>
                                {/* Import from series */}
                                {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')}
                                    />
                                )}

                                {showAddForm && (
                                    <div className="px-2">
                                        <InputField
                                            input={
                                                <TextInput
                                                    value={newWorldName}
                                                    setValue={function (e: React.ChangeEvent<HTMLInputElement>): void {
                                                        setNewWorldName(e.target.value);
                                                    }}
                                                    placeholder={t('worldSetting.newWorldPlaceholder')}
                                                />
                                            }
                                            actionIcon={faPlus}
                                            actionLabel={t('worldSetting.createWorldLabel')}
                                            addButtonCallBack={async function (): Promise<void> {
                                                await addNewWorld();
                                                setShowAddForm(false);
                                            }}
                                        />
                                    </div>
                                )}

                                <WorldEditorList
                                    worlds={worlds}
                                    onWorldClick={handleWorldClick}
                                    onAddWorld={handleAddWorld}
                                />
                            </>
                        )}
                    </div>
                )}

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

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

            {showDeleteConfirm && selectedWorld && (
                <AlertBox
                    title={t('worldSetting.deleteTitle')}
                    message={t('worldSetting.deleteMessage', {name: selectedWorld.name})}
                    type="danger"
                    confirmText={t('common.delete')}
                    cancelText={t('common.cancel')}
                    onConfirm={async function (): Promise<void> { setShowDeleteConfirm(false); }}
                    onCancel={function (): void { setShowDeleteConfirm(false); }}
                />
            )}
        </div>
    );
}
