import SvgChannelFilter from "@/app/components/svgs/svgChannelFilter";
import { useEffect, useMemo, useRef, useState } from "react";

type Channel = { id: string; handle: string; icon?: string };

export default function ChanalFilter({
  channel_list,
  visibleSet,
  onChangeVisible,
  isOpen: controlledOpen,
  onOpenChange,
}:{
  channel_list: Channel[];
  visibleSet: Set<string>;
  onChangeVisible: (nextVisibleIds: string[]) => void;
  isOpen?: boolean;
  onOpenChange?: (open: boolean) => void;
}) {
  const [internalOpen, setInternalOpen] = useState(false);
  const isOpen = typeof controlledOpen === 'boolean' ? controlledOpen : internalOpen;
  const setOpen = (next: boolean) => { if (onOpenChange) onOpenChange(next); else setInternalOpen(next); };
  const allIds = useMemo(() => channel_list.map(c => c.id), [channel_list]);
  const allChecked = useMemo(() => allIds.every(id => visibleSet.has(id)) && allIds.length > 0, [allIds, visibleSet]);

  const didInitRef = useRef(false);
  useEffect(() => {
    // 최초 1회만: 비어있으면 전체 선택으로 초기화
    if (!didInitRef.current) {
      didInitRef.current = true;
      if (visibleSet.size === 0 && allIds.length > 0) {
        onChangeVisible(allIds);
      }
    }
  }, [allIds]);

  const toggleOne = (id: string) => {
    const next = new Set(visibleSet);
    if (next.has(id)) next.delete(id); else next.add(id);
    onChangeVisible(Array.from(next));
  };

  const toggleAll = () => {
    if (allChecked) {
      onChangeVisible([]);
    } else {
      onChangeVisible(allIds);
    }
  };
  return (
    <>
      <div className="relative">
        <div className={`w-[36px] h-[36px] border-1  rounded-lg flex items-center justify-center  cursor-pointer 
        ${isOpen ? 'border-[#F94B37] bg-[#FFF3F2]' : 'border-border-pale bg-white '} `}
        onClick={()=>{setOpen(!isOpen)}}
        >
          <SvgChannelFilter color={isOpen ? '#F94B37' : '#848484'} width={20} height={20} />
        </div>
        {isOpen && (
          <div className="absolute top-full left-[-264px] z-50">
            <div className="w-[300px] min-h-[200px] max-h-[350px] mt-2 border-1 border-border-pale rounded-lg items-center justify-start bg-white shadow-lg flex flex-col p-3 overflow-auto">
              <div className="w-full flex items-center justify-between border-b-1 text-base font-semibold border-border-pale py-2 px-1">
                <span>채널 필터</span>
                <label className="flex items-center gap-2 text-sm cursor-pointer">
                  <input className="accent-[#F94B37]" type="checkbox" checked={allChecked} onChange={toggleAll} /> 전체 선택
                </label>
              </div>
              <div className="w-full space-y-1">
                {channel_list.map((ch) => (
                  <label
                    key={ch.id}
                    className={`w-full flex items-center justify-start gap-2 py-2 px-2 text-sm cursor-pointer rounded-md ${visibleSet.has(ch.id) ? 'bg-[#FFF3F2]' : ''}`}
                  >
                    <input
                      className="accent-[#F94B37]"
                      type="checkbox"
                      checked={visibleSet.has(ch.id)}
                      onChange={() => toggleOne(ch.id)}
                    />
                    <div className="w-[20px] h-[20px] rounded-full border-1 border-border-pale overflow-hidden">
                      {ch.icon ? (
                        <img src={ch.icon} className="w-[20px] h-[20px] rounded-full" />
                      ) : (
                        <div className="w-full h-full bg-[#e6e9ef]" />
                      )}
                    </div>
                    <span className="truncate">{ch.handle}</span>
                  </label>
                ))}
              </div>
              <button
                className="mt-2 w-full h-[36px] rounded-md bg-[#F94B37] border-1 border-[#D73B29] text-white font-semibold hover:bg-[#D73B29]"
                onClick={() => setOpen(false)}
              >
                확인
              </button>
            </div>
          </div>
        )}
      </div>
    </>
  )
}