import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { Empty, Spin, App as AntApp } from 'antd';
import { SharedAPI } from '../api';
import Markdown from '../components/Markdown';

interface Data {
  agent: { name: string; description: string };
  session: { id: string; title: string; createdAt: number; updatedAt: number };
  messages: { id: string; role: 'user' | 'assistant'; content: string; createdAt: number }[];
}

export default function SharedSessionPage() {
  const { token } = useParams();
  const [data, setData] = useState<Data | null>(null);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState<string>('');
  const { message } = AntApp.useApp();
  const loginHref = `${(import.meta.env.BASE_URL || '/').replace(/\/$/, '')}/login`;

  useEffect(() => {
    if (!token) return;
    SharedAPI.get(token)
      .then(setData)
      .catch((e) => {
        const msg = e?.response?.data?.error ?? e?.message ?? '加载失败';
        setErr(msg);
        message.error(msg);
      })
      .finally(() => setLoading(false));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [token]);

  if (loading) return <Spin style={{ display: 'block', marginTop: 80 }} />;
  if (err || !data)
    return (
      <Empty
        description={err || '会话不存在或已失效'}
        style={{ marginTop: 80 }}
      />
    );

  return (
    <div style={{ minHeight: '100vh', background: 'var(--color-bg)' }}>
      <div
        style={{
          maxWidth: 900,
          margin: '0 auto',
          padding: '32px 24px',
          background: 'var(--color-surface)',
          minHeight: '100vh',
          boxShadow: 'var(--shadow-lg)'
        }}
      >
        <div
          style={{
            paddingBottom: 16,
            borderBottom: '1px solid var(--color-border)',
            marginBottom: 24
          }}
        >
          <div style={{ fontSize: 12, color: 'var(--color-text-tertiary)', marginBottom: 4 }}>公开分享</div>
          <h1 style={{ margin: 0, fontSize: 24, color: 'var(--color-text)' }}>{data.session.title}</h1>
          <div style={{ marginTop: 8, color: 'var(--color-text-secondary)' }}>
            🤖 {data.agent.name} · {data.messages.length} 条消息
            <span style={{ marginLeft: 12, fontSize: 12, color: 'var(--color-text-tertiary)' }}>
              {new Date(data.session.updatedAt).toLocaleString('zh-CN')}
            </span>
          </div>
          {data.agent.description && (
            <div style={{ marginTop: 6, fontSize: 13, color: 'var(--color-text-secondary)' }}>
              {data.agent.description}
            </div>
          )}
        </div>

        {data.messages.map((m) => (
          <div
            key={m.id}
            style={{
              marginBottom: 18,
              display: 'flex',
              flexDirection: 'column',
              alignItems: m.role === 'user' ? 'flex-end' : 'flex-start'
            }}
          >
            <div
              style={{
                fontSize: 12,
                color: 'var(--color-text-tertiary)',
                marginBottom: 4
              }}
            >
              {m.role === 'user' ? '🧑 用户' : '🤖 助手'} ·{' '}
              {new Date(m.createdAt).toLocaleString('zh-CN')}
            </div>
            <div
              style={{
                maxWidth: '85%',
                padding: '12px 16px',
                borderRadius: 14,
                background: m.role === 'user' ? 'var(--color-brand-soft)' : 'var(--color-surface)',
                border: '1px solid var(--color-border)',
                color: 'var(--color-text)',
                boxShadow: m.role === 'assistant' ? 'var(--shadow-xs)' : 'none'
              }}
            >
              {m.role === 'assistant' ? (
                <Markdown>{m.content}</Markdown>
              ) : (
                <div style={{ whiteSpace: 'pre-wrap' }}>{m.content}</div>
              )}
            </div>
          </div>
        ))}

        <div
          style={{
            textAlign: 'center',
            color: 'var(--color-text-tertiary)',
            fontSize: 12,
            marginTop: 40
          }}
        >
          由 Agent Studio 生成 · <a href={loginHref} style={{ color: 'var(--color-brand)' }}>登录创建你自己的 agent</a>
        </div>
      </div>
    </div>
  );
}
