"use client";

import React, { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";

type SearchBarProps = {
  variant?: "header" | "landing";
};

type Suggestion = {
  id: number;
  title?: string | null;
  name?: string | null;
  poster_path?: string | null;
  release_date?: string | null;
  first_air_date?: string | null;
  media_type?: "movie" | "tv";
  type?: "movie" | "tv";
  poster?: string;
  href?: string;
};

export default function SearchBar({ variant = "header" }: SearchBarProps) {
  const router = useRouter();
  const wrapperRef = useRef<HTMLDivElement | null>(null);

  // Browser/session level cache: same query dobara API hit nahi karegi
  const suggestionCacheRef = useRef<Record<string, Suggestion[]>>({});

  const [query, setQuery] = useState("");
  const [suggestions, setSuggestions] = useState<Suggestion[]>([]);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  const isLanding = variant === "landing";

  const getPosterUrl = (path?: string | null) => {
    if (!path) {
      return "https://images.unsplash.com/photo-1440404653325-ab127d49abc1?q=80&w=200&auto=format&fit=crop";
    }

    if (path.startsWith("http")) {
      return path;
    }

    return `https://image.tmdb.org/t/p/w185${path}`;
  };

  const getItemTitle = (item: Suggestion) => {
    return item.title || item.name || "Untitled";
  };

  const getItemYear = (item: Suggestion) => {
    const date = item.release_date || item.first_air_date;
    return date ? date.substring(0, 4) : "N/A";
  };

  const getItemType = (item: Suggestion): "movie" | "tv" => {
    return item.type || item.media_type || (item.name ? "tv" : "movie");
  };

  const getItemHref = (item: Suggestion) => {
    if (item.href) {
      return item.href;
    }

    const type = getItemType(item);
    return type === "tv" ? `/tv/${item.id}` : `/movie/${item.id}`;
  };

  const handleSearch = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    const cleanQuery = query.trim();

    if (!cleanQuery) {
      return;
    }

    setShowSuggestions(false);
    router.push(`/search?q=${encodeURIComponent(cleanQuery)}`);
  };

  useEffect(() => {
    const cleanQuery = query.trim();
    const cacheKey = cleanQuery.toLowerCase();

    // 3 letters se pehle API call nahi hogi
    if (cleanQuery.length < 3) {
      setSuggestions([]);
      setShowSuggestions(false);
      setIsLoading(false);
      return;
    }

    // Same query agar pehle search ho chuki hai to API dobara hit nahi hogi
    const cachedSuggestions = suggestionCacheRef.current[cacheKey];

    if (cachedSuggestions) {
      setSuggestions(cachedSuggestions);
      setShowSuggestions(true);
      setIsLoading(false);
      return;
    }

    const controller = new AbortController();

    const timer = setTimeout(async () => {
      try {
        setIsLoading(true);

        const response = await fetch(
          `/api/search?q=${encodeURIComponent(cleanQuery)}`,
          {
            signal: controller.signal,
          }
        );

        if (!response.ok) {
          throw new Error(`Suggestion API failed: ${response.status}`);
        }

        const data = await response.json();
        const results: Suggestion[] = data.results || [];

        suggestionCacheRef.current[cacheKey] = results;

        setSuggestions(results);
        setShowSuggestions(true);
      } catch (error: any) {
        if (error?.name !== "AbortError") {
          console.error("Suggestion fetch failed:", error);
        }
      } finally {
        setIsLoading(false);
      }
    }, 700);

    return () => {
      clearTimeout(timer);
      controller.abort();
    };
  }, [query]);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        wrapperRef.current &&
        !wrapperRef.current.contains(event.target as Node)
      ) {
        setShowSuggestions(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  return (
    <div
      ref={wrapperRef}
      className={`position-relative ${isLanding ? "w-100" : ""}`}
    >
      <form onSubmit={handleSearch} className="w-100">
        <div
          className={`d-flex align-items-center overflow-hidden shadow-lg ${
            isLanding
              ? "bg-white rounded-pill landing-search-box"
              : "bg-dark border border-secondary rounded-pill header-search-box"
          }`}
          style={{
            minHeight: isLanding ? "66px" : "46px",
            border: isLanding
              ? "5px solid rgba(255,255,255,0.12)"
              : undefined,
          }}
        >
          <span
            className={
              isLanding ? "ps-4 pe-2 text-dark" : "ps-3 pe-2 text-white-50"
            }
          >
            <i className={`bi bi-search ${isLanding ? "fs-4" : ""}`}></i>
          </span>

          <input
            type="text"
            value={query}
            onChange={(event) => setQuery(event.target.value)}
            onFocus={() => {
              if (suggestions.length > 0) {
                setShowSuggestions(true);
              }
            }}
            placeholder="Search movies or TV series..."
            className={`form-control border-0 shadow-none ${
              isLanding ? "text-dark" : "text-white"
            }`}
            autoComplete="off"
            style={{
              height: isLanding ? "60px" : "44px",
              background: "transparent",
              fontSize: isLanding ? "1rem" : "0.92rem",
            }}
          />

          <button
            type="submit"
            className={`btn rounded-pill fw-bold ${
              isLanding ? "btn-danger px-4 me-2" : "btn-danger px-3 me-1"
            }`}
            style={{
              height: isLanding ? "48px" : "36px",
              minWidth: isLanding ? "112px" : "78px",
              fontSize: isLanding ? "1rem" : "0.85rem",
            }}
          >
            Search
          </button>
        </div>
      </form>

      {showSuggestions && (suggestions.length > 0 || isLoading) && (
        <div
          className="position-absolute start-50 translate-middle-x bg-dark border border-secondary rounded-4 shadow-lg text-start search-suggestions-dropdown"
          style={{
            top: isLanding ? "78px" : "54px",
            width: "100%",
            minWidth: isLanding ? "100%" : "360px",
            maxWidth: isLanding ? "720px" : "420px",
            maxHeight: isLanding ? "430px" : "360px",
            overflowY: "auto",
            overflowX: "hidden",
            zIndex: 9999,
          }}
        >
          {isLoading && suggestions.length === 0 && (
            <div className="p-3 text-white-50 small">Searching...</div>
          )}

          {suggestions.map((item) => {
            const title = getItemTitle(item);
            const type = getItemType(item);
            const href = getItemHref(item);
            const poster = item.poster || getPosterUrl(item.poster_path);

            return (
              <Link
                key={`${type}-${item.id}`}
                href={href}
                className="d-flex align-items-center gap-3 p-3 text-decoration-none border-bottom border-secondary search-suggestion-item"
                style={{ color: "white" }}
                onClick={() => setShowSuggestions(false)}
              >
                <img
                  src={poster}
                  alt={title}
                  style={{
                    width: isLanding ? "44px" : "38px",
                    height: isLanding ? "64px" : "56px",
                    objectFit: "cover",
                    borderRadius: "8px",
                    background: "#111",
                  }}
                />

                <div className="flex-grow-1 overflow-hidden">
                  <div className="fw-semibold text-truncate">{title}</div>

                  <div className="small text-white-50">
                    {getItemYear(item)} •{" "}
                    {type === "tv" ? "TV Series" : "Movie"}
                  </div>
                </div>

                <i className="bi bi-chevron-right text-white-50"></i>
              </Link>
            );
          })}

          {query.trim().length >= 3 && (
            <button
              type="button"
              onClick={() => {
                setShowSuggestions(false);
                router.push(`/search?q=${encodeURIComponent(query.trim())}`);
              }}
              className="btn w-100 text-start text-white p-3 border-0"
            >
              View all results for{" "}
              <strong className="text-danger">"{query.trim()}"</strong>
            </button>
          )}
        </div>
      )}
    </div>
  );
}