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";
import { InputText } from "primereact/inputtext";

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([]);
    const [posterLoading, setPosterLoading] = useState(true);
    const [submittedRequest, setSubmittedRequest] = useState(null); // Track successful submission
    const [csrfToken, setCsrfToken] = useState(null);

    // Get CSRF token from window global on mount
    useEffect(() => {
        if (typeof window !== 'undefined' && window._t) {
            setCsrfToken(window._t);
        }
    }, []);

    useEffect(() => {
        if (title !== selectedTitle) {
            if (selectedOverview) setSelectedOverview("");
            if (selectedItem) setSelectedItem(null);
            if (type) setType("");
            if (selectedTitle) setSelectedTitle("");
            setPosterLoading(true);
        }
    }, [title, selectedTitle, selectedOverview, selectedItem, type]);

    const searchTitles = async (event) => {
        const query = event.query;
        if (query.length < 2) {
            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;
        }

        if (!csrfToken) {
            toast.error("Security token not loaded. Please refresh the page.");
            return;
        }

        setIsSubmitting(true);
        try {
            const response = await fetch('/api/submit', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ title, year, type, requester, csrfToken }),
            });
            const responseData = await response.json().catch(() => ({}));

            if (!response.ok) {
                const errorMessage = responseData.error || 'Submission failed';
                toast.error(errorMessage);

                // If CSRF token error, require page reload
                if (response.status === 403) {
                    toast.error('Please refresh the page and try again.');
                }
                return;
            }

            // Save the new CSRF token from the response for future submissions
            if (responseData.csrfToken) {
                setCsrfToken(responseData.csrfToken);
            }

            // Store submitted request info for success view
            setSubmittedRequest({
                title,
                year,
                type,
                requester,
                poster_path: selectedItem?.poster_path,
            });
        } catch (error) {
            console.error('Submission error:', error);
            toast.error("Failed to submit request. Please try again.");
        } finally {
            setIsSubmitting(false);
        }
    };

    const resetForm = () => {
        setType("");
        setTitle("");
        setYear("");
        setRequester("");
        setSelectedOverview("");
        setSelectedTitle("");
        setSelectedItem(null);
        setSubmittedRequest(null);
        setPosterLoading(true);
        // Token was already refreshed from the submit response
    };

    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);
    };

    const formatMediaType = (mediaTypeValue) => {
        if (!mediaTypeValue) return "";
        if (mediaTypeValue === "tv") return "TV Series";
        if (mediaTypeValue === "movie") return "Movie";
        return mediaTypeValue.charAt(0).toUpperCase() + mediaTypeValue.slice(1);
    };

    const selectedTypeLabel = formatMediaType(selectedItem?.mediaType || type);

    // Success view after submission
    if (submittedRequest) {
        const typeLabel = formatMediaType(submittedRequest.type);
        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-[#141414] rounded-2xl shadow-lg shadow-neutral-900/5 dark:shadow-black/20 border border-neutral-200/60 dark:border-neutral-800/60 text-center">
                    <div className="mb-6">
                        <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-green-100 dark:bg-green-900/30 flex items-center justify-center">
                            <svg className="w-8 h-8 text-green-600 dark:text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                            </svg>
                        </div>
                        <h2 className="text-2xl font-bold text-neutral-900 dark:text-white mb-2 tracking-tight font-['IBM_Plex_Sans',sans-serif]">
                            Request Submitted!
                        </h2>
                        <p className="text-neutral-500 dark:text-neutral-400 text-sm">
                            Your request has been received and is pending review.
                        </p>
                    </div>

                    <div className="p-4 bg-neutral-50 dark:bg-neutral-900/50 rounded-xl border border-neutral-200/60 dark:border-neutral-700/60 mb-6">
                        <div className="flex items-center gap-4">
                            {submittedRequest.poster_path && (
                                <img
                                    src={`https://image.tmdb.org/t/p/w92${submittedRequest.poster_path}`}
                                    alt="Poster"
                                    className="w-16 h-auto rounded-lg border border-neutral-200 dark:border-neutral-700"
                                />
                            )}
                            <div className="flex-1 text-left">
                                <p className="font-semibold text-neutral-900 dark:text-white">
                                    {submittedRequest.title}
                                </p>
                                <p className="text-sm text-neutral-500 dark:text-neutral-400">
                                    {submittedRequest.year && `${submittedRequest.year} · `}
                                    {typeLabel || 'Media'}
                                </p>
                                {submittedRequest.requester && (
                                    <p className="text-xs text-neutral-400 dark:text-neutral-500 mt-1">
                                        Requested by: {submittedRequest.requester}
                                    </p>
                                )}
                            </div>
                        </div>
                    </div>

                    <Button
                        onClick={resetForm}
                        className="w-full py-3 px-6 bg-neutral-900 dark:bg-white text-white dark:text-neutral-900 font-semibold rounded-xl hover:bg-neutral-800 dark:hover:bg-neutral-100 transition-colors shadow-sm"
                    >
                        Submit Another Request
                    </Button>
                </div>
            </div>
        );
    }

    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-[#141414] rounded-2xl shadow-lg shadow-neutral-900/5 dark:shadow-black/20 border border-neutral-200/60 dark:border-neutral-800/60">
                <div className="text-center mb-8">
                    <h1 className="text-3xl font-bold text-neutral-900 dark:text-white mb-2 tracking-tight font-['IBM_Plex_Sans',sans-serif]">
                        Request Movies/TV
                    </h1>
                    <p className="text-neutral-500 dark:text-neutral-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-medium text-neutral-700 dark:text-neutral-300">
                            Title <span className="text-red-500">*</span>
                        </label>
                        <AutoComplete
                            id="title"
                            value={title}
                            suggestions={suggestions}
                            completeMethod={searchTitles}
                            minLength={2}
                            delay={300}
                            onChange={(e) => {
                                // Handle both string input and object selection
                                const val = e.target?.value ?? e.value;
                                setTitle(typeof val === 'string' ? val : val?.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 border-neutral-200 dark:border-neutral-700 rounded-xl px-4 py-3 bg-white dark:bg-neutral-900/50 focus:border-blue-500 dark:focus:border-blue-400 focus:ring-2 focus:ring-blue-500/20 transition-all outline-none"
                            panelClassName="rounded-xl overflow-hidden"
                            field="label"
                            autoComplete="off"
                            onShow={attachScrollFix}
                            itemTemplate={(item) => (
                                <div className="p-2 rounded">
                                    <span className="font-medium">{item.label}</span>
                                    {item.year && <span className="text-sm text-neutral-500 ml-2">({item.year})</span>}
                                    <span className="text-xs text-neutral-400 ml-2 uppercase">{item.mediaType === 'tv' ? 'TV' : 'Movie'}</span>
                                </div>
                            )}
                        />
                        {selectedItem && selectedTypeLabel && (
                            <div className="text-xs font-medium uppercase text-neutral-500 dark:text-neutral-400 tracking-wide">
                                Selected type: <span className="font-bold text-neutral-700 dark:text-neutral-200">{selectedTypeLabel}</span>
                            </div>
                        )}
                    </div>

                    {selectedOverview && (
                        <div className="space-y-2">
                            <label className="block text-sm font-medium text-neutral-700 dark:text-neutral-300">
                                Synopsis
                            </label>
                            <div className="p-4 bg-neutral-50 dark:bg-neutral-900/50 rounded-xl border border-neutral-200/60 dark:border-neutral-700/60">
                                <div className="flex flex-col sm:flex-row gap-4">
                                    <div className="flex-1">
                                        <p className="text-sm text-neutral-600 dark:text-neutral-400 leading-relaxed">
                                            {selectedOverview}
                                        </p>
                                    </div>
                                    {selectedItem?.poster_path && (
                                        <div className="relative w-24 sm:w-32 md:w-40 flex-shrink-0 overflow-hidden rounded-lg">
                                            {posterLoading && (
                                                <div className="w-full bg-neutral-200 dark:bg-neutral-700 rounded-lg animate-pulse" style={{ aspectRatio: '2/3' }} />
                                            )}
                                            <img
                                                src={`https://image.tmdb.org/t/p/w200${selectedItem.poster_path}`}
                                                alt="Poster"
                                                className={`w-full h-auto rounded-lg border border-neutral-200 dark:border-neutral-700 transition-opacity duration-300 ${posterLoading ? 'hidden' : 'block'}`}
                                                onLoad={() => setPosterLoading(false)}
                                                onError={() => setPosterLoading(false)}
                                            />
                                        </div>
                                    )}
                                </div>
                            </div>
                        </div>
                    )}

                    <div className="space-y-2">
                        <label htmlFor="year" className="block text-sm font-medium text-neutral-700 dark:text-neutral-300">
                            Year <span className="text-neutral-400">(optional)</span>
                        </label>
                        <InputText
                            id="year"
                            value={year}
                            onChange={(e) => setYear(e.target.value)}
                            placeholder="e.g. 2023"
                            className="w-full border border-neutral-200 dark:border-neutral-700 rounded-xl px-4 py-3 bg-white dark:bg-neutral-900/50 focus:border-blue-500 dark:focus:border-blue-400 focus:ring-2 focus:ring-blue-500/20 transition-all outline-none"
                        />
                    </div>

                    <div className="space-y-2">
                        <label htmlFor="requester" className="block text-sm font-medium text-neutral-700 dark:text-neutral-300">
                            Your Name <span className="text-neutral-400">(optional)</span>
                        </label>
                        <InputText
                            id="requester"
                            value={requester}
                            onChange={(e) => setRequester(e.target.value)}
                            placeholder="Who is requesting this?"
                            className="w-full border border-neutral-200 dark:border-neutral-700 rounded-xl px-4 py-3 bg-white dark:bg-neutral-900/50 focus:border-blue-500 dark:focus:border-blue-400 focus:ring-2 focus:ring-blue-500/20 transition-all outline-none"
                        />
                    </div>

                    <div className="pt-4">
                        <Button
                            type="submit"
                            disabled={isSubmitting}
                            className="w-full py-3 px-6 bg-neutral-900 dark:bg-white text-white dark:text-neutral-900 font-semibold rounded-xl hover:bg-neutral-800 dark:hover:bg-neutral-100 disabled:opacity-50 disabled:cursor-not-allowed transition-colors shadow-sm"
                        >
                            {isSubmitting ? "Submitting..." : "Submit Request"}
                        </Button>
                    </div>
                </form>
            </div>
        </div>
    );
}