import { ContentEditable } from "@common/components/ContentEditable";
import { extractString } from "@common/utils";
import { useState } from "preact/hooks";
import styles from '../../assets/location-editor.module.css';
import { LocationScale, useAppState, type Location } from "../../contexts/state";
import LLM from "../../utils/llm";

export const LocationEditor = ({ visible }: { visible: boolean }) => {
    const { currentWorld, currentStory, dispatch, connection, model } = useAppState();
    const [showDeleteConfirm, setShowDeleteConfirm] = useState<string | null>(null);
    const [generatingShortDesc, setGeneratingShortDesc] = useState<string | null>(null);

    if (!currentWorld || !visible) {
        return null;
    }

    // When a story is selected, edit story-level locations; otherwise world-level
    const storyId = currentStory?.id ?? null;
    const worldId = currentWorld.id;
    const locations = currentStory ? currentStory.locations : currentWorld.locations;

    const handleAddLocation = () => {
        dispatch({
            type: 'ADD_LOCATION',
            worldId,
            storyId,
            location: {
                id: crypto.randomUUID(),
                name: 'New Location',
                shortDescription: '',
                description: '',
                scale: LocationScale.Room,
            },
        });
    };

    const handleEditLocation = (locationId: string, field: keyof Location, value: string | Event) => {
        dispatch({
            type: 'EDIT_LOCATION',
            worldId,
            storyId,
            locationId,
            updates: { [field]: extractString(value) },
        });
    };

    const handleDeleteLocation = (locationId: string) => {
        dispatch({
            type: 'DELETE_LOCATION',
            worldId,
            storyId,
            locationId,
        });
    };

    const handleGenerateShortDescription = async (locationId: string) => {
        if (!connection || !model) return;

        const location = locations.find(l => l.id === locationId);
        if (!location || !location.description.trim()) return;

        setGeneratingShortDesc(locationId);
        try {
            const shortDesc = await LLM.summarize(connection, model.id, location.description, 'sentence');
            handleEditLocation(locationId, 'shortDescription', shortDesc.trim());
        } catch (error) {
            console.error('Failed to generate short description:', error);
        } finally {
            setGeneratingShortDesc(null);
        }
    };

    return (
        <div class={styles.locationEditor}>
            <div class={styles.header}>
                <h2>{currentStory ? 'Story Locations' : 'World Locations'}</h2>
                <button class={styles.addButton} onClick={handleAddLocation}>
                    + Add Location
                </button>
            </div>

            <div class={styles.list}>
                {locations.length === 0 && (
                    <p class={styles.empty}>No locations yet. Add your first location!</p>
                )}

                {locations.map((location) => (
                    <div key={location.id} class={styles.locationCard}>
                        <div class={styles.cardHeader}>
                            <input
                                type="text"
                                class={styles.nameInput}
                                value={location.name}
                                onInput={(e) => handleEditLocation(location.id, 'name', e)}
                                onFocus={(e) => e.currentTarget.select()}
                                placeholder="Location name"
                            />
                            {showDeleteConfirm === location.id ? (
                                <div class={styles.deleteConfirm}>
                                    <span>Delete?</span>
                                    <button
                                        class={styles.confirmButton}
                                        onClick={() => {
                                            handleDeleteLocation(location.id);
                                            setShowDeleteConfirm(null);
                                        }}
                                    >
                                        Yes
                                    </button>
                                    <button
                                        class={styles.cancelButton}
                                        onClick={() => setShowDeleteConfirm(null)}
                                    >
                                        No
                                    </button>
                                </div>
                            ) : (
                                <button
                                    class={styles.deleteButton}
                                    onClick={() => setShowDeleteConfirm(location.id)}
                                >
                                    ×
                                </button>
                            )}
                        </div>

                        <div class={styles.field}>
                            <div class={styles.label}>Scale</div>
                            <select
                                class={styles.select}
                                value={location.scale}
                                onInput={(e) => handleEditLocation(location.id, 'scale', e)}
                            >
                                {Object.values(LocationScale).map((option) => (
                                    <option key={option} value={option}>
                                        {option.charAt(0).toUpperCase() + option.slice(1).toLowerCase()}
                                    </option>
                                ))}
                            </select>
                        </div>

                        <div class={styles.field}>
                            <div class={styles.label}>Description</div>
                            <ContentEditable
                                autoLines
                                class={styles.textarea}
                                value={location.description}
                                onInput={(e) => handleEditLocation(location.id, 'description', e)}
                                placeholder="Full location description..."
                            />
                        </div>

                        <div class={styles.field}>
                            <div class={styles.label}>
                                Short Description
                                <button
                                    class={styles.generateButton}
                                    onClick={() => handleGenerateShortDescription(location.id)}
                                    disabled={!location.description.trim() || generatingShortDesc === location.id || !connection || !model}
                                >
                                    {generatingShortDesc === location.id ? 'Generating...' : 'Generate'}
                                </button>
                            </div>
                            <textarea
                                class={styles.textarea}
                                value={location.shortDescription}
                                onInput={(e) => handleEditLocation(location.id, 'shortDescription', e)}
                                placeholder="Brief description (one line)..."
                                rows={1}
                            />
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
};
