"use client";

import React, { useState } from "react";
import {
  Menu,
  Search,
  X,
  SlidersHorizontal,
  Film,
  Send,
  MessageCircle,
  Sparkles,
  RotateCcw,
} from "lucide-react";
import { getSiteLogo, getSiteName, getTelegramUrl, getWhatsappChannelUrl } from "../config/site";

interface HeaderProps {
  onToggleMenu: () => void;
  searchTerm: string;
  onSearchChange: (query: string) => void;
  onSearchSubmit?: () => void;
  selectedQuality: string;
  onQualityChange: (quality: string) => void;
  selectedLanguage: string;
  onLanguageChange: (language: string) => void;
  selectedYear: string;
  onYearChange: (year: string) => void;
  onHomeClick: () => void;
  activeCategoryName?: string;
  onResetFilters: () => void;
  hasActiveFilters: boolean;
}

const QUALITIES = ["All", "4K UHD", "1080p", "720p", "480p", "HEVC"];
const LANGUAGES = ["All", "Dual Audio", "Hindi", "English", "Tamil", "Telugu", "South"];
const YEARS = ["All", "2025", "2024", "2023", "2022", "2021", "2020"];

export function Header({
  onToggleMenu,
  searchTerm,
  onSearchChange,
  onSearchSubmit,
  selectedQuality,
  onQualityChange,
  selectedLanguage,
  onLanguageChange,
  selectedYear,
  onYearChange,
  onHomeClick,
  activeCategoryName,
  onResetFilters,
  hasActiveFilters,
}: HeaderProps) {
  const [searchExpanded, setSearchExpanded] = useState(false);
  const [filtersOpen, setFiltersOpen] = useState(false);

  const siteName = getSiteName();
  const siteLogo = getSiteLogo();
  const tgUrl = getTelegramUrl();
  const waUrl = getWhatsappChannelUrl();

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      e.preventDefault();
      onSearchSubmit?.();
      setSearchExpanded(false);
    }
  };

  return (
    <header className="sticky top-0 z-40 w-full border-b border-white/10 bg-black/80 backdrop-blur-xl transition-all duration-300">
      <div className="max-w-7xl mx-auto px-3 sm:px-6 h-16 flex items-center justify-between gap-2 sm:gap-4">
        {/* Left Section: Menu button + Brand */}
        <div className="flex items-center gap-2 sm:gap-3 shrink-0">
          <button
            id="header-menu-button"
            onClick={onToggleMenu}
            aria-label="Open side menu"
            className="p-2 sm:p-2.5 rounded-xl bg-white/[0.04] hover:bg-white/[0.08] text-white/80 hover:text-white border border-white/10 transition-colors"
          >
            <Menu className="w-5 h-5" />
          </button>

          <button
            id="header-logo-brand"
            onClick={onHomeClick}
            className="flex items-center gap-2.5 group focus:outline-none"
          >
            <div className="relative w-9 h-9 rounded-xl bg-red-600 flex items-center justify-center shadow-md shadow-red-600/30 group-hover:shadow-red-600/60 border border-red-400/40 transition-all duration-300">
              <Film className="w-5 h-5 text-white fill-white/20" />
            </div>
            <div className="flex flex-col text-left">
              <span className="text-base sm:text-lg font-black tracking-tight text-white group-hover:text-red-400 transition-colors flex items-center gap-1">
                {siteName}
                <span className="w-1.5 h-1.5 rounded-full bg-red-500 animate-ping" />
              </span>
              <span className="text-[10px] text-white/40 font-medium -mt-1 hidden sm:block">
                HD & 4K Downloads
              </span>
            </div>
          </button>
        </div>

        {/* Center / Right: Search, Filter Toggle, Social Links */}
        <div className="flex items-center justify-end gap-2 flex-1 max-w-xl">
          {/* Animated Search Bar */}
          <div
            className={`relative flex items-center transition-all duration-300 ease-out ${
              searchExpanded
                ? "w-full max-w-md sm:max-w-lg"
                : "w-9 sm:w-64"
            }`}
          >
            {searchExpanded ? (
              <form
                onSubmit={(e) => {
                  e.preventDefault();
                  onSearchSubmit?.();
                  setSearchExpanded(false);
                }}
                className="relative w-full flex items-center"
              >
                <Search className="absolute left-3 w-4 h-4 text-white/40 pointer-events-none" />
                <input
                  id="header-search-input-expanded"
                  type="text"
                  value={searchTerm}
                  onChange={(e) => onSearchChange(e.target.value)}
                  onKeyDown={handleKeyDown}
                  placeholder="Search movies, web series, anime..."
                  autoFocus
                  className="w-full h-10 pl-9 pr-9 rounded-xl bg-white/[0.07] border border-red-500/50 text-white placeholder-white/40 text-sm focus:outline-none focus:ring-2 focus:ring-red-500/50 shadow-inner"
                />
                <button
                  type="button"
                  onClick={() => {
                    onSearchChange("");
                    setSearchExpanded(false);
                  }}
                  aria-label="Clear search"
                  className="absolute right-2.5 p-1 rounded-lg hover:bg-white/10 text-white/60 hover:text-white"
                >
                  <X className="w-4 h-4" />
                </button>
              </form>
            ) : (
              <>
                {/* Collapsed on mobile, input field on desktop */}
                <form
                  onSubmit={(e) => {
                    e.preventDefault();
                    onSearchSubmit?.();
                  }}
                  className="hidden sm:flex relative w-full items-center"
                >
                  <Search className="absolute left-3 w-4 h-4 text-white/40 pointer-events-none" />
                  <input
                    id="header-search-input"
                    type="text"
                    value={searchTerm}
                    onChange={(e) => onSearchChange(e.target.value)}
                    onKeyDown={handleKeyDown}
                    placeholder="Search movies & series..."
                    className="w-full h-10 pl-9 pr-8 rounded-xl bg-white/[0.04] border border-white/10 text-white placeholder-white/40 text-sm hover:border-white/20 focus:outline-none focus:border-red-500/50 transition-colors"
                  />
                  {searchTerm && (
                    <button
                      type="button"
                      onClick={() => onSearchChange("")}
                      aria-label="Clear search input"
                      className="absolute right-2.5 p-1 rounded-lg hover:bg-white/10 text-white/60 hover:text-white"
                    >
                      <X className="w-3.5 h-3.5" />
                    </button>
                  )}
                </form>

                {/* Mobile icon trigger */}
                <button
                  id="header-search-toggle-mobile"
                  onClick={() => setSearchExpanded(true)}
                  aria-label="Open search bar"
                  className="sm:hidden p-2.5 rounded-xl bg-white/[0.04] hover:bg-white/[0.08] text-white/80 border border-white/10 transition-colors"
                >
                  <Search className="w-4 h-4" />
                </button>
              </>
            )}
          </div>

          {/* Filter Toggle Button */}
          <button
            id="header-filter-toggle-btn"
            onClick={() => setFiltersOpen(!filtersOpen)}
            aria-label="Toggle filters panel"
            className={`p-2 sm:px-3 sm:py-2 rounded-xl border transition-all duration-200 flex items-center gap-1.5 text-xs font-semibold ${
              filtersOpen || hasActiveFilters
                ? "bg-red-600 text-white border-red-500 shadow-md shadow-red-600/30"
                : "bg-white/[0.04] hover:bg-white/[0.08] text-white/80 hover:text-white border-white/10"
            }`}
          >
            <SlidersHorizontal className="w-4 h-4" />
            <span className="hidden md:inline">Filters</span>
            {hasActiveFilters && (
              <span className="w-2 h-2 rounded-full bg-white animate-pulse" />
            )}
          </button>

          {/* Telegram Channel Button */}
          <a
            id="header-telegram-link"
            href={tgUrl}
            target="_blank"
            rel="noopener noreferrer"
            title="Join Telegram Channel"
            className="hidden lg:flex items-center gap-1.5 px-3 py-2 rounded-xl bg-sky-600/20 hover:bg-sky-600 text-sky-400 hover:text-white border border-sky-500/30 transition-all text-xs font-semibold"
          >
            <Send className="w-3.5 h-3.5" />
            <span>Telegram</span>
          </a>

          {/* WhatsApp Channel Button */}
          <a
            id="header-whatsapp-link"
            href={waUrl}
            target="_blank"
            rel="noopener noreferrer"
            title="Join WhatsApp Channel"
            className="hidden xl:flex items-center gap-1.5 px-3 py-2 rounded-xl bg-emerald-600/20 hover:bg-emerald-600 text-emerald-400 hover:text-white border border-emerald-500/30 transition-all text-xs font-semibold"
          >
            <MessageCircle className="w-3.5 h-3.5" />
            <span>WhatsApp</span>
          </a>
        </div>
      </div>

      {/* Expandable Filter Panel */}
      {filtersOpen && (
        <div
          id="header-filter-panel"
          className="border-t border-white/10 bg-neutral-950/95 backdrop-blur-2xl p-4 sm:p-6 animate-in slide-in-from-top-2 duration-200"
        >
          <div className="max-w-7xl mx-auto space-y-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Sparkles className="w-4 h-4 text-red-500" />
                <h4 className="text-xs font-bold uppercase tracking-wider text-white/90">
                  Quick Filter Movies & Series
                </h4>
              </div>

              {hasActiveFilters && (
                <button
                  onClick={onResetFilters}
                  className="flex items-center gap-1 text-xs text-red-400 hover:text-red-300 font-medium transition-colors"
                >
                  <RotateCcw className="w-3 h-3" />
                  <span>Reset All</span>
                </button>
              )}
            </div>

            {/* Quality Row */}
            <div className="space-y-1.5">
              <span className="text-[11px] font-medium text-white/50 uppercase tracking-wider">
                Quality
              </span>
              <div className="flex items-center gap-1.5 flex-wrap">
                {QUALITIES.map((q) => {
                  const val = q === "All" ? "" : q;
                  const isActive = selectedQuality === val;
                  return (
                    <button
                      key={q}
                      onClick={() => onQualityChange(val)}
                      className={`px-3 py-1 rounded-lg text-xs font-medium transition-all ${
                        isActive
                          ? "bg-red-600 text-white border border-red-400/40 shadow-sm"
                          : "bg-white/[0.04] text-white/70 hover:bg-white/[0.08] hover:text-white border border-white/5"
                      }`}
                    >
                      {q}
                    </button>
                  );
                })}
              </div>
            </div>

            {/* Language Row */}
            <div className="space-y-1.5">
              <span className="text-[11px] font-medium text-white/50 uppercase tracking-wider">
                Language / Audio
              </span>
              <div className="flex items-center gap-1.5 flex-wrap">
                {LANGUAGES.map((l) => {
                  const val = l === "All" ? "" : l;
                  const isActive = selectedLanguage === val;
                  return (
                    <button
                      key={l}
                      onClick={() => onLanguageChange(val)}
                      className={`px-3 py-1 rounded-lg text-xs font-medium transition-all ${
                        isActive
                          ? "bg-red-600 text-white border border-red-400/40 shadow-sm"
                          : "bg-white/[0.04] text-white/70 hover:bg-white/[0.08] hover:text-white border border-white/5"
                      }`}
                    >
                      {l}
                    </button>
                  );
                })}
              </div>
            </div>

            {/* Year Row */}
            <div className="space-y-1.5">
              <span className="text-[11px] font-medium text-white/50 uppercase tracking-wider">
                Release Year
              </span>
              <div className="flex items-center gap-1.5 flex-wrap">
                {YEARS.map((y) => {
                  const val = y === "All" ? "" : y;
                  const isActive = selectedYear === val;
                  return (
                    <button
                      key={y}
                      onClick={() => onYearChange(val)}
                      className={`px-3 py-1 rounded-lg text-xs font-medium transition-all ${
                        isActive
                          ? "bg-red-600 text-white border border-red-400/40 shadow-sm"
                          : "bg-white/[0.04] text-white/70 hover:bg-white/[0.08] hover:text-white border border-white/5"
                      }`}
                    >
                      {y}
                    </button>
                  );
                })}
              </div>
            </div>
          </div>
        </div>
      )}
    </header>
  );
}
