import { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { analyzeChatSave, saveChatMessageAsPage } from '../api/client';
import type { ChatSaveAnalysis, MindSpaceSaveCategory } from '../types';
import { PageSavePreviewPanel } from './PageSavePreviewPanel';

const CATEGORY_OPTIONS: Array<{
  code: MindSpaceSaveCategory;
  label: string;
  hint: string;
}> = [
  {
    code: 'draft',
    label: '页面草稿',
    hint: '继续编辑后再决定是否发布',
  },
  {
    code: 'oa',
    label: 'OA 工作区',
    hint: '与上传文档并列的资料卡片',
  },
  {
    code: 'private',
    label: '私人区',
    hint: '默认不可公开，发布前需检查',
  },
  {
    code: 'public',
    label: '公开区',
    hint: '可公开候选，仍需走发布流程',
  },
];

const CATEGORY_LABELS: Record<MindSpaceSaveCategory, string> = {
  draft: '页面草稿',
  oa: 'OA 工作区',
  private: '私人区',
  public: '公开区',
};

export type PageSaveDialogProps = {
  sessionId: string;
  messageId: string;
  compact?: boolean;
  onClose: () => void;
  onSaved: (result: {
    kind: 'page' | 'asset';
    categoryCode: MindSpaceSaveCategory;
    pageId?: string;
  }) => void;
};

export function PageSaveDialog({
  sessionId,
  messageId,
  compact = false,
  onClose,
  onSaved,
}: PageSaveDialogProps) {
  const [analysis, setAnalysis] = useState<ChatSaveAnalysis | null>(null);
  const [analysisLoading, setAnalysisLoading] = useState(true);
  const [analysisError, setAnalysisError] = useState<string | null>(null);
  const [selectedLinkIndex, setSelectedLinkIndex] = useState(0);
  const [title, setTitle] = useState('');
  const [summary, setSummary] = useState('');
  const [templateId, setTemplateId] = useState('editorial');
  const [categoryCode, setCategoryCode] = useState<MindSpaceSaveCategory>('draft');
  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);
  const [saveNotice, setSaveNotice] = useState<string | null>(null);
  const [privateAcknowledged, setPrivateAcknowledged] = useState(false);
  const [thumbnailVersion, setThumbnailVersion] = useState(0);
  const [previewScrollLock, setPreviewScrollLock] = useState(false);
  const titleRef = useRef('');
  const summaryRef = useRef('');

  const loadAnalysis = async (
    linkIndex: number,
    options: { updateForm?: boolean; previewTitle?: string; previewSummary?: string } = {},
  ) => {
    const updateForm = options.updateForm ?? true;
    if (updateForm) {
      setAnalysisLoading(true);
      setAnalysisError(null);
    }
    try {
      const result = await analyzeChatSave({
        sessionId,
        messageId,
        selectedLinkIndex: linkIndex,
        previewTitle: options.previewTitle,
        previewSummary: options.previewSummary,
      });
      setAnalysis(result);
      if (updateForm) {
        setTitle(result.suggestedTitle);
        setSummary(result.suggestedSummary);
        titleRef.current = result.suggestedTitle;
        summaryRef.current = result.suggestedSummary;
        setSelectedLinkIndex(result.selectedLinkIndex >= 0 ? result.selectedLinkIndex : linkIndex);
      }
      if (result.thumbnailUrl) {
        setThumbnailVersion(Date.now());
      }
    } catch (err) {
      if (updateForm) {
        setAnalysisError(err instanceof Error ? err.message : '无法分析消息内容');
      }
    } finally {
      if (updateForm) {
        setAnalysisLoading(false);
      }
    }
  };

  useEffect(() => {
    void loadAnalysis(0);
  }, [sessionId, messageId]);

  useEffect(() => {
    titleRef.current = title;
  }, [title]);

  useEffect(() => {
    summaryRef.current = summary;
  }, [summary]);

  useEffect(() => {
    if (!analysis || analysis.contentMode !== 'static_html') return undefined;
    const timer = window.setTimeout(() => {
      setThumbnailVersion(Date.now());
    }, 500);
    return () => window.clearTimeout(timer);
  }, [title, summary, analysis?.contentMode]);

  useEffect(() => {
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape' && !saving) onClose();
    };
    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, [onClose, saving]);

  useEffect(() => {
    setPrivateAcknowledged(false);
  }, [categoryCode, analysis?.privacyScan?.findings.length]);

  const isStaticHtml = analysis?.contentMode === 'static_html';
  const privacyFindings = analysis?.privacyScan.findings ?? [];
  const privateBlocked = categoryCode === 'private' && analysis?.privacyScan.allowed === false;
  const privateNeedsAck =
    categoryCode === 'private' && privacyFindings.length > 0 && analysis?.privacyScan.allowed;

  const save = async () => {
    if (!title.trim()) return;
    setSaving(true);
    setSaveError(null);
    try {
      const result = await saveChatMessageAsPage({
        sessionId,
        messageId,
        title: title.trim(),
        summary: summary.trim(),
        templateId: isStaticHtml ? 'static-html' : templateId,
        categoryCode,
        selectedLinkIndex,
        acknowledgedFindingIds:
          categoryCode === 'private' && privateNeedsAck && privateAcknowledged
            ? privacyFindings.map((finding) => finding.id)
            : undefined,
      });
      if (result.kind === 'page') {
        setSaveNotice(`已保存到${CATEGORY_LABELS[categoryCode]}`);
        onSaved({ kind: 'page', categoryCode: 'draft', pageId: result.page.id });
        return;
      }
      setSaveNotice(`已保存到${CATEGORY_LABELS[result.categoryCode]}`);
      onSaved({ kind: 'asset', categoryCode: result.categoryCode });
    } catch (err) {
      setSaveError(err instanceof Error ? err.message : '保存失败');
    } finally {
      setSaving(false);
    }
  };

  return createPortal(
    <div
      className={`page-save-backdrop${previewScrollLock ? ' is-preview-scroll-locked' : ''}`}
      role="presentation"
      onClick={saving ? undefined : onClose}
    >
      <section
        className={`page-save-panel${compact ? ' page-save-panel-compact' : ' page-save-panel-wide'}`}
        role="dialog"
        aria-modal="true"
        onClick={(event) => event.stopPropagation()}
      >
        <div className={`page-save-scroll${previewScrollLock ? ' is-preview-scroll-locked' : ''}`}>
          <p className="mindspace-eyebrow">SAVE TO MINDSPACE</p>
          <h2>{isStaticHtml ? '保存生成的页面' : '保存 AI 回答为文章'}</h2>

          {analysisLoading && <div className="page-save-state">正在识别页面内容…</div>}
          {analysisError && <div className="page-save-error">{analysisError}</div>}

          {!analysisLoading && analysis && (
            <div className="page-save-layout">
              <div className="page-save-form">
                {isStaticHtml && analysis && (
                  <div className="page-save-preview-block">
                    <PageSavePreviewPanel
                      sessionId={sessionId}
                      messageId={messageId}
                      selectedLinkIndex={selectedLinkIndex}
                      title={title}
                      summary={summary}
                      analysis={analysis}
                      thumbnailVersion={thumbnailVersion}
                      onPreviewHoverChange={setPreviewScrollLock}
                    />
                    {analysis.links.length > 1 && (
                      <label>
                        选择链接页面
                        <select
                          value={selectedLinkIndex}
                          onChange={(event) => {
                            const nextIndex = Number(event.target.value);
                            setSelectedLinkIndex(nextIndex);
                            void loadAnalysis(nextIndex);
                          }}
                        >
                          {analysis.links.map((link, index) => (
                            <option value={index} key={link.publicUrl}>
                              {link.filename}
                            </option>
                          ))}
                        </select>
                      </label>
                    )}
                    <p className="page-save-source">
                      来源文件：{analysis.filename ?? analysis.relativePath}
                      {analysis.previewUrl ? ` · 公网链接仅作参考` : ''}
                    </p>
                  </div>
                )}

                <label>
                  页面标题
                  <input
                    value={title}
                    maxLength={255}
                    onChange={(event) => setTitle(event.target.value)}
                  />
                </label>
                <label>
                  摘要
                  <textarea
                    value={summary}
                    maxLength={1000}
                    rows={3}
                    onChange={(event) => setSummary(event.target.value)}
                  />
                </label>

                {!isStaticHtml && (
                  <label>
                    页面模板
                    <select value={templateId} onChange={(event) => setTemplateId(event.target.value)}>
                      <option value="editorial">编辑长文</option>
                      <option value="report">分析报告</option>
                      <option value="knowledge-card">知识卡片</option>
                      <option value="profile">个人介绍</option>
                    </select>
                  </label>
                )}

                <fieldset className="page-save-targets">
                  <legend>保存到</legend>
                  {CATEGORY_OPTIONS.map((option) => {
                    const disabledPrivate =
                      option.code === 'private' && analysis.privacyScan.allowed === false;
                    return (
                      <label
                        className={`page-save-target${disabledPrivate ? ' is-disabled' : ''}`}
                        key={option.code}
                      >
                        <input
                          type="radio"
                          name="save-target"
                          value={option.code}
                          checked={categoryCode === option.code}
                          disabled={disabledPrivate}
                          onChange={() => setCategoryCode(option.code)}
                        />
                        <span>
                          <strong>{option.label}</strong>
                          <small>
                            {disabledPrivate
                              ? '内容含阻断级敏感信息，不能保存到私人区'
                              : option.hint}
                          </small>
                        </span>
                      </label>
                    );
                  })}
                </fieldset>

                {categoryCode === 'private' && (
                  <div className="page-save-private-panel">
                    <strong>私人区安全说明</strong>
                    <p>私人区默认不可公开。若后续要发布，系统会要求脱敏副本和二次确认。</p>
                    {privacyFindings.length > 0 && (
                      <ul className="page-save-private-findings">
                        {privacyFindings.map((finding) => (
                          <li key={finding.id}>
                            {finding.blocking ? '阻断' : '提醒'} · {finding.label ?? finding.type}（
                            {finding.occurrenceCount} 处）{finding.sampleMasked}
                          </li>
                        ))}
                      </ul>
                    )}
                    {privateNeedsAck && (
                      <label className="page-save-private-ack">
                        <input
                          type="checkbox"
                          checked={privateAcknowledged}
                          onChange={(event) => setPrivateAcknowledged(event.target.checked)}
                        />
                        <span>我已知悉上述敏感信息，确认保存到私人区</span>
                      </label>
                    )}
                  </div>
                )}
              </div>

              {!compact && (
                <aside className="page-save-aside">
                  <p className="mindspace-eyebrow">WHERE IT GOES</p>
                  <h3>保存后落点</h3>
                  <div className="page-save-destination-preview">
                    <span>{CATEGORY_LABELS[categoryCode]}</span>
                    <div className="page-save-destination-grid">
                      <div className="page-save-destination-card is-muted">📄 资料</div>
                      <div
                        className={`page-save-destination-card${categoryCode === 'draft' || isStaticHtml ? ' is-active' : ''}`}
                      >
                        {isStaticHtml ? '🌐 页面' : '📝 文章'}
                      </div>
                      <div className="page-save-destination-card is-muted">📊 表格</div>
                    </div>
                    <p>
                      {categoryCode === 'draft'
                        ? '进入草稿编辑工作台，可预览真实页面并决定是否发布。'
                        : '以资料卡片形式保存在该分区，与上传文件并列展示。'}
                    </p>
                  </div>
                </aside>
              )}
            </div>
          )}

          {saveNotice && <div className="page-save-notice">{saveNotice}</div>}
          {saveError && <div className="page-save-error">{saveError}</div>}
        </div>

        <div className="page-save-actions">
          <button type="button" onClick={onClose} disabled={saving}>
            取消
          </button>
          <button
            type="button"
            className="page-save-primary"
            onClick={() => void save()}
            disabled={
              saving ||
              analysisLoading ||
              !title.trim() ||
              Boolean(analysisError) ||
              privateBlocked ||
              (privateNeedsAck && !privateAcknowledged)
            }
          >
            {saving ? '正在保存…' : categoryCode === 'draft' ? '保存并进入编辑' : '保存到空间'}
          </button>
        </div>
      </section>
    </div>,
    document.body,
  );
}
