"use client";

import { useEffect, useRef, useState, useCallback, KeyboardEvent } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Image from "next/image";
import { Search, Play, Music2, ChevronRight, Film, Headphones, Clock, X } from "lucide-react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { performSearch, setQuery } from "@/store/slices/searchSlice";
import { setTrack, setQueue } from "@/store/slices/playerSlice";
import { searchService } from "@/services/searchService";
import type { SearchItem, SearchHistoryItem } from "@/services/searchService";
import type { MusicItem } from "@/services/musicSectionService";
import { useTranslation } from "@/i18n";
import { isLoggedIn } from "@/utils/auth";

/* ── helpers ────────────────────────────────────────────────────────────────── */

function toMusicItem(item: SearchItem): MusicItem {
  return {
    id: item.id,
    contentType: item.contentType,
    title: item.title,
    thumbnail: item.thumbnail,
    landscapeImg: item.landscapeImg,
    audioUrl: item.audioUrl,
    channelName: item.channelName,
    channelImage: item.channelImage,
    duration: item.duration,
    durationMs: 0,
    views: item.views,
    likes: "",
    category: "",
    language: "",
    isDownload: false,
    isRent: false,
    rentPrice: 0,
  };
}

/* ── Video card ─────────────────────────────────────────────────────────────── */

function VideoCard({ item, index }: { item: SearchItem; index: number }) {
  const router = useRouter();
  const [hovered, setHovered] = useState(false);
  const [imgError, setImgError] = useState(false);

  return (
    <article
      className="group relative flex-shrink-0 cursor-pointer"
      style={{
        width: 256,
        animation: `srch-card-in 0.4s ease both`,
        animationDelay: `${index * 60}ms`,
      }}
      onClick={() => router.push(`/video/${item.id}`)}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >
      {/* Thumbnail */}
      <div
        className="relative w-full overflow-hidden"
        style={{
          aspectRatio: "16/9",
          borderRadius: 10,
          background: "var(--deep)",
          boxShadow: hovered
            ? "0 8px 32px rgba(var(--accent-rgb),0.22), 0 2px 8px rgba(0,0,0,0.4)"
            : "0 2px 12px rgba(0,0,0,0.3)",
          transition: "box-shadow 0.25s ease",
          transform: hovered ? "translateY(-2px)" : "translateY(0)",
        }}
      >
        {item.landscapeImg && !imgError ? (
          <Image
            src={item.landscapeImg}
            alt={item.title}
            fill
            className="object-cover"
            unoptimized
            sizes="256px"
            onError={() => setImgError(true)}
            style={{ transition: "transform 0.35s ease", transform: hovered ? "scale(1.04)" : "scale(1)" }}
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center">
            <Film size={28} color="#888" />
          </div>
        )}

        {/* Bottom gradient */}
        <div
          className="absolute inset-x-0 bottom-0 h-16 pointer-events-none"
          style={{ background: "linear-gradient(to top, rgba(0,0,0,0.75), transparent)" }}
        />

        {/* Play overlay */}
        <div
          className="absolute inset-0 flex items-center justify-center pointer-events-none"
          style={{ opacity: hovered ? 1 : 0, transition: "opacity 0.22s ease" }}
        >
          <div
            className="w-11 h-11 rounded-full flex items-center justify-center"
            style={{
              background: "rgba(var(--accent-rgb),0.9)",
              boxShadow: "0 0 0 6px rgba(var(--accent-rgb),0.2)",
              paddingLeft: 2,
            }}
          >
            <Play size={18} fill="#fff" color="#fff" />
          </div>
        </div>

        {/* Duration badge */}
        {item.duration && (
          <span
            className="absolute bottom-2 right-2 text-[9px] font-bold text-[#ffffff] px-1.5 py-0.5 rounded"
            style={{ background: "rgba(0,0,0,0.75)", letterSpacing: "0.04em" }}
          >
            {item.duration}
          </span>
        )}

        {/* Accent line on hover */}
        <div
          className="absolute bottom-0 left-0 h-0.5 rounded-full"
          style={{
            background: "var(--accent)",
            width: hovered ? "100%" : "0%",
            transition: "width 0.3s ease",
          }}
        />
      </div>

      {/* Info */}
      <div className="mt-2.5 px-0.5">
        <p
          className="text-[12px] font-semibold leading-snug line-clamp-2"
          style={{ letterSpacing: "-0.01em", color: "var(--text-primary)" }}
        >
          {item.title}
        </p>
        <div className="flex items-center gap-1.5 mt-1.5">
          {item.channelImage && (
            <div className="w-4 h-4 rounded-full overflow-hidden bg-[var(--deep)] flex-shrink-0 relative">
              <Image src={item.channelImage} alt="" fill className="object-cover" unoptimized sizes="16px" />
            </div>
          )}
          <span className="text-[10px] truncate" style={{ color: "var(--text-muted)" }}>{item.channelName}</span>
          {item.views && (
            <>
              <span style={{ color: "var(--text-muted)" }}>·</span>
              <span className="text-[10px]" style={{ color: "var(--text-muted)" }}>{item.views}</span>
            </>
          )}
        </div>
      </div>
    </article>
  );
}

/* ── Music card ─────────────────────────────────────────────────────────────── */

function MusicCard({
  item,
  index,
  allMusic,
}: {
  item: SearchItem;
  index: number;
  allMusic: SearchItem[];
}) {
  const dispatch = useAppDispatch();
  const [hovered, setHovered] = useState(false);
  const [imgError, setImgError] = useState(false);

  const handlePlay = () => {
    const track = toMusicItem(item);
    const queue = allMusic.map(toMusicItem);
    dispatch(setQueue(queue));
    dispatch(setTrack(track));
  };

  return (
    <article
      className="group relative flex-shrink-0 cursor-pointer"
      style={{
        width: 160,
        animation: `srch-card-in 0.4s ease both`,
        animationDelay: `${index * 55}ms`,
      }}
      onClick={handlePlay}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >
      {/* Cover art */}
      <div
        className="relative w-full overflow-hidden"
        style={{
          aspectRatio: "1/1",
          borderRadius: 12,
          background: "linear-gradient(135deg, var(--deep), #1a1a4e)",
          boxShadow: hovered
            ? "0 8px 28px rgba(var(--accent-rgb),0.25), 0 2px 8px rgba(0,0,0,0.4)"
            : "0 2px 10px rgba(0,0,0,0.3)",
          transition: "box-shadow 0.25s ease",
          transform: hovered ? "translateY(-3px) scale(1.01)" : "translateY(0) scale(1)",
        }}
      >
        {item.thumbnail && !imgError ? (
          <Image
            src={item.thumbnail}
            alt={item.title}
            fill
            className="object-cover"
            unoptimized
            sizes="160px"
            onError={() => setImgError(true)}
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center">
            <Music2 size={32} color="#888" />
          </div>
        )}

        <div
          className="absolute inset-0 pointer-events-none"
          style={{ background: "linear-gradient(180deg, transparent 40%, rgba(0,0,0,0.65) 100%)" }}
        />

        {/* Play overlay */}
        <div
          className="absolute inset-0 flex items-center justify-center pointer-events-none"
          style={{ opacity: hovered ? 1 : 0, transition: "opacity 0.22s ease" }}
        >
          <div
            className="w-10 h-10 rounded-full flex items-center justify-center"
            style={{
              background: "var(--accent)",
              boxShadow: "0 0 0 5px rgba(var(--accent-rgb),0.18)",
              paddingLeft: 2,
            }}
          >
            <Play size={15} fill="#fff" color="#fff" />
          </div>
        </div>

        {/* Music eq bars on hover */}
        <div
          className="absolute bottom-2 right-2 flex items-end gap-[2px]"
          style={{ height: 14, opacity: hovered ? 1 : 0, transition: "opacity 0.2s ease" }}
        >
          {[1, 2, 3].map((i) => (
            <div
              key={i}
              className="w-[2px] rounded-full"
              style={{
                background: "var(--accent)",
                height: "100%",
                animation: `srch-eq 600ms ease-in-out ${i * 100}ms infinite alternate`,
              }}
            />
          ))}
        </div>
      </div>

      {/* Info */}
      <div className="mt-2 px-0.5">
        <p className="text-[11px] font-semibold leading-snug line-clamp-2" style={{ color: "var(--text-primary)" }}>{item.title}</p>
        <p className="text-[10px] mt-0.5 truncate" style={{ color: "var(--text-muted)" }}>{item.channelName}</p>
      </div>
    </article>
  );
}

/* ── Horizontal scroll row ──────────────────────────────────────────────────── */

function ScrollRow({ children, label, icon: Icon, count }: {
  children: React.ReactNode;
  label: string;
  icon: React.ElementType;
  count: number;
}) {
  const rowRef = useRef<HTMLDivElement>(null);
  const [canScrollRight, setCanScrollRight] = useState(true);

  const checkScroll = useCallback(() => {
    const el = rowRef.current;
    if (!el) return;
    setCanScrollRight(el.scrollLeft + el.clientWidth < el.scrollWidth - 8);
  }, []);

  useEffect(() => {
    checkScroll();
    rowRef.current?.addEventListener("scroll", checkScroll, { passive: true });
    return () => rowRef.current?.removeEventListener("scroll", checkScroll);
  }, [checkScroll, children]);

  return (
    <section className="mt-8">
      {/* Section header */}
      <div className="flex items-center gap-3 mb-4 px-1">
        <div
          className="w-7 h-7 rounded-lg flex items-center justify-center flex-shrink-0"
          style={{ background: "rgba(var(--accent-rgb),0.12)", border: "1px solid rgba(var(--accent-rgb),0.2)" }}
        >
          <Icon size={13} color="var(--accent)" strokeWidth={2} />
        </div>
        <h2 className="text-sm font-bold tracking-tight" style={{ color: "var(--text-primary)" }}>{label}</h2>
        <span
          className="text-[10px] font-bold px-2 py-0.5 rounded-full"
          style={{ background: "rgba(var(--accent-rgb),0.1)", color: "var(--accent)", border: "1px solid rgba(var(--accent-rgb),0.15)" }}
        >
          {count}
        </span>
        <div className="flex-1 h-px" style={{ background: "var(--border)" }} />
        <ChevronRight size={14} style={{ color: "var(--text-muted)" }} />
      </div>

      {/* Scrollable track */}
      <div className="relative">
        <div
          ref={rowRef}
          className="flex gap-4 overflow-x-auto scrollbar-hide pb-2"
          style={{ scrollBehavior: "smooth" }}
        >
          {children}
          {/* Right spacer */}
          <div className="flex-shrink-0 w-4" />
        </div>

        {/* Right fade mask */}
        {canScrollRight && (
          <div
            className="absolute top-0 right-0 bottom-0 w-16 pointer-events-none"
            style={{ background: "linear-gradient(to right, transparent, var(--bg))" }}
          />
        )}
      </div>
    </section>
  );
}

/* ── Skeleton cards ─────────────────────────────────────────────────────────── */

function VideoSkeleton() {
  return (
    <div className="flex-shrink-0 animate-pulse" style={{ width: 256 }}>
      <div className="w-full rounded-xl" style={{ aspectRatio: "16/9", background: "var(--card)" }} />
      <div className="mt-2.5 space-y-1.5">
        <div className="h-2.5 rounded-full" style={{ background: "var(--card)", width: "90%" }} />
        <div className="h-2.5 rounded-full" style={{ background: "var(--card)", width: "55%" }} />
      </div>
    </div>
  );
}

function MusicSkeleton() {
  return (
    <div className="flex-shrink-0 animate-pulse" style={{ width: 160 }}>
      <div className="w-full rounded-xl" style={{ aspectRatio: "1/1", background: "var(--card)" }} />
      <div className="mt-2 space-y-1.5">
        <div className="h-2.5 rounded-full" style={{ background: "var(--card)", width: "85%" }} />
        <div className="h-2.5 rounded-full" style={{ background: "var(--card)", width: "55%" }} />
      </div>
    </div>
  );
}

/* ── Empty state ────────────────────────────────────────────────────────────── */

function EmptyState({ query }: { query: string }) {
  const { t } = useTranslation();
  return (
    <div className="flex flex-col items-center justify-center py-20 text-center">
      <div
        className="w-16 h-16 rounded-2xl flex items-center justify-center mb-4"
        style={{ background: "var(--btn-ghost)", border: "1px solid var(--border)" }}
      >
        <Search size={24} strokeWidth={1.5} style={{ color: "var(--text-muted)" }} />
      </div>
      <p className="text-sm font-semibold mb-1" style={{ color: "var(--text-primary)" }}>{t("search_noResults")} &ldquo;{query}&rdquo;</p>
      <p className="text-xs" style={{ color: "var(--text-muted)" }}>{t("search_tryDifferent")}</p>
    </div>
  );
}

/* ── Main page ──────────────────────────────────────────────────────────────── */

export default function SearchPage() {
  const { t } = useTranslation();
  const router = useRouter();
  const searchParams = useSearchParams();
  const dispatch = useAppDispatch();
  const { query, videos, music, isLoading, hasSearched } = useAppSelector((s) => s.search);

  const [inputVal, setInputVal] = useState(query);
  const inputRef = useRef<HTMLInputElement>(null);
  const [searchHistory, setSearchHistory] = useState<SearchHistoryItem[]>([]);

  /* Fetch search history on mount if logged in */
  useEffect(() => {
    if (!isLoggedIn()) return;
    searchService.getSearchHistory().then(setSearchHistory).catch(() => {});
  }, []);

  /* On mount, trigger search if URL has ?q= */
  useEffect(() => {
    const q = searchParams.get("q") || "";
    if (q && q !== query) {
      setInputVal(q);
      dispatch(setQuery(q));
      dispatch(performSearch(q));
    } else if (query) {
      setInputVal(query);
    }
    inputRef.current?.focus();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleSearch = useCallback((overrideQuery?: string) => {
    const q = (overrideQuery ?? inputVal).trim();
    if (!q) return;
    if (!overrideQuery) {
      // keep inputVal in sync when called from keyboard / button
    } else {
      setInputVal(overrideQuery);
    }
    dispatch(setQuery(q));
    dispatch(performSearch(q));
    router.replace(`/search?q=${encodeURIComponent(q)}`, { scroll: false });
  }, [inputVal, dispatch, router]);

  const handleRemoveHistory = useCallback((id: string) => {
    setSearchHistory((prev) => prev.filter((h) => h.id !== id));
    searchService.removeSearchHistoryItem(id).catch(() => {});
  }, []);

  const onKey = (e: KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") handleSearch(undefined);
  };

  const noResults = hasSearched && !isLoading && videos.length === 0 && music.length === 0;

  return (
    <div className="min-h-screen px-4 py-6 pb-28 md:px-8" style={{ background: "var(--bg)" }}>

      {/* ── Search bar ── */}
      <div
        className="max-w-2xl mx-auto mb-8"
        style={{ animation: "srch-rise 0.4s ease both" }}
      >
        <div
          className="flex items-center gap-3 h-12 rounded-2xl px-4 transition-all"
          style={{
            background: "var(--card)",
            border: "1px solid var(--border)",
            boxShadow: "0 4px 24px rgba(0,0,0,0.3)",
          }}
        >
          <Search size={15} color="#666" strokeWidth={2} className="flex-shrink-0" />
          <input
            ref={inputRef}
            type="text"
            className="flex-1 bg-transparent outline-none text-sm placeholder:text-[color:var(--text-muted)]"
            style={{ color: "var(--text-primary)" }}
            placeholder={t("search_channelsPlaceholder")}
            value={inputVal}
            onChange={(e) => setInputVal(e.target.value)}
            onKeyDown={onKey}
          />
          {inputVal && (
            <button
              className="text-[10px] font-bold px-3 py-1.5 rounded-lg transition-all active:scale-95"
              style={{ background: "var(--accent)", color: "#fff" }}
              onClick={() => handleSearch(undefined)}
            >
              {t("search_button")}
            </button>
          )}
        </div>
      </div>

      {/* ── Idle state ── */}
      {!hasSearched && !isLoading && (
        <div
          className="flex flex-col items-center justify-center py-24 text-center"
          style={{ animation: "srch-rise 0.5s ease both", animationDelay: "0.1s" }}
        >
          <div
            className="w-20 h-20 rounded-3xl flex items-center justify-center mb-5"
            style={{
              background: "linear-gradient(135deg, rgba(var(--accent-rgb),0.1), rgba(var(--accent-rgb),0.04))",
              border: "1px solid rgba(var(--accent-rgb),0.15)",
              boxShadow: "0 0 40px rgba(var(--accent-rgb),0.06)",
            }}
          >
            <Search size={30} color="rgba(var(--accent-rgb),0.6)" strokeWidth={1.4} />
          </div>
          <p className="text-base font-bold mb-1.5" style={{ color: "var(--text-primary)" }}>{t("search_findAnything")}</p>
          <p className="text-xs" style={{ color: "var(--text-muted)" }}>
            {t("search_description")}
          </p>
          <div className="flex items-center gap-2 mt-5 flex-wrap justify-center">
            {["Movies", "Music", "Podcasts", "Live Events", "Shorts"].map((tag) => (
              <button
                key={tag}
                className="text-[11px] font-medium px-3 py-1.5 rounded-full transition-all hover:brightness-125"
                style={{
                  background: "var(--btn-ghost)",
                  border: "1px solid var(--border)",
                  color: "var(--text-muted)",
                }}
                onClick={() => handleSearch(tag)}
              >
                {tag}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* ── Recent Searches ── */}
      {!hasSearched && !isLoading && searchHistory.length > 0 && (
        <div
          className="max-w-2xl mx-auto mt-2"
          style={{ animation: "srch-rise 0.45s ease both", animationDelay: "0.05s" }}
        >
          <div className="flex items-center gap-2 mb-3 px-1">
            <Clock size={13} color="var(--text-muted)" strokeWidth={2} />
            <h3 className="text-[11px] font-bold uppercase tracking-widest" style={{ color: "var(--text-muted)" }}>
              Recent Searches
            </h3>
          </div>
          <div
            className="rounded-2xl overflow-hidden"
            style={{ background: "var(--card)", border: "1px solid var(--border)" }}
          >
            {searchHistory.map((item, idx) => (
              <div
                key={item.id}
                className="flex items-center gap-3 px-4 py-3 cursor-pointer transition-colors hover:brightness-110"
                style={{
                  borderTop: idx > 0 ? "1px solid var(--border)" : "none",
                  background: "transparent",
                }}
                onClick={() => handleSearch(item.title)}
              >
                <Clock size={14} color="#666" strokeWidth={1.8} className="flex-shrink-0" />
                <span
                  className="flex-1 text-sm truncate"
                  style={{ color: "var(--text-primary)" }}
                >
                  {item.title}
                </span>
                <button
                  className="flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center transition-all active:scale-90"
                  style={{ background: "var(--btn-ghost)" }}
                  onClick={(e) => {
                    e.stopPropagation();
                    handleRemoveHistory(item.id);
                  }}
                  aria-label={`Remove ${item.title} from history`}
                >
                  <X size={11} color="#888" strokeWidth={2} />
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ── Loading skeletons ── */}
      {isLoading && (
        <>
          <section className="mt-4">
            <div className="flex items-center gap-2 mb-4">
              <div className="h-3 w-16 rounded-full animate-pulse" style={{ background: "var(--card)" }} />
            </div>
            <div className="flex gap-4 overflow-hidden">
              {Array.from({ length: 5 }).map((_, i) => <VideoSkeleton key={i} />)}
            </div>
          </section>
          <section className="mt-8">
            <div className="flex items-center gap-2 mb-4">
              <div className="h-3 w-16 rounded-full animate-pulse" style={{ background: "var(--card)" }} />
            </div>
            <div className="flex gap-4 overflow-hidden">
              {Array.from({ length: 6 }).map((_, i) => <MusicSkeleton key={i} />)}
            </div>
          </section>
        </>
      )}

      {/* ── No results ── */}
      {noResults && <EmptyState query={query} />}

      {/* ── Results ── */}
      {!isLoading && hasSearched && (videos.length > 0 || music.length > 0) && (
        <>
          {videos.length > 0 && (
            <ScrollRow label={t("nav_videos")} icon={Film} count={videos.length}>
              {videos.map((v, i) => (
                <VideoCard key={v.id} item={v} index={i} />
              ))}
            </ScrollRow>
          )}

          {music.length > 0 && (
            <ScrollRow label={t("nav_music")} icon={Headphones} count={music.length}>
              {music.map((m, i) => (
                <MusicCard key={m.id} item={m} index={i} allMusic={music} />
              ))}
            </ScrollRow>
          )}
        </>
      )}
    </div>
  );
}
