import { useEffect, useState } from 'react';
import { ApartmentOutlined, ClockCircleOutlined, PlayCircleOutlined, PlusOutlined, ThunderboltOutlined } from '@ant-design/icons';
import { Button, Empty, Tag, App as AntApp, Popconfirm } from 'antd';
import type { Workflow } from '../../api';
import { WorkflowAPI } from '../../api';
import { SAMPLE_GRAPH } from './constants';
import WorkflowEditorDrawer from './components/WorkflowEditorDrawer';
import RunsDrawer from './components/RunsDrawer';

export default function WorkflowsPage() {
  const { message } = AntApp.useApp();
  const [list, setList] = useState<Workflow[]>([]);
  const [loading, setLoading] = useState(false);
  const [editorOpen, setEditorOpen] = useState(false);
  const [editing, setEditing] = useState<Workflow | null>(null);
  const [runsOpen, setRunsOpen] = useState(false);
  const [runsFor, setRunsFor] = useState<Workflow | null>(null);

  const load = async () => {
    setLoading(true);
    try {
      const data = await WorkflowAPI.list();
      setList(data);
    } catch (e: any) {
      message.error('加载失败：' + (e?.message ?? e));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    load();
  }, []);

  const onCreate = () => {
    setEditing({
      id: '',
      name: '新工作流',
      description: '',
      graph: SAMPLE_GRAPH,
      scheduleCron: '',
      scheduleEnabled: false,
      enabled: true,
      lastRunAt: 0,
      runCount: 0,
      createdAt: 0,
      updatedAt: 0
    });
    setEditorOpen(true);
  };

  const onEdit = (w: Workflow) => {
    setEditing(w);
    setEditorOpen(true);
  };

  const onDelete = async (w: Workflow) => {
    await WorkflowAPI.remove(w.id);
    message.success('已删除');
    load();
  };

  return (
    <div className="feature-cover-container">
      <div className="page-container" style={{ maxWidth: 1400 }}>
        <div
          style={{
            borderRadius: 24,
            padding: '30px 30px 26px',
            background:
              'linear-gradient(135deg, rgba(255,255,255,0.98) 0%, rgba(236,253,245,0.92) 42%, rgba(239,246,255,0.96) 100%)',
            border: '1px solid rgba(8, 145, 178, 0.12)',
            boxShadow: '0 20px 48px rgba(15, 23, 42, 0.06)',
            marginBottom: 24
          }}
        >
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 20, flexWrap: 'wrap', marginBottom: 20 }}>
            <div style={{ maxWidth: 680 }}>
              <div
                style={{
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: 8,
                  padding: '6px 12px',
                  borderRadius: 999,
                  background: 'rgba(255,255,255,0.78)',
                  border: '1px solid rgba(8, 145, 178, 0.10)',
                  color: 'var(--color-text-secondary)',
                  fontSize: 12,
                  fontWeight: 600,
                  marginBottom: 16
                }}
              >
                <ApartmentOutlined style={{ color: 'var(--color-brand)' }} />
                自动化编排中心
              </div>
              <h1 className="page-title" style={{ marginBottom: 10 }}>
                工作流编排
              </h1>
              <div className="page-subtitle" style={{ marginTop: 0, fontSize: 15, lineHeight: 1.75 }}>
                让多个 Agent、技能、HTTP 请求与数据转换连成一条可运行的自动化链路。这里更像一个流程画廊，而不是传统表格后台。
              </div>
            </div>
            <Button type="primary" size="large" icon={<PlusOutlined />} onClick={onCreate} style={{ borderRadius: 14, height: 46, padding: '0 18px', fontWeight: 600 }}>
              新建工作流
            </Button>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0, 1fr))', gap: 14 }}>
            {[
              { label: '工作流数量', value: list.length, tone: 'rgba(8, 145, 178, 0.10)', color: 'var(--color-brand)' },
              { label: '启用中', value: list.filter((item) => item.enabled).length, tone: 'rgba(34, 197, 94, 0.10)', color: 'var(--color-success)' },
              {
                label: '定时运行',
                value: list.filter((item) => item.scheduleEnabled && item.scheduleCron).length,
                tone: 'rgba(249, 115, 22, 0.10)',
                color: 'var(--color-warning)'
              }
            ].map((item) => (
              <div
                key={item.label}
                style={{ borderRadius: 18, padding: '16px 18px', background: 'rgba(255,255,255,0.72)', border: '1px solid rgba(255,255,255,0.7)' }}
              >
                <div style={{ fontSize: 12.5, color: 'var(--color-text-secondary)', marginBottom: 10 }}>{item.label}</div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                  <span style={{ fontSize: 30, fontWeight: 700, color: 'var(--color-text)' }}>{item.value}</span>
                  <span style={{ borderRadius: 999, padding: '4px 8px', background: item.tone, color: item.color, fontSize: 12, fontWeight: 600 }}>
                    实时状态
                  </span>
                </div>
              </div>
            ))}
          </div>
        </div>

        {loading ? null : list.length === 0 ? (
          <div style={{ borderRadius: 22, background: 'var(--color-surface)', border: '1px solid var(--color-border)', padding: '54px 24px' }}>
            <Empty description="还没有工作流，点击上方开始搭建第一条自动化流程" />
          </div>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: 18 }}>
            {list.map((r) => (
              <div
                key={r.id}
                style={{
                  borderRadius: 20,
                  border: '1px solid var(--color-border)',
                  background: 'linear-gradient(180deg, rgba(255,255,255,0.98) 0%, rgba(252,252,253,1) 100%)',
                  boxShadow: '0 12px 28px rgba(15, 23, 42, 0.045)',
                  padding: 20,
                  minHeight: 308,
                  display: 'flex',
                  flexDirection: 'column'
                }}
              >
                <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, marginBottom: 16 }}>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 19, fontWeight: 700, color: 'var(--color-text)', marginBottom: 6 }}>{r.name}</div>
                    <div style={{ fontSize: 13, color: 'var(--color-text-secondary)', lineHeight: 1.7 }}>
                      {r.description || '还没有补充描述，可以说明这个流程负责什么自动化任务。'}
                    </div>
                  </div>
                  <Tag
                    bordered={false}
                    style={{
                      margin: 0,
                      borderRadius: 999,
                      background: r.enabled ? 'var(--color-success-soft)' : 'var(--color-surface-2)',
                      color: r.enabled ? 'var(--color-success)' : 'var(--color-text-secondary)',
                      height: 28,
                      lineHeight: '28px'
                    }}
                  >
                    {r.enabled ? '已启用' : '已停用'}
                  </Tag>
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0, 1fr))', gap: 12, marginBottom: 16 }}>
                  <div
                    style={{
                      borderRadius: 16,
                      padding: '14px 14px 12px',
                      background: 'rgba(8, 145, 178, 0.06)',
                      border: '1px solid rgba(8, 145, 178, 0.10)'
                    }}
                  >
                    <div style={{ fontSize: 12, color: 'var(--color-text-secondary)', marginBottom: 8 }}>节点数</div>
                    <div style={{ fontSize: 24, fontWeight: 700, color: 'var(--color-text)' }}>{r.graph?.nodes?.length ?? 0}</div>
                  </div>
                  <div
                    style={{
                      borderRadius: 16,
                      padding: '14px 14px 12px',
                      background: 'rgba(34, 197, 94, 0.06)',
                      border: '1px solid rgba(34, 197, 94, 0.10)'
                    }}
                  >
                    <div style={{ fontSize: 12, color: 'var(--color-text-secondary)', marginBottom: 8 }}>运行次数</div>
                    <div style={{ fontSize: 24, fontWeight: 700, color: 'var(--color-text)' }}>{r.runCount}</div>
                  </div>
                  <div
                    style={{
                      borderRadius: 16,
                      padding: '14px 14px 12px',
                      background: 'rgba(249, 115, 22, 0.06)',
                      border: '1px solid rgba(249, 115, 22, 0.10)'
                    }}
                  >
                    <div style={{ fontSize: 12, color: 'var(--color-text-secondary)', marginBottom: 8 }}>触发方式</div>
                    <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--color-text)' }}>{r.scheduleEnabled && r.scheduleCron ? '定时' : '手动'}</div>
                  </div>
                </div>

                <div
                  style={{
                    borderRadius: 16,
                    padding: '16px 16px 14px',
                    background: 'linear-gradient(180deg, rgba(248,250,252,0.9) 0%, rgba(255,255,255,0.95) 100%)',
                    border: '1px solid rgba(148, 163, 184, 0.14)',
                    marginBottom: 16
                  }}
                >
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, color: 'var(--color-text-secondary)', marginBottom: 10 }}>
                    <ClockCircleOutlined />
                    调度与运行
                  </div>
                  {r.scheduleEnabled && r.scheduleCron ? (
                    <Tag bordered={false} style={{ margin: 0, background: 'var(--color-brand-soft)', color: 'var(--color-brand)', borderRadius: 999 }}>
                      cron: {r.scheduleCron}
                    </Tag>
                  ) : (
                    <Tag bordered={false} style={{ margin: 0, background: 'var(--color-surface-2)', color: 'var(--color-text-secondary)', borderRadius: 999 }}>
                      手动触发
                    </Tag>
                  )}
                  <div style={{ fontSize: 12.5, color: 'var(--color-text-tertiary)', marginTop: 10 }}>
                    上次运行 {r.lastRunAt ? new Date(r.lastRunAt).toLocaleString() : '尚未运行'}
                  </div>
                </div>

                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 'auto', paddingTop: 16, borderTop: '1px solid var(--color-border)' }}>
                  <Button type="primary" icon={<ThunderboltOutlined />} onClick={() => onEdit(r)} style={{ borderRadius: 12, height: 40, fontWeight: 600 }}>
                    编辑流程
                  </Button>
                  <Button
                    icon={<PlayCircleOutlined />}
                    onClick={() => {
                      setRunsFor(r);
                      setRunsOpen(true);
                    }}
                    style={{ borderRadius: 12, height: 40 }}
                  >
                    运行 / 历史
                  </Button>
                  <Popconfirm title="删除？" onConfirm={() => onDelete(r)}>
                    <Button danger style={{ borderRadius: 12, height: 40 }}>
                      删除
                    </Button>
                  </Popconfirm>
                </div>
              </div>
            ))}
          </div>
        )}

        {editing && (
          <WorkflowEditorDrawer
            open={editorOpen}
            workflow={editing}
            onClose={() => setEditorOpen(false)}
            onSaved={() => {
              setEditorOpen(false);
              load();
            }}
          />
        )}

        {runsFor && <RunsDrawer open={runsOpen} workflow={runsFor} onClose={() => setRunsOpen(false)} />}
      </div>

      <div className="feature-cover">
        <Empty description="功能规划中，本期不支持" />
      </div>
    </div>
  );
}

