"use client";

import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import { Button } from "@/shared/components/ui/button";
import { X } from "lucide-react";
import { getKnowledgePointOptionsAction } from "../actions-kp";

interface KpOption {
  id: string;
  name: string;
}

interface Props {
  textbookId?: string;
  chapterId?: string;
  selectedIds: string[];
  onChange: (ids: string[]) => void;
  onClose: () => void;
}

export function KnowledgePointPicker({
  textbookId,
  chapterId,
  selectedIds,
  onChange,
  onClose,
}: Props) {
  const t = useTranslations("lessonPreparation");
  const [options, setOptions] = useState<KpOption[]>([]);
  const [local, setLocal] = useState<string[]>(selectedIds);

  useEffect(() => {
    if (!textbookId) {
      return;
    }
    getKnowledgePointOptionsAction({ textbookId, chapterId }).then((res) => {
      if (res.success && res.data) setOptions(res.data.options);
    });
  }, [textbookId, chapterId]);

  function toggle(id: string) {
    setLocal((prev) =>
      prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id],
    );
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30">
      <div
        role="dialog"
        aria-modal="true"
        aria-label={t("knowledgePoint.title")}
        className="bg-surface rounded-lg shadow-xl w-96 max-h-[70vh] flex flex-col"
      >
        <div className="flex justify-between items-center p-4 border-b border-outline-variant">
          <h3 className="font-title-md">{t("knowledgePoint.title")}</h3>
          <button onClick={onClose} aria-label={t("action.close")}>
            <X className="w-4 h-4" aria-hidden="true" />
          </button>
        </div>
        <div className="flex-1 overflow-y-auto p-4">
          {options.length === 0 ? (
            <p className="text-on-surface-variant text-sm">
              {t("knowledgePoint.empty")}
            </p>
          ) : (
            <div className="space-y-1">
              {options.map((kp) => (
                <label
                  key={kp.id}
                  className="flex items-center gap-2 p-2 hover:bg-surface-container-highest rounded cursor-pointer"
                >
                  <input
                    type="checkbox"
                    checked={local.includes(kp.id)}
                    onChange={() => toggle(kp.id)}
                  />
                  <span className="text-sm">{kp.name}</span>
                </label>
              ))}
            </div>
          )}
        </div>
        <div className="p-4 border-t border-outline-variant flex justify-end gap-2">
          <Button variant="outline" size="sm" onClick={onClose}>
            {t("action.cancel")}
          </Button>
          <Button
            size="sm"
            onClick={() => {
              onChange(local);
              onClose();
            }}
          >
            {t("action.confirm")}
          </Button>
        </div>
      </div>
    </div>
  );
}
