'use client';
import React, {useContext, useMemo, useState} from 'react';
import {useLocations, UseLocationsConfig, LocationProps, Element, SubElement} from '@/hooks/settings/useLocations';
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 {SeriesLocationItem} 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 LocationSettingsList from './LocationSettingsList';
import LocationSettingsDetail from './LocationSettingsDetail';
import LocationSettingsEdit from './LocationSettingsEdit';

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

/**
 * LocationSettings - 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 LocationSettings({
    entityType = 'book',
    entityId,
    showToggle = true,
}: LocationSettingsProps): React.JSX.Element {
    const t = useTranslations();
    const {book} = useContext(BookContext);
    const [showDeleteConfirm, setShowDeleteConfirm] = useState<boolean>(false);

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

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

    const {
        sections,
        seriesLocations,
        toolEnabled,
        isLoading,
        isSeriesMode,
        bookSeriesId,
        newSectionName,
        newElementNames,
        newSubElementNames,
        viewMode,
        selectedSectionIndex,
        addSection,
        addElement,
        addSubElement,
        removeSection,
        removeElement,
        removeSubElement,
        updateElement,
        updateSubElement,
        saveLocations,
        toggleTool,
        importFromSeries,
        exportToSeries,
        setNewSectionName,
        setNewElementNames,
        setNewSubElementNames,
        enterDetailMode,
        enterEditMode,
        exitEditMode,
        backToList,
    } = useLocations(config);

    const availableSeriesLocations = useMemo(function (): SeriesLocationItem[] {
        return seriesLocations.filter(function (sl: SeriesLocationItem): boolean {
            return !sections.some(function (s: LocationProps): boolean {
                return s.seriesLocationId === sl.id;
            });
        });
    }, [seriesLocations, sections]);

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

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

    async function handleDelete(): Promise<void> {
        if (selectedSectionIndex >= 0 && sections[selectedSectionIndex]) {
            await removeSection(sections[selectedSectionIndex].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 selectedSection: LocationProps | undefined = sections[selectedSectionIndex];
    const canExport: boolean = Boolean(bookSeriesId && selectedSection && !selectedSection.seriesLocationId);

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

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

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

                                {/* Liste des sections */}
                                <LocationSettingsList
                                    sections={sections}
                                    newSectionName={newSectionName}
                                    onSectionClick={enterDetailMode}
                                    onAddSection={addSection}
                                    onNewSectionNameChange={setNewSectionName}
                                />
                            </>
                        )}
                    </div>
                )}

                {viewMode === 'detail' && selectedSection && (
                    <div className="p-4">
                        <LocationSettingsDetail section={selectedSection}/>
                    </div>
                )}

                {viewMode === 'edit' && selectedSection && (
                    <div className="p-4">
                        <LocationSettingsEdit
                            section={selectedSection}
                            newElementNames={newElementNames}
                            newSubElementNames={newSubElementNames}
                            onAddElement={addElement}
                            onAddSubElement={addSubElement}
                            onRemoveElement={removeElement}
                            onRemoveSubElement={removeSubElement}
                            onUpdateElement={updateElement}
                            onUpdateSubElement={updateSubElement}
                            onNewElementNameChange={function (sectionId: string, name: string): void {
                                setNewElementNames({...newElementNames, [sectionId]: name});
                            }}
                            onNewSubElementNameChange={function (elementIndex: number, name: string): void {
                                setNewSubElementNames({...newSubElementNames, [elementIndex]: name});
                            }}
                        />
                    </div>
                )}
            </div>

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