"use client";

import { Input } from "@/components/ui/input";
import { Search, XCircle } from "lucide-react";
import { ReactNode, useState, useEffect } from "react";

interface SearchFilterProps {
  searchValue: string;
  onSearchChange: (value: string) => void;
  searchPlaceholder?: string;
  filterButton?: boolean;
  onFilterClick?: () => void;
  extraActions?: ReactNode;
}

export function SearchFilter({
  searchValue,
  onSearchChange,
  searchPlaceholder = "검색",
  filterButton: _filterButton = true,
  onFilterClick: _onFilterClick,
  extraActions
}: SearchFilterProps) {
  const [isMobile, setIsMobile] = useState(false);

  useEffect(() => {
    const checkMobile = () => {
      // Next.js SSR 호환성: typeof window 체크
      if (typeof window !== "undefined") {
        setIsMobile(window.innerWidth < 640); // sm breakpoint
      }
    };

    checkMobile();
    window.addEventListener('resize', checkMobile);

    return () => window.removeEventListener('resize', checkMobile);
  }, []);

  return (
    <div className={`flex gap-3 ${extraActions ? 'flex-col xl:flex-row xl:items-center xl:flex-wrap' : 'flex-col sm:flex-row sm:items-center'}`}>
      <div className={`relative ${extraActions ? 'xl:flex-1 xl:min-w-0 xl:max-w-xs' : 'flex-1'}`}>
        <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-4 h-4" />
        <Input
          placeholder={isMobile ? "내용을 검색해주세요." : searchPlaceholder}
          value={searchValue}
          onChange={(e) => onSearchChange(e.target.value)}
          className="pl-10 pr-8 text-[14px]"
        />
        {searchValue && (
          <button
            type="button"
            onClick={() => onSearchChange('')}
            className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground/60 hover:text-muted-foreground transition-colors"
          >
            <XCircle className="w-4 h-4" />
          </button>
        )}
      </div>
      {extraActions && (
        <div className="flex flex-col gap-2 xl:flex-row xl:items-center xl:flex-wrap">
          {extraActions}
        </div>
      )}
    </div>
  );
}