"use client";

import { useEffect, useMemo, useRef, useState } from "react";

export interface SyllabusTopic {
  id: number;
  title: string;
  order: number;
}

export interface SyllabusChapter {
  id: number;
  title: string;
  order: number;
  topics: SyllabusTopic[];
}

export interface SyllabusPayload {
  book: { id: number; title: string } | null;
  chapters: SyllabusChapter[];
}

type SyllabusOption = {
  key: string;
  kind: "topic" | "chapter";
  id: number;
  label: string;
};

function normalizeSearch(value: string) {
  return value.replace(/ي/g, "ی").replace(/ك/g, "ک").replace(/\s+/g, " ").trim().toLowerCase();
}

function syllabusOptions(syllabus: SyllabusPayload): SyllabusOption[] {
  const options: SyllabusOption[] = [];
  for (const chapter of syllabus.chapters) {
    if (chapter.topics.length === 0) {
      options.push({
        key: `c:${chapter.id}`,
        kind: "chapter",
        id: chapter.id,
        label: chapter.title,
      });
      continue;
    }
    for (const topic of chapter.topics) {
      options.push({
        key: `t:${topic.id}`,
        kind: "topic",
        id: topic.id,
        label: `${chapter.title} — ${topic.title}`,
      });
    }
  }
  return options;
}

export function SyllabusSearchSelect({
  syllabus,
  topicIds,
  chapterIds,
  onChange,
  disabled = false,
  emptyLabel = "انتخاب سرفصل",
}: {
  syllabus: SyllabusPayload;
  topicIds: number[];
  chapterIds: number[];
  onChange: (next: { topicIds: number[]; chapterIds: number[] }) => void;
  disabled?: boolean;
  emptyLabel?: string;
}) {
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState("");
  const rootRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const options = useMemo(() => syllabusOptions(syllabus), [syllabus]);
  const selectedKeys = useMemo(() => {
    const keys = new Set<string>();
    for (const id of topicIds) keys.add(`t:${id}`);
    for (const id of chapterIds) keys.add(`c:${id}`);
    return keys;
  }, [topicIds, chapterIds]);
  const selected = options.filter((option) => selectedKeys.has(option.key));
  const q = normalizeSearch(query);
  const filtered = useMemo(() => {
    if (!q) return options;
    return options.filter((option) => normalizeSearch(option.label).includes(q));
  }, [options, q]);

  useEffect(() => {
    if (!open || disabled) return;
    const onDoc = (e: MouseEvent) => {
      if (!rootRef.current?.contains(e.target as Node)) {
        setOpen(false);
        setQuery("");
      }
    };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [disabled, open]);

  useEffect(() => {
    if (open) inputRef.current?.focus();
  }, [open]);

  const toggleOption = (option: SyllabusOption) => {
    if (option.kind === "topic") {
      const next = topicIds.includes(option.id)
        ? topicIds.filter((id) => id !== option.id)
        : [...topicIds, option.id];
      onChange({ topicIds: next, chapterIds });
      return;
    }
    const next = chapterIds.includes(option.id)
      ? chapterIds.filter((id) => id !== option.id)
      : [...chapterIds, option.id];
    onChange({ topicIds, chapterIds: next });
  };

  const summary =
    selected.length === 0
      ? emptyLabel
      : selected.length === 1
        ? selected[0].label
        : `${selected[0].label} و ${selected.length - 1} مورد دیگر`;

  return (
    <div className="space-y-2">
      {syllabus.book ? (
        <p className="text-xs font-semibold text-slate-500">کتاب: {syllabus.book.title}</p>
      ) : null}
      <div ref={rootRef}>
        <button
          type="button"
          disabled={disabled}
          className="flex w-full items-center justify-between rounded-xl border border-[var(--border)] bg-white px-3.5 py-2.5 text-right text-sm outline-none transition focus:border-primary focus:ring-2 focus:ring-primary disabled:opacity-70"
          onClick={() => !disabled && setOpen((v) => !v)}
        >
          <span className={selected.length ? "text-foreground" : "text-[var(--muted)]"}>{summary}</span>
          <svg
            viewBox="0 0 24 24"
            className={`h-4 w-4 shrink-0 text-slate-400 transition-transform ${open ? "rotate-180" : ""}`}
            fill="none"
            stroke="currentColor"
            strokeWidth="1.5"
            aria-hidden
          >
            <path d="M6 9l6 6 6-6" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </button>
        {open && !disabled ? (
          <div className="mt-1 overflow-hidden rounded-xl border border-[var(--border)] bg-white shadow-lg">
            <div className="border-b border-[var(--border)] p-2">
              <input
                ref={inputRef}
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder="جستجوی سرفصل…"
                className="w-full rounded-lg border border-[var(--border)] px-3 py-1.5 text-sm outline-none focus:border-primary"
              />
            </div>
            <ul className="max-h-56 overflow-y-auto py-1 text-sm">
              {filtered.length === 0 ? (
                <li className="px-3 py-2 text-[var(--muted)]">موردی یافت نشد.</li>
              ) : (
                filtered.map((option) => {
                  const checked = selectedKeys.has(option.key);
                  return (
                    <li key={option.key}>
                      <button
                        type="button"
                        className={`flex w-full items-start gap-2 px-3 py-2 text-right hover:bg-slate-50 ${
                          checked ? "bg-slate-50 font-medium text-primary" : ""
                        }`}
                        onClick={() => toggleOption(option)}
                      >
                        <span
                          className={`mt-0.5 inline-block h-3.5 w-3.5 shrink-0 rounded-sm border ${
                            checked ? "border-teal-600 bg-teal-600" : "border-slate-300"
                          }`}
                        />
                        <span>{option.label}</span>
                      </button>
                    </li>
                  );
                })
              )}
            </ul>
          </div>
        ) : null}
      </div>
      {selected.length > 0 ? (
        <div className="flex flex-wrap gap-1.5">
          {selected.map((option) => (
            <span
              key={option.key}
              className="inline-flex items-center gap-1 rounded-full bg-slate-100 px-2.5 py-1 text-xs text-slate-700"
            >
              {option.label}
              {!disabled ? (
                <button
                  type="button"
                  className="text-slate-400 hover:text-slate-700"
                  onClick={() => toggleOption(option)}
                  aria-label={`حذف ${option.label}`}
                >
                  ×
                </button>
              ) : null}
            </span>
          ))}
        </div>
      ) : null}
    </div>
  );
}
