import React, { useState } from "react";
import VideoPlayerMultiple from "./components/VideoPlayerMultiple.jsx";
import TimelineStacked from "./components/TimelineStacked.jsx";
import VideoPlayerTimelineStack from "./components/VideoPlayerTimelineStack.jsx";
import VideoUploadDropzone from "./components/VideoUploadDropzone.jsx";
import "./Explorer.css";

function Explorer() {
    const [queries, setQueries] = useState([
        { id: 1, text: "", submitted: false },
    ]);
    const [nextId, setNextId] = useState(2);
    const [uploadedVideos, setUploadedVideos] = useState([
        // Default video
    ]);

    const handleQueryChange = (id, text) => {
        setQueries((prev) =>
            prev.map((query) => (query.id === id ? { ...query, text } : query))
        );
    };

    const handleSubmitQuery = (id) => {
        const query = queries.find((q) => q.id === id);
        if (query && query.text.trim()) {
            // Mark this query as submitted
            setQueries((prev) =>
                prev.map((q) => (q.id === id ? { ...q, submitted: true } : q))
            );

            // Add a new empty query box
            setQueries((prev) => [
                ...prev,
                { id: nextId, text: "", submitted: false },
            ]);
            setNextId((prev) => prev + 1);

            // TODO: Handle the query submission (API call, etc.)
            console.log(`Submitted query: "${query.text}"`);
        }
    };

    const handleRemoveQuery = (id) => {
        if (queries.length > 1) {
            setQueries((prev) => prev.filter((query) => query.id !== id));
        }
    };

    const handleKeyPress = (e, id) => {
        if (e.key === "Enter") {
            handleSubmitQuery(id);
        }
    };

    const handleVideoUpload = (videoUrl) => {
        setUploadedVideos((prev) => [...prev, videoUrl]);
    };

    const handleVideoDelete = (index) => {
        setUploadedVideos((prev) => prev.filter((_, i) => i !== index));
    };

    return (
        <div className="explorer-container">
            {/* Video Players */}
            <div className="multiple-timelines-videos">
                {uploadedVideos.map((videoSrc, index) => (
                    <VideoPlayerTimelineStack
                        key={index}
                        video_src={videoSrc}
                        onDelete={() => handleVideoDelete(index)}
                    />
                ))}
            </div>
            <VideoUploadDropzone onVideoUpload={handleVideoUpload} />
        </div>
    );
}

export default Explorer;
