"use client";

import React, { useEffect, useRef, useState } from "react";
import { X } from "lucide-react";
import SeaQaQuestionList from "@/components/SeaQa/SeaQaQuestionList";
import SeaQaSidebar from "@/components/SeaQa/SeaQaSidebar";
import LoginModal from "@/components/Membership/LoginModal";
import { useGetCategoryTreeQuery } from "@/api/category.api";

const QUESTION_CATEGORY_TYPE = "seaqa";
const TYPE_OPTIONS = ["Answered", "Unanswered"];

export default function SeaQAPage() {
  const [selectedTypes, setSelectedTypes] = useState<string[]>([]);
  const [selectedTopics, setSelectedTopics] = useState<number[]>([]);
  const [loginModalOpen, setLoginModalOpen] = useState(false);
  const [questionListKey, setQuestionListKey] = useState(0);
  const [keywords, setKeywords] = useState<string[]>([]);
  const [inputValue, setInputValue] = useState("");
  const [filterDropdownOpen, setFilterDropdownOpen] = useState(false);
  const [debouncedSearch, setDebouncedSearch] = useState("");
  const [isSmallScreen, setIsSmallScreen] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);
  const filterDropdownRef = useRef<HTMLDivElement>(null);

  const { data: categoryTree = [], isLoading: topicsLoading } =
    useGetCategoryTreeQuery(QUESTION_CATEGORY_TYPE);

  const childTopics = categoryTree.flatMap((parent) => parent.childCategories);

  const toggleType = (type: string) =>
    setSelectedTypes((prev) =>
      prev.includes(type) ? prev.filter((t) => t !== type) : [...prev, type],
    );

  const toggleTopic = (id: number) =>
    setSelectedTopics((prev) =>
      prev.includes(id) ? prev.filter((t) => t !== id) : [...prev, id],
    );

  // Add a single keyword chip. Dedupe happens inside the functional update so
  // committing several at once (e.g. a pasted "a,b,c") can't double-add.
  const addKeyword = (val: string) => {
    const trimmed = val.trim().toLowerCase();
    if (!trimmed) return;
    setKeywords((prev) => (prev.includes(trimmed) ? prev : [...prev, trimmed]));
  };

  const commitInput = (val: string) => {
    addKeyword(val);
    setInputValue("");
  };

  // Mobile soft keyboards (Gboard/iOS) often don't report the comma key in
  // keydown (keyCode 229 during composition), so the comma separator is
  // detected here in onChange instead — where the typed character lands.
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const val = e.target.value;
    setInputValue(val);
    // if (val.includes(",")) {
    //   const parts = val.split(",");
    //   const last = parts.pop() ?? "";
    //   parts.forEach(addKeyword);
    //   setInputValue(last);
    // } else {
    //   setInputValue(val);
    // }
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    // Commit a keyword chip on Enter (or comma, on keyboards that report it).
    // Space is intentionally NOT a trigger so multi-word searches type naturally.
    if (e.key === "," || e.key === "Enter") {
      e.preventDefault();
      commitInput(inputValue);
    } else if (
      e.key === "Backspace" &&
      inputValue === "" &&
      keywords.length > 0
    ) {
      setKeywords((prev) => prev.slice(0, -1));
    }
  };

  const removeKeyword = (kw: string) =>
    setKeywords((prev) => prev.filter((k) => k !== kw));

  const hasChips = keywords.length > 0;

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (
        filterDropdownRef.current &&
        !filterDropdownRef.current.contains(e.target as Node)
      ) {
        setFilterDropdownOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  // Track screens below Tailwind's `sm` (640px) to shorten the search hint.
  useEffect(() => {
    const mq = window.matchMedia("(max-width: 639px)");
    const update = () => setIsSmallScreen(mq.matches);
    update();
    mq.addEventListener("change", update);
    return () => mq.removeEventListener("change", update);
  }, []);

  // Debounce: combine committed keywords + live input → searchText
  useEffect(() => {
    const combined = [...keywords, inputValue.trim()].filter(Boolean).join(" ");
    const timer = setTimeout(() => setDebouncedSearch(combined), 400);
    return () => clearTimeout(timer);
  }, [inputValue, keywords]);

  return (
    <div className="bg-[#efefef] min-h-screen">
      <div className="max-w-[1074px] mx-auto px-4 py-6 flex flex-col md:flex-row gap-6 items-start">
        {/* Left column */}
        <div className="w-full md:w-[650px] shrink-0 flex flex-col gap-3">
          {/* Search bar */}
          <div
            className="flex items-center gap-2 flex-wrap bg-white border border-[#e5e7eb] rounded-xl px-3 py-2 cursor-text focus-within:shadow-[0_0_0_2px_#93c5fd] focus-within:border-transparent transition-all"
            onClick={() => inputRef.current?.focus()}
          >
            <svg
              width="16"
              height="16"
              fill="none"
              stroke="#9ca3af"
              strokeWidth="2"
              viewBox="0 0 24 24"
              className="shrink-0"
            >
              <circle cx="11" cy="11" r="8" />
              <path strokeLinecap="round" d="M21 21l-4.35-4.35" />
            </svg>

            {/* Keyword chips */}
            {keywords.map((kw) => (
              <span
                key={kw}
                className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[12px] font-medium bg-[#eff6ff] text-[#2563eb] border border-[#bfdbfe]"
              >
                {kw}
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    removeKeyword(kw);
                  }}
                  className="flex items-center p-0 bg-transparent border-none cursor-pointer text-inherit"
                >
                  <X size={11} />
                </button>
              </span>
            ))}

            <input
              ref={inputRef}
              type="text"
              value={inputValue}
              onChange={handleChange}
              // onKeyDown={handleKeyDown}
              // onBlur={() => {
              //   if (inputValue.trim()) commitInput(inputValue);
              // }}
              // placeholder={
              //   hasChips
              //     ? "Add keyword…"
              //     : isSmallScreen
              //       ? "Search questions…"
              //       : "Search questions… (press Enter or Comma to add keyword)"
              // }
              placeholder="Search questions…"
              className="flex-1 min-w-30 text-[14px] border-none outline-none bg-transparent text-[#111827] placeholder:text-[#d1d5db]"
            />

            {/* Filter icon → Answered/Unanswered dropdown */}
            <div
              ref={filterDropdownRef}
              className="relative shrink-0"
              onClick={(e) => e.stopPropagation()}
            >
              <button
                type="button"
                onClick={() => setFilterDropdownOpen((o) => !o)}
                className={`flex items-center cursor-pointer bg-transparent border-none transition-colors ${
                  filterDropdownOpen || selectedTypes.length > 0
                    ? "text-[#3b82f6]"
                    : "text-[#9ca3af]"
                }`}
              >
                {selectedTypes.length > 0 && (
                  <span className="mr-1 text-[11px] font-semibold text-[#3b82f6]">
                    {selectedTypes.length}
                  </span>
                )}
                <svg
                  width="16"
                  height="16"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M4 6h16M7 12h10M10 18h4"
                  />
                </svg>
              </button>

              {filterDropdownOpen && (
                <div className="absolute right-0 top-full mt-2 w-44 bg-white border border-[#e5e7eb] rounded-xl shadow-lg z-50 overflow-hidden py-1">
                  {TYPE_OPTIONS.map((type) => {
                    const checked = selectedTypes.includes(type);
                    return (
                      <button
                        key={type}
                        type="button"
                        onClick={() => toggleType(type)}
                        className="w-full flex items-center gap-1.5 px-4 py-2.5 text-sm text-[#374151] hover:bg-[#f9fafb] transition-colors cursor-pointer"
                      >
                        <span
                          className={`w-4 h-4 rounded border flex items-center justify-center shrink-0 transition-colors ${
                            checked
                              ? "bg-[#3b82f6] border-[#3b82f6]"
                              : "bg-white border-[#d1d5db]"
                          }`}
                        >
                          {checked && (
                            <svg
                              width="10"
                              height="8"
                              viewBox="0 0 10 8"
                              fill="none"
                            >
                              <path
                                d="M1 4l2.5 2.5L9 1"
                                stroke="white"
                                strokeWidth="1.5"
                                strokeLinecap="round"
                                strokeLinejoin="round"
                              />
                            </svg>
                          )}
                        </span>
                        <span className="font-medium">{type}</span>
                      </button>
                    );
                  })}
                </div>
              )}
            </div>
          </div>

          {/* Question list */}
          <SeaQaQuestionList
            key={questionListKey}
            categoryIds={selectedTopics}
            answerFilter={selectedTypes.length === 1 ? selectedTypes : []}
            searchText={debouncedSearch || undefined}
          />
        </div>

        {/* Right column */}
        <aside className="w-full md:flex-1 flex flex-col gap-4">
          <SeaQaSidebar
            topics={childTopics}
            selectedTopics={selectedTopics}
            onToggleTopic={toggleTopic}
            onClearTopics={() => setSelectedTopics([])}
            isLoading={topicsLoading}
            onLoginClick={() => setLoginModalOpen(true)}
          />
        </aside>
      </div>

      <LoginModal
        isOpen={loginModalOpen}
        onClose={() => setLoginModalOpen(false)}
        onSuccess={() => setQuestionListKey((k) => k + 1)}
      />
    </div>
  );
}
