/* global __COMET_VERSION__:readonly */
import { App, applyDocumentTheme, applyHostStyleVariables } from '@modelcontextprotocol/ext-apps';
import { useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { Alert, Button, Card, ConfigProvider, Empty, Space, Tag, Typography, theme } from 'antd';

const app = new App({ name: 'Comet Workflows', version: __COMET_VERSION__ }, {});
const connected = app.connect();

async function callTool(name) {
  await connected;
  const result = await app.callServerTool({ name, arguments: {} });
  if (result.isError) throw new Error(result.content?.find(({ type }) => type === 'text')?.text);
  return result.structuredContent;
}

function Panel() {
  const [context, setContext] = useState({});
  const [snapshot, setSnapshot] = useState(null);
  const [loading, setLoading] = useState(true);
  const [opening, setOpening] = useState(false);
  const [url, setUrl] = useState('');
  const [error, setError] = useState('');
  const [openError, setOpenError] = useState('');
  const zh = !context.locale || context.locale.startsWith('zh');
  const label = (chinese, english) => (zh ? chinese : english);

  async function refresh() {
    setLoading(true);
    setError('');
    try {
      setSnapshot(await callTool('comet_status'));
    } catch (failure) {
      setError(failure.message);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    const applyContext = (value) => {
      if (!value) return;
      if (value.theme) applyDocumentTheme(value.theme);
      if (value.styles?.variables) applyHostStyleVariables(value.styles.variables);
      if (value.locale) document.documentElement.lang = value.locale;
      setContext((current) => ({ ...current, ...value }));
    };
    app.onhostcontextchanged = applyContext;
    void connected.then(
      () => applyContext(app.getHostContext()),
      () => {},
    );
    void refresh();
  }, []);

  async function openDashboard() {
    setOpening(true);
    setOpenError('');
    setUrl('');
    try {
      const { url: address } = await callTool('open_comet_dashboard');
      setUrl(address);
      const result = await app.openLink({ url: address });
      if (!result.isError) setUrl('');
    } catch (failure) {
      setOpenError(failure.message);
    } finally {
      setOpening(false);
    }
  }

  return (
    <ConfigProvider
      theme={{ algorithm: context.theme === 'dark' ? theme.darkAlgorithm : theme.defaultAlgorithm }}
    >
      <main className="panel">
        <Typography.Title level={3}>{snapshot?.project.name ?? 'Comet'}</Typography.Title>
        {snapshot && (
          <Typography.Text type="secondary">
            {snapshot.project.path}
            {snapshot.branch && ` · ${snapshot.branch}`}
          </Typography.Text>
        )}
        <div className="panel-toolbar">
          <Button onClick={refresh} loading={loading}>
            {label('刷新', 'Refresh')}
          </Button>
          <Button type="primary" onClick={openDashboard} loading={opening}>
            {label('打开完整 Dashboard', 'Open full Dashboard')}
          </Button>
        </div>
        <Space orientation="vertical" size="middle" style={{ width: '100%' }}>
          {error && <Alert type="error" title={error} />}
          {openError && <Alert type="warning" title={openError} />}
          {url && <Typography.Paragraph copyable>{url}</Typography.Paragraph>}
          {snapshot?.incomplete && (
            <Alert
              type="warning"
              title={label(
                '部分工作流数据未加载，请在完整 Dashboard 查看。',
                'Some workflow data could not be shown. See the full Dashboard.',
              )}
            />
          )}
          {!loading && !error && snapshot?.changes.length === 0 && (
            <Empty description={label('当前工作区没有 Change', 'No changes in this worktree')} />
          )}
          {snapshot?.changes.map(({ id, name, phase, status, workflow, artifacts }) => (
            <Card key={`${workflow}:${id}`} size="small" title={name}>
              <Space wrap size="small">
                <Tag color={workflow === 'Native' ? 'blue' : 'default'}>{workflow}</Tag>
                <Tag>{phase}</Tag>
                <Typography.Text type="secondary">
                  {status === 'archived' ? label('已归档', 'Archived') : label('进行中', 'Active')}
                </Typography.Text>
              </Space>
              {artifacts.length > 0 && (
                <ul className="panel-list">
                  {artifacts.map((artifact, index) => (
                    <li key={`${artifact}:${index}`}>{artifact}</li>
                  ))}
                </ul>
              )}
            </Card>
          ))}
        </Space>
      </main>
    </ConfigProvider>
  );
}

createRoot(document.getElementById('root')).render(<Panel />);
