import { useEffect, useState, useCallback, lazy, Suspense } from 'react';
import { Button, message, Modal, Space, Spin, Table, Tag } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import {
  listProcessDefinitions,
  createProcessDefinition,
  updateProcessDefinition,
  publishProcessDefinition,
  type ProcessDefinitionInfo,
  type CreateProcessDefinitionRequest,
} from '../../api/workflowDefinitions';

const ProcessDesigner = lazy(() => import('./ProcessDesigner'));
import { useThemeMode } from '../../hooks/useThemeMode';

const statusColors: Record<string, { bg: string; color: string; text: string }> = {
  draft: { bg: '#f8fafc', color: '#475569', text: '草稿' },
  published: { bg: '#ecfdf5', color: '#059669', text: '已发布' },
  deprecated: { bg: '#fef2f2', color: '#dc2626', text: '已弃用' },
};

export default function ProcessDefinitions() {
  const [data, setData] = useState<ProcessDefinitionInfo[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [designerOpen, setDesignerOpen] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const isDark = useThemeMode();

  const fetchData = useCallback(async (p = page) => {
    setLoading(true);
    try {
      const res = await listProcessDefinitions(p, 20);
      setData(res.data);
      setTotal(res.total);
    } finally {
      setLoading(false);
    }
  }, [page]);

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

  const handleCreate = () => {
    setEditingId(null);
    setDesignerOpen(true);
  };

  const handleEdit = (id: string) => {
    setEditingId(id);
    setDesignerOpen(true);
  };

  const handlePublish = async (id: string) => {
    try {
      await publishProcessDefinition(id);
      message.success('发布成功');
      fetchData();
    } catch {
      message.error('发布失败');
    }
  };

  const handleSave = async (req: CreateProcessDefinitionRequest, id?: string) => {
    try {
      if (id) {
        const current = data.find((d) => d.id === id);
        await updateProcessDefinition(id, { ...req, version: current?.version ?? 0 });
        message.success('更新成功');
      } else {
        await createProcessDefinition(req);
        message.success('创建成功');
      }
      setDesignerOpen(false);
      fetchData();
    } catch {
      message.error(id ? '更新失败' : '创建失败');
    }
  };

  const columns: ColumnsType<ProcessDefinitionInfo> = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (v: string) => <span style={{ fontWeight: 500 }}>{v}</span>,
    },
    {
      title: '编码',
      dataIndex: 'key',
      key: 'key',
      render: (v: string) => (
        <Tag style={{
          background: isDark ? '#1E293B' : '#f8fafc',
          border: 'none',
          color: isDark ? '#94a3b8' : '#475569',
          fontFamily: 'monospace',
          fontSize: 12,
        }}>
          {v}
        </Tag>
      ),
    },
    { title: '版本', dataIndex: 'version', key: 'version', width: 80 },
    { title: '分类', dataIndex: 'category', key: 'category', width: 120 },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (s: string) => {
        const info = statusColors[s] || { bg: '#f8fafc', color: '#475569', text: s };
        return (
          <Tag style={{
            background: info.bg,
            border: 'none',
            color: info.color,
            fontWeight: 500,
          }}>
            {info.text}
          </Tag>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size={4}>
          {record.status === 'draft' && (
            <>
              <Button size="small" type="text" onClick={() => handleEdit(record.id)}>
                编辑
              </Button>
              <Button size="small" type="primary" onClick={() => handlePublish(record.id)}>
                发布
              </Button>
            </>
          )}
        </Space>
      ),
    },
  ];

  return (
    <>
      <div style={{
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: 16,
      }}>
        <span style={{ fontSize: 13, color: isDark ? '#475569' : '#94a3b8' }}>
          共 {total} 个流程定义
        </span>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
          新建流程
        </Button>
      </div>

      <div style={{
        background: isDark ? '#111827' : '#FFFFFF',
        borderRadius: 12,
        border: `1px solid ${isDark ? '#1E293B' : '#f8fafc'}`,
        overflow: 'hidden',
      }}>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={data}
          loading={loading}
          pagination={{
            current: page,
            total,
            pageSize: 20,
            onChange: setPage,
            showTotal: (t) => `共 ${t} 条记录`,
          }}
        />
      </div>

      <Modal
        title={editingId ? '编辑流程' : '新建流程'}
        open={designerOpen}
        onCancel={() => setDesignerOpen(false)}
        footer={null}
        width={1200}
        destroyOnHidden
      >
        <Suspense fallback={<div style={{ textAlign: 'center', padding: 40 }}><Spin /></div>}>
          <ProcessDesigner
            definitionId={editingId}
            onSave={handleSave}
          />
        </Suspense>
      </Modal>
    </>
  );
}
