import React, { useCallback, useEffect, useRef, useState } from 'react';

import useCharacterStore from '../../Store/SideBarLeft/CharacterSlice';
import StudioInsertionPopup from './StudioInsertionPopup';

import './StudioBindingEditorPopup.css';

const CHARACTER_FIELDS = [
  { key: 'description', label: '描述', rows: 5 },
  { key: 'personality', label: '性格', rows: 3 },
  { key: 'scenario', label: '场景', rows: 3 },
  { key: 'first_mes', label: '开场白', rows: 4 },
  { key: 'mes_example', label: '对话示例', rows: 4 },
];

function entryLabel(entry) {
  if (entry.comment?.trim()) return entry.comment.trim();
  if (Array.isArray(entry.key) && entry.key.length) return entry.key.join(', ');
  return '未命名条目';
}

function StudioBindingEditorPopup({
  open,
  characterName,
  worldbookName,
  highlightEntryUid = null,
  initialTab = 'character',
  onClose,
}) {
  const updateCharacter = useCharacterStore((s) => s.updateCharacter);
  const fetchCharacters = useCharacterStore((s) => s.fetchCharacters);

  const [tab, setTab] = useState(initialTab);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [saveHint, setSaveHint] = useState('');
  const [character, setCharacter] = useState(null);
  const [characterForm, setCharacterForm] = useState(null);
  const [characterSaving, setCharacterSaving] = useState(false);
  const [entries, setEntries] = useState([]);
  const [expandedEntryUid, setExpandedEntryUid] = useState(null);
  const [entryForms, setEntryForms] = useState({});
  const [entrySavingUid, setEntrySavingUid] = useState(null);
  const highlightRef = useRef(null);

  const loadData = useCallback(async () => {
    if (!characterName && !worldbookName) return;
    setLoading(true);
    setError('');
    try {
      const tasks = [];

      if (characterName) {
        tasks.push(
          fetch(`/api/characters/${encodeURIComponent(characterName)}`)
            .then(async (res) => {
              if (!res.ok) throw new Error('加载角色卡失败');
              return res.json();
            })
            .then((data) => {
              setCharacter(data);
              setCharacterForm({
                description: data.description || '',
                personality: data.personality || '',
                scenario: data.scenario || '',
                first_mes: data.first_mes || '',
                mes_example: data.mes_example || '',
              });
            })
        );
      } else {
        setCharacter(null);
        setCharacterForm(null);
      }

      if (worldbookName) {
        tasks.push(
          fetch(
            `/api/worldbooks/${encodeURIComponent(worldbookName)}/entries?page=1&page_size=100`
          )
            .then(async (res) => {
              if (!res.ok) throw new Error('加载世界书条目失败');
              return res.json();
            })
            .then((data) => {
              const list = data.entries || [];
              setEntries(list);
              const forms = {};
              list.forEach((entry) => {
                forms[entry.uid] = {
                  comment: entry.comment || '',
                  content: entry.content || '',
                  key: Array.isArray(entry.key) ? entry.key.join(', ') : (entry.key || ''),
                };
              });
              setEntryForms(forms);
            })
        );
      } else {
        setEntries([]);
        setEntryForms({});
      }

      await Promise.all(tasks);
    } catch (e) {
      setError(e.message || '加载绑定资源失败');
    } finally {
      setLoading(false);
    }
  }, [characterName, worldbookName]);

  useEffect(() => {
    if (open) {
      setTab(initialTab);
      setSaveHint('');
      setExpandedEntryUid(highlightEntryUid || null);
      loadData();
    }
  }, [open, initialTab, highlightEntryUid, loadData]);

  useEffect(() => {
    if (!open || !highlightEntryUid) return undefined;
    const timer = setTimeout(() => {
      highlightRef.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }, 200);
    return () => clearTimeout(timer);
  }, [open, highlightEntryUid, entries.length, loading]);

  const handleCharacterFieldChange = (key, value) => {
    setCharacterForm((prev) => ({ ...prev, [key]: value }));
    setSaveHint('');
  };

  const handleSaveCharacter = async () => {
    if (!characterName || !character || !characterForm) return;
    setCharacterSaving(true);
    setError('');
    try {
      await updateCharacter(characterName, {
        ...character,
        ...characterForm,
      });
      await fetchCharacters();
      setSaveHint('角色卡已保存');
      setTimeout(() => setSaveHint(''), 2500);
    } catch (e) {
      setError(e.message || '保存角色卡失败');
    } finally {
      setCharacterSaving(false);
    }
  };

  const handleEntryFieldChange = (uid, key, value) => {
    setEntryForms((prev) => ({
      ...prev,
      [uid]: { ...prev[uid], [key]: value },
    }));
    setSaveHint('');
  };

  const handleSaveEntry = async (uid) => {
    if (!worldbookName) return;
    const form = entryForms[uid];
    if (!form) return;
    setEntrySavingUid(uid);
    setError('');
    try {
      const keyList = form.key
        .split(/[,，]/)
        .map((s) => s.trim())
        .filter(Boolean);
      const res = await fetch(
        `/api/worldbooks/${encodeURIComponent(worldbookName)}/entries/${encodeURIComponent(uid)}`,
        {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            comment: form.comment,
            content: form.content,
            key: keyList,
          }),
        }
      );
      if (!res.ok) {
        const detail = await res.text();
        throw new Error(detail || '保存条目失败');
      }
      setSaveHint('世界书条目已保存');
      setTimeout(() => setSaveHint(''), 2500);
      await loadData();
      setExpandedEntryUid(uid);
    } catch (e) {
      setError(e.message || '保存条目失败');
    } finally {
      setEntrySavingUid(null);
    }
  };

  const title = characterName ? `绑定编辑 · ${characterName}` : '绑定编辑';

  return (
    <StudioInsertionPopup
      open={open}
      title={title}
      defaultExpanded
      onClose={onClose}
    >
      {() => (
        <div className="studio-binding-editor">
          <div className="studio-binding-editor__tabs" role="tablist">
            <button
              type="button"
              role="tab"
              aria-selected={tab === 'character'}
              className={`studio-binding-editor__tab${tab === 'character' ? ' is-active' : ''}`}
              onClick={() => setTab('character')}
            >
              角色卡
            </button>
            <button
              type="button"
              role="tab"
              aria-selected={tab === 'worldbook'}
              className={`studio-binding-editor__tab${tab === 'worldbook' ? ' is-active' : ''}`}
              onClick={() => setTab('worldbook')}
            >
              世界书
            </button>
          </div>

          {saveHint ? (
            <p className="studio-binding-editor__hint studio-binding-editor__hint--success">
              {saveHint}
            </p>
          ) : null}

          {loading ? (
            <p className="studio-binding-editor__status">加载中…</p>
          ) : error ? (
            <p className="studio-binding-editor__status studio-binding-editor__status--error">
              {error}
            </p>
          ) : tab === 'character' ? (
            <div className="studio-binding-editor__panel">
              {!character || !characterForm ? (
                <p className="studio-binding-editor__empty">暂无绑定角色卡</p>
              ) : (
                <>
                  <div className="studio-binding-editor__hero">
                    {character.avatar ? (
                      <img
                        src={character.avatar}
                        alt=""
                        className="studio-binding-editor__avatar"
                      />
                    ) : (
                      <div className="studio-binding-editor__avatar studio-binding-editor__avatar--placeholder">
                        🎭
                      </div>
                    )}
                    <div>
                      <h3 className="studio-binding-editor__name">{character.name}</h3>
                      {worldbookName ? (
                        <p className="studio-binding-editor__meta">世界书：{worldbookName}</p>
                      ) : null}
                    </div>
                  </div>
                  {CHARACTER_FIELDS.map(({ key, label, rows }) => (
                    <label key={key} className="studio-binding-editor__field">
                      <span className="studio-binding-editor__field-label">{label}</span>
                      <textarea
                        className="studio-binding-editor__textarea"
                        rows={rows}
                        value={characterForm[key] || ''}
                        onChange={(e) => handleCharacterFieldChange(key, e.target.value)}
                      />
                    </label>
                  ))}
                  <button
                    type="button"
                    className="studio-binding-editor__save-btn"
                    onClick={handleSaveCharacter}
                    disabled={characterSaving}
                  >
                    {characterSaving ? '保存中…' : '保存角色卡'}
                  </button>
                </>
              )}
            </div>
          ) : (
            <div className="studio-binding-editor__panel">
              {!worldbookName ? (
                <p className="studio-binding-editor__empty">暂无绑定世界书</p>
              ) : entries.length === 0 ? (
                <p className="studio-binding-editor__empty">
                  世界书「{worldbookName}」暂无条目
                </p>
              ) : (
                <ul className="studio-binding-editor__entries">
                  {entries.map((entry) => {
                    const expanded = expandedEntryUid === entry.uid;
                    const highlighted = highlightEntryUid === entry.uid;
                    const form = entryForms[entry.uid] || {
                      comment: entry.comment || '',
                      content: entry.content || '',
                      key: Array.isArray(entry.key) ? entry.key.join(', ') : '',
                    };
                    return (
                      <li
                        key={entry.uid}
                        ref={highlighted ? highlightRef : null}
                        className={`studio-binding-editor__entry${highlighted ? ' is-highlighted' : ''}`}
                      >
                        <button
                          type="button"
                          className="studio-binding-editor__entry-head"
                          onClick={() =>
                            setExpandedEntryUid(expanded ? null : entry.uid)
                          }
                        >
                          <span className="studio-binding-editor__entry-title">
                            {entryLabel(entry)}
                          </span>
                          <span className="studio-binding-editor__entry-meta">
                            {entry.activationType || '—'} · order {entry.order ?? 0}
                          </span>
                        </button>
                        {expanded ? (
                          <div className="studio-binding-editor__entry-body">
                            <label className="studio-binding-editor__field">
                              <span className="studio-binding-editor__field-label">备注</span>
                              <input
                                type="text"
                                className="studio-binding-editor__input"
                                value={form.comment}
                                onChange={(e) =>
                                  handleEntryFieldChange(entry.uid, 'comment', e.target.value)
                                }
                              />
                            </label>
                            <label className="studio-binding-editor__field">
                              <span className="studio-binding-editor__field-label">关键词</span>
                              <input
                                type="text"
                                className="studio-binding-editor__input"
                                value={form.key}
                                onChange={(e) =>
                                  handleEntryFieldChange(entry.uid, 'key', e.target.value)
                                }
                                placeholder="逗号分隔"
                              />
                            </label>
                            <label className="studio-binding-editor__field">
                              <span className="studio-binding-editor__field-label">内容</span>
                              <textarea
                                className="studio-binding-editor__textarea"
                                rows={6}
                                value={form.content}
                                onChange={(e) =>
                                  handleEntryFieldChange(entry.uid, 'content', e.target.value)
                                }
                              />
                            </label>
                            <button
                              type="button"
                              className="studio-binding-editor__save-btn"
                              onClick={() => handleSaveEntry(entry.uid)}
                              disabled={entrySavingUid === entry.uid}
                            >
                              {entrySavingUid === entry.uid ? '保存中…' : '保存条目'}
                            </button>
                          </div>
                        ) : null}
                      </li>
                    );
                  })}
                </ul>
              )}
            </div>
          )}
        </div>
      )}
    </StudioInsertionPopup>
  );
}

export default StudioBindingEditorPopup;
