"use client";

import { useState } from "react";
import Link from "next/link";
import { BookOpen, Languages, Lightbulb } from "lucide-react";
import { CommandGroup, CommandItem } from "@/components/ui/command";
import { DropdownMenuCheckboxItem, DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { notify } from "../components/ui/feedback-store";
import { describeError } from "../lib/useAsyncAction";
import { glossaryHref, matchesGlossary, useGlossary } from "./glossary-client";
import { setBnHints, setTipsEnabled, useLearningPrefs } from "./learning-prefs";

const MAX_PALETTE_TERMS = 5;

/**
 * "Glossary" group for the search palette: up to five trade terms matching the query, each opening its entry on
 * /help/glossary, listed right after the records. A query like "glossary" or "help" offers the glossary page itself.
 * The shell renders it inside its CommandList and passes its own `go(href)`.
 */
export function GlossaryCommandGroup({ query, open, onSelect }) {
  const glossary = useGlossary(open);
  const term = String(query || "").trim();
  if (!open) return null;

  const pageMatch = term.length >= 3 && matchesPage(term);
  const terms = term.length >= 2 ? glossary.entries.filter((entry) => matchesGlossary(entry, term)).slice(0, MAX_PALETTE_TERMS) : [];
  if (!pageMatch && !terms.length) return null;

  return <CommandGroup heading="Glossary">
    {terms.map((entry) => <CommandItem key={entry.key} value={`glossary:${entry.key}`} onSelect={() => onSelect(glossaryHref(entry.key))} className="items-start">
      <BookOpen className="mt-0.5" />
      <span className="grid min-w-0 flex-1">
        <span className="truncate font-medium">{entry.term}</span>
        <span className="line-clamp-1 text-xs text-muted-foreground">{entry.meaning}</span>
      </span>
    </CommandItem>)}
    {pageMatch && <CommandItem value="glossary:page" onSelect={() => onSelect(glossaryHref())}>
      <BookOpen /> Glossary of trade terms <span className="ml-2 hidden truncate text-xs text-muted-foreground sm:inline">TNA, L/C, lab dip and more in plain words</span>
    </CommandItem>}
  </CommandGroup>;
}

function matchesPage(term) {
  const needle = term.toLowerCase();
  return ["glossary", "help", "terms", "meaning", "words"].some((word) => word.startsWith(needle) || needle.startsWith(word));
}

/**
 * Account-menu items for the learning layer: tips on/off, Bangla hints on/off and a link to the glossary.
 * The shell renders them inside its DropdownMenuContent; `onNavigate` closes the mobile sidebar.
 */
export function LearningMenuItems({ onNavigate }) {
  const prefs = useLearningPrefs();
  const [saving, setSaving] = useState(null);

  const toggle = async (key, change, checked, label) => {
    setSaving(key);
    try {
      await change(checked);
    } catch (error) {
      notify.error(`${label} could not be changed`, describeError(error));
    } finally {
      setSaving(null);
    }
  };

  return <>
    {prefs.available && <>
      <DropdownMenuCheckboxItem checked={prefs.tipsEnabled} disabled={saving === "tips"} onSelect={(event) => event.preventDefault()}
        onCheckedChange={(checked) => toggle("tips", setTipsEnabled, checked, "Tips")}>
        <Lightbulb /> Show tips
      </DropdownMenuCheckboxItem>
      <DropdownMenuCheckboxItem checked={prefs.bnHints} disabled={saving === "bn"} onSelect={(event) => event.preventDefault()}
        onCheckedChange={(checked) => toggle("bn", setBnHints, checked, "Bangla hints")}>
        <Languages /> Show Bangla hints
      </DropdownMenuCheckboxItem>
    </>}
    <DropdownMenuItem asChild><Link href={glossaryHref()} onClick={onNavigate}><BookOpen /> Glossary</Link></DropdownMenuItem>
  </>;
}
