import { useState } from "react";
import type { FC } from "react";
import { Modal, Toast } from "@douyinfe/semi-ui";
import { request } from "../../api/client";
import styles from "./CreateKnowledgeModal.module.css";

const KNOWLEDGE_TYPES = ["strategy", "tool", "user_profile", "usecase", "definition", "plan"];

interface CreateKnowledgeModalProps {
  visible: boolean;
  contextText: string;
  traceId?: string;
  goalId?: string;
  messageId?: string;
  sequence?: number;
  onClose: () => void;
  onCreated?: (knowledgeId: string) => void;
}

export const CreateKnowledgeModal: FC<CreateKnowledgeModalProps> = ({
  visible,
  contextText,
  traceId,
  goalId,
  messageId,
  sequence,
  onClose,
  onCreated,
}) => {
  const [comment, setComment] = useState("");
  const [selectedTypes, setSelectedTypes] = useState<string[]>(["strategy"]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isContextExpanded, setIsContextExpanded] = useState(false);

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

  const handleClose = () => {
    setComment("");
    setSelectedTypes(["strategy"]);
    setIsContextExpanded(false);
    onClose();
  };

  const handleSubmit = async () => {
    if (!comment.trim()) {
      Toast.warning("请输入评论内容");
      return;
    }
    if (selectedTypes.length === 0) {
      Toast.warning("请至少选择一个知识类型");
      return;
    }

    setIsSubmitting(true);
    try {
      const result = await request<{ knowledge_id: string }>("/api/traces/extract_comment", {
        method: "POST",
        data: {
          comment: comment.trim(),
          context: contextText,
          types: selectedTypes,
          source: {
            name: "user_feedback",
            category: "exp",
            trace_id: traceId,
            goal_id: goalId,
            message_id: messageId,
            sequence: sequence ?? null,
            submitted_by: "user",
          },
          scopes: ["org:cybertogether"],
          owner: "user",
        },
      });
      Toast.success("知识已创建，正在处理去重...");
      onCreated?.(result.knowledge_id);
      handleClose();
    } catch {
      Toast.error("创建失败，请重试");
    } finally {
      setIsSubmitting(false);
    }
  };

  const footer = (
    <div className={styles.footer}>
      <button className={styles.cancelBtn} onClick={handleClose} disabled={isSubmitting}>
        取消
      </button>
      <button className={styles.submitBtn} onClick={handleSubmit} disabled={isSubmitting || !comment.trim()}>
        {isSubmitting ? "创建中..." : "创建知识"}
      </button>
    </div>
  );

  return (
    <Modal
      title="创建知识"
      visible={visible}
      onCancel={handleClose}
      footer={footer}
      width={600}
      maskClosable={false}
    >
      <div className={styles.body}>
        {contextText && (
          <div className={styles.contextBlock}>
            <span className={styles.expandToggle} onClick={() => setIsContextExpanded((v) => !v)}>
              {isContextExpanded ? "▲ 收起上下文" : "▼ 展开上下文"}
            </span>
            {isContextExpanded && (
              <pre className={styles.contextContent}>{contextText}</pre>
            )}
          </div>
        )}

        <div className={styles.field}>
          <label className={styles.label}>知识类型</label>
          <div className={styles.typeList}>
            {KNOWLEDGE_TYPES.map((type) => (
              <label key={type} className={styles.typeItem}>
                <input
                  type="checkbox"
                  checked={selectedTypes.includes(type)}
                  onChange={() => toggleType(type)}
                />
                <span>{type}</span>
              </label>
            ))}
          </div>
        </div>

        <div className={styles.field}>
          <label className={styles.label}>
            评论 <span className={styles.required}>*</span>
          </label>
          <textarea
            className={styles.textarea}
            value={comment}
            onChange={(e) => setComment(e.target.value)}
            placeholder="描述你的观察、经验或注意事项，LLM 将自动提取结构化知识..."
            rows={5}
            disabled={isSubmitting}
          />
        </div>
      </div>
    </Modal>
  );
};
