import React, { useState, useEffect } from "react";
import { toast } from "react-toastify";
import { Button } from "@mui/joy";
// Dropdown not used in this form; removed to avoid unused-import warnings
import { AutoComplete } from "primereact/autocomplete/autocomplete.esm.js";
import { InputText } from "primereact/inputtext/inputtext.esm.js";

export default function ReqForm() {
    const [type, setType] = useState("");
    const [title, setTitle] = useState("");
    const [year, setYear] = useState("");
    const [requester, setRequester] = useState("");
    const [selectedItem, setSelectedItem] = useState(null);
    const [selectedOverview, setSelectedOverview] = useState("");
    const [selectedTitle, setSelectedTitle] = useState("");
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [suggestions, setSuggestions] = useState([]);

    useEffect(() => {
        if (title !== selectedTitle && selectedOverview) {
            setSelectedOverview("");
            setSelectedTitle("");
        }
    }, [title, selectedTitle, selectedOverview]);

    const searchTitles = async (event) => {
        const query = event.query;
        if (query.length < 3) {
            setSuggestions([]);
            return;
        }

        try {
            const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
            if (!response.ok) {
                throw new Error(`API error: ${response.status}`);
            }
            const data = await response.json();
            setSuggestions(data);
        } catch (error) {
            console.error('Error fetching suggestions:', error);
            setSuggestions([]);
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (!title.trim()) {
            toast.error("Please fill in the required fields.");
            return;
        }

        setIsSubmitting(true);
        try {
            const response = await fetch('/api/submit', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ title, year, type, requester }),
            });
            if (!response.ok) {
                throw new Error('Submission failed');
            }
            toast.success("Request submitted successfully!");
            // Reset form
            setType("");
            setTitle("");
            setYear("");
            setRequester("");
            setSelectedOverview("");
            setSelectedTitle("");
            setSelectedItem(null);
        } catch (error) {
            console.error('Submission error:', error);
            toast.error("Failed to submit request. Please try again.");
        } finally {
            setIsSubmitting(false);
        }
    };

    const attachScrollFix = () => {
        setTimeout(() => {
            const panel = document.querySelector(".p-autocomplete-panel");
            const items = panel?.querySelector(".p-autocomplete-items");
            if (items) {
                items.style.maxHeight = "200px";
                items.style.overflowY = "auto";
                items.style.overscrollBehavior = "contain";
                const wheelHandler = (e) => {
                    const delta = e.deltaY;
                    const atTop = items.scrollTop === 0;
                    const atBottom = items.scrollTop + items.clientHeight >= items.scrollHeight;
                    if ((delta < 0 && atTop) || (delta > 0 && atBottom)) {
                        e.preventDefault();
                    } else {
                        e.stopPropagation();
                    }
                };
                items.removeEventListener("wheel", wheelHandler);
                items.addEventListener("wheel", wheelHandler, { passive: false });
            }
        }, 0);
    };

    return (
        <div className="flex items-center justify-center min-h-[60vh] p-4">
            <div className="w-full max-w-lg p-8 bg-white dark:bg-[#1E1E1E] rounded-3xl shadow-2xl border border-gray-200 dark:border-gray-700">
                <div className="text-center mb-8">
                    <h1 className="text-4xl font-bold text-gray-800 dark:text-white mb-2">
                        Request Movies/TV
                    </h1>
                    <p className="text-gray-600 dark:text-gray-400 text-sm">
                        Submit your request for review
                    </p>
                </div>
                <form onSubmit={handleSubmit} className="space-y-6">
                    <div className="space-y-2">
                        <label htmlFor="title" className="block text-sm font-semibold text-gray-700 dark:text-gray-300">
                            Title <span className="text-red-500">*</span>
                        </label>
                        <AutoComplete
                            id="title"
                            value={title}
                            suggestions={suggestions}
                            completeMethod={searchTitles}
                            onChange={(e) => setTitle(typeof e.value === 'string' ? e.value : e.value.label)}
                            onSelect={(e) => {
                                setType(e.value.mediaType === 'tv' ? 'tv' : 'movie');
                                setTitle(e.value.label);
                                setSelectedTitle(e.value.label);
                                setSelectedItem(e.value);
                                if (e.value.year) setYear(e.value.year);
                                setSelectedOverview(e.value.overview || "");
                            }}
                            placeholder="Enter movie or TV title"
                            title="Enter movie or TV show title"
                            className="w-full"
                            inputClassName="w-full border-2 border-gray-200 dark:border-gray-600 rounded-xl px-4 py-3 focus:border-[#12f8f4] transition-colors"
                            panelClassName="border-2 border-gray-200 dark:border-gray-600 rounded-xl"
                            field="label"
                            onShow={attachScrollFix}
                            itemTemplate={(item) => (
                                <div className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded">
                                    <span className="font-medium">{item.label}</span>
                                    {item.year && <span className="text-sm text-gray-500 ml-2">({item.year})</span>}
                                    <span className="text-xs text-gray-400 ml-2 uppercase">{item.mediaType === 'tv' ? 'TV' : 'Movie'}</span>
                                </div>
                            )}
                        />
                    </div>

                    {selectedOverview && (
                        <div className="space-y-2">
                            <label className="block text-sm font-semibold text-gray-700 dark:text-gray-300">
                                Synopsis
                            </label>
                            <div className="p-3 bg-gray-50 dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-600">
                                <div className="flex flex-col sm:flex-row gap-4">
                                    <div className="flex-1">
                                        <p className="text-sm text-gray-600 dark:text-gray-400 leading-relaxed">
                                            {selectedOverview}
                                        </p>
                                    </div>
                                    {selectedItem?.poster_path && (
                                        <img
                                            src={`https://image.tmdb.org/t/p/w200${selectedItem.poster_path}`}
                                            alt="Poster"
                                            className="w-24 sm:w-32 md:w-40 h-auto rounded-lg border border-gray-200 dark:border-gray-600"
                                        />
                                    )}
                                </div>
                            </div>
                        </div>
                    )}

                    <div className="space-y-2">
                        <label htmlFor="year" className="block text-sm font-semibold text-gray-700 dark:text-gray-300">
                            Year <span className="text-gray-500">(optional)</span>
                        </label>
                        <InputText
                            id="year"
                            value={year}
                            onChange={(e) => setYear(e.target.value)}
                            placeholder="e.g. 2023"
                            className="w-full border-2 border-gray-200 dark:border-gray-600 rounded-xl px-4 py-3 focus:border-[#12f8f4] transition-colors"
                        />
                    </div>

                    <div className="space-y-2">
                        <label htmlFor="requester" className="block text-sm font-semibold text-gray-700 dark:text-gray-300">
                            Your Name <span className="text-gray-500">(optional)</span>
                        </label>
                        <InputText
                            id="requester"
                            value={requester}
                            onChange={(e) => setRequester(e.target.value)}
                            placeholder="Who is requesting this?"
                            className="w-full border-2 border-gray-200 dark:border-gray-600 rounded-xl px-4 py-3 focus:border-[#12f8f4] transition-colors"
                        />
                    </div>

                    <div className="pt-4">
                        <Button
                            type="submit"
                            disabled={isSubmitting}
                            className="w-full py-3 px-6 bg-[#12f8f4] text-gray-900 font-semibold rounded-xl disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            {isSubmitting ? "Submitting..." : "Submit Request"}
                        </Button>
                    </div>
                </form>
            </div>
        </div>
    );
}