"use client";
import { useRouter, useSearchParams } from "next/navigation";
import React, { useState, useRef, useEffect } from "react";

export function BoardToolbar({ boardId }: { boardId: string }) {
  const router = useRouter();
  const sp = useSearchParams();
  const sort = (sp.get("sort") as "recent" | "popular" | "views" | "likes" | "comments" | null) ?? "recent";
  const scope = (sp.get("scope") as "q" | "author" | null) ?? "q"; // q: 제목+내용, author: 작성자
  const defaultText = scope === "author" ? sp.get("author") ?? "" : sp.get("q") ?? "";
  const period = sp.get("period") ?? "all"; // all | 1d | 1w | 1m

  const onChangeSort = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const next = new URLSearchParams(sp.toString());
    next.set("sort", e.target.value);
    router.push(`/boards/${boardId}?${next.toString()}` , { scroll: false });
  };

  const pushSort = (value: string) => {
    const next = new URLSearchParams(sp.toString());
    next.set("sort", value);
    router.push(`/boards/${boardId}?${next.toString()}`, { scroll: false });
  };

  const SortDropdown = () => {
    const [open, setOpen] = useState(false);
    const ref = useRef<HTMLDivElement | null>(null);
    useEffect(() => {
      const handler = (ev: MouseEvent) => { if (ref.current && !ref.current.contains(ev.target as Node)) setOpen(false); };
      window.addEventListener("click", handler);
      return () => window.removeEventListener("click", handler);
    }, []);
    const label =
      sort === "recent" ? "최신순" : sort === "views" ? "조회순" : sort === "likes" ? "좋아요순" : sort === "comments" ? "댓글순" : "인기순";
    const items: { value: string; text: string }[] = [
      { value: "recent", text: "최신순" },
      { value: "views", text: "조회순" },
      { value: "likes", text: "좋아요순" },
      { value: "comments", text: "댓글순" },
    ];
    return (
      <div ref={ref} className="relative">
        <button
          type="button"
          onClick={() => setOpen((v) => !v)}
          className="inline-flex h-12 px-4 items-center justify-center gap-1 rounded-[16px] border border-[#d5d5d5] bg-white text-[14px] text-[#161616] min-w-[93px] cursor-pointer hover:bg-neutral-100"
        >
          <span>{label}</span>
          <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden>
            <path d="M5 8l5 5 5-5" stroke="#707070" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
        {open && (
          <div className="absolute mt-2 left-0 z-20 bg-white rounded-[16px] p-2 shadow-[0_0_2px_rgba(0,0,0,0.05),0_4px_8px_rgba(0,0,0,0.08)] w-[93px]">
            <div className="flex flex-col gap-1">
              {items.map((it) => (
                <button
                  key={it.value}
                  type="button"
                  onClick={() => { setOpen(false); pushSort(it.value); }}
                  className={`w-full px-3 py-2 rounded-[8px] text-[14px] inline-flex items-center justify-center cursor-pointer ${
                    sort === it.value ? "bg-[#707070] text-white" : "text-[#707070] hover:bg-neutral-100"
                  }`}
                >
                  {it.text}
                </button>
              ))}
            </div>
          </div>
        )}
      </div>
    );
  };

  const ScopeDropdown = ({ value, onSelect }: { value: "q" | "author"; onSelect: (v: "q" | "author") => void }) => {
    const [open, setOpen] = useState(false);
    const ref = useRef<HTMLDivElement | null>(null);
    useEffect(() => {
      const handler = (ev: MouseEvent) => { if (ref.current && !ref.current.contains(ev.target as Node)) setOpen(false); };
      window.addEventListener("click", handler);
      return () => window.removeEventListener("click", handler);
    }, []);
    const label = value === "author" ? "작성자" : "제목+내용";
    const items: { value: "q" | "author"; text: string }[] = [
      { value: "q", text: "제목+내용" },
      { value: "author", text: "작성자" },
    ];
    return (
      <div ref={ref} className="relative">
        <button
          type="button"
          onClick={() => setOpen((v) => !v)}
          className="inline-flex h-12 px-4 items-center justify-center gap-1 rounded-[16px] border border-[#d5d5d5] bg-white text-[14px] text-[#161616] min-w-[93px] cursor-pointer hover:bg-neutral-100"
        >
          <span>{label}</span>
          <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden>
            <path d="M5 8l5 5 5-5" stroke="#707070" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
        {open && (
          <div className="absolute mt-2 left-0 z-20 bg-white rounded-[16px] p-2 shadow-[0_0_2px_rgba(0,0,0,0.05),0_4px_8px_rgba(0,0,0,0.08)] w-[120px]">
            <div className="flex flex-col gap-1">
              {items.map((it) => (
                <button
                  key={it.value}
                  type="button"
                  onClick={() => { onSelect(it.value); setOpen(false); }}
                  className={`w-full px-3 py-2 rounded-[8px] text-[14px] inline-flex items-center justify-center cursor-pointer ${
                    value === it.value ? "bg-[#707070] text-white" : "text-[#707070] hover:bg-neutral-100"
                  }`}
                >
                  {it.text}
                </button>
              ))}
            </div>
          </div>
        )}
      </div>
    );
  };

  const onChangePeriod = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const next = new URLSearchParams(sp.toString());
    const v = e.target.value;
    next.set("period", v);
    // 계산된 start 적용
    const now = new Date();
    if (v === "1d") now.setDate(now.getDate() - 1);
    if (v === "1w") now.setDate(now.getDate() - 7);
    if (v === "1m") now.setMonth(now.getMonth() - 1);
    if (v === "all") next.delete("start"); else next.set("start", now.toISOString());
    router.push(`/boards/${boardId}?${next.toString()}` , { scroll: false });
  };

  const onSubmit = (formData: FormData) => {
    const next = new URLSearchParams(sp.toString());
    const scopeSel = String(formData.get("scope") || "q");
    const text = String(formData.get("text") || "");
    next.set("scope", scopeSel);
    if (scopeSel === "author") {
      next.delete("q");
      if (text) next.set("author", text); else next.delete("author");
    } else {
      next.delete("author");
      if (text) next.set("q", text); else next.delete("q");
    }
    router.push(`/boards/${boardId}?${next.toString()}` , { scroll: false });
  };

  return (
    <div className="px-0 py-2 flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
      {/* 검색바: 모바일에서는 상단 전체폭 */}
      <form action={onSubmit} className="order-1 md:order-2 flex items-center gap-2 w-full md:w-auto">
        <input type="hidden" name="scope" value={scope} />
        <ScopeDropdown
          value={scope}
          onSelect={(v) => {
            // hidden input을 업데이트하기 위해 URL 파라미터는 변경하지 않고 폼 값만 유지
            // 검색 제출 시 onSubmit에서 반영됨
            const form = (document.activeElement as HTMLElement)?.closest("form") as HTMLFormElement | null;
            if (form) {
              const input = form.querySelector('input[name="scope"]') as HTMLInputElement | null;
              if (input) input.value = v;
            }
          }}
        />
        <div className="relative w-full md:w-96 group">
          <button
            type="submit"
            aria-label="검색 실행"
            className="absolute right-2 top-2 w-8 h-8 text-neutral-500 cursor-pointer"
          >
            <svg
              width="32"
              height="32"
              viewBox="0 0 32 32"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
              aria-hidden
              className="w-8 h-8 block group-hover:hidden group-focus-within:hidden"
            >
              <path
                d="M21 21L17.682 17.682M17.682 17.682C18.4963 16.8676 19 15.7426 19 14.5C19 12.0147 16.9853 10 14.5 10C12.0147 10 10 12.0147 10 14.5C10 16.9853 12.0147 19 14.5 19C15.7426 19 16.8676 18.4963 17.682 17.682ZM28 16C28 22.6274 22.6274 28 16 28C9.37258 28 4 22.6274 4 16C4 9.37258 9.37258 4 16 4C22.6274 4 28 9.37258 28 16Z"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
            <svg
              width="32"
              height="32"
              viewBox="0 0 32 32"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
              aria-hidden
              className="w-8 h-8 hidden group-hover:block group-focus-within:block"
            >
              <path d="M11 14.5C11 12.567 12.567 11 14.5 11C16.433 11 18 12.567 18 14.5C18 15.4668 17.6093 16.3404 16.9749 16.9749C16.3404 17.6093 15.4668 18 14.5 18C12.567 18 11 16.433 11 14.5Z" fill="#707070" />
              <path fillRule="evenodd" clipRule="evenodd" d="M16 3C8.8203 3 3 8.8203 3 16C3 23.1797 8.8203 29 16 29C23.1797 29 29 23.1797 29 16C29 8.8203 23.1797 3 16 3ZM14.5 9C11.4624 9 9 11.4624 9 14.5C9 17.5376 11.4624 20 14.5 20C15.6571 20 16.7316 19.6419 17.6174 19.0316L20.2929 21.7071C20.6834 22.0976 21.3166 22.0976 21.7071 21.7071C22.0976 21.3166 22.0976 20.6834 21.7071 20.2929L19.0316 17.6174C19.6419 16.7316 20 15.6571 20 14.5C20 11.4624 17.5376 9 14.5 9Z" fill="#707070" />
            </svg>
          </button>
          <input
            name="text"
            defaultValue={defaultText}
            placeholder="검색어를 입력해 주세요."
            className="w-full h-12 pr-12 pl-2 rounded-2xl border bg-white border-neutral-300 hover:border-[2px] hover:border-neutral-500 focus:border-2 focus:border-neutral-800 focus:outline-none transition-colors"
          />
        </div>
      </form>

      {/* 필터: 모바일에서는 검색 아래쪽 */}
      <div className="order-2 md:order-1 flex items-center gap-2">
        <SortDropdown />
      </div>
    </div>
  );
}

export default BoardToolbar;


