import { useEffect, useCallback, useState } from 'react';
import { Table, Tag } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { listCompletedTasks, type TaskInfo } from '../../api/workflowTasks';
import { useThemeMode } from '../../hooks/useThemeMode';

const outcomeStyles: Record<string, { bg: string; color: string; text: string }> = {
  approved: { bg: '#ECFDF5', color: '#059669', text: '同意' },
  rejected: { bg: '#FEF2F2', color: '#dc2626', text: '拒绝' },
  delegated: { bg: '#eff6ff', color: '#2563eb', text: '已委派' },
};

export default function CompletedTasks() {
  const [data, setData] = useState<TaskInfo[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const isDark = useThemeMode();

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

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

  const columns: ColumnsType<TaskInfo> = [
    {
      title: '任务名称',
      dataIndex: 'node_name',
      key: 'node_name',
      render: (v: string) => <span style={{ fontWeight: 500 }}>{v}</span>,
    },
    { title: '流程', dataIndex: 'definition_name', key: 'definition_name' },
    {
      title: '业务键',
      dataIndex: 'business_key',
      key: 'business_key',
      render: (v: string | undefined) => v || '-',
    },
    {
      title: '结果',
      dataIndex: 'outcome',
      key: 'outcome',
      width: 100,
      render: (o: string) => {
        const info = outcomeStyles[o] || { bg: '#f8fafc', color: '#475569', text: o };
        return (
          <Tag style={{
            background: info.bg,
            border: 'none',
            color: info.color,
            fontWeight: 500,
          }}>
            {info.text}
          </Tag>
        );
      },
    },
    {
      title: '完成时间',
      dataIndex: 'completed_at',
      key: 'completed_at',
      width: 180,
      render: (v: string) => (
        <span style={{ color: isDark ? '#475569' : '#94a3b8', fontSize: 13 }}>
          {v ? new Date(v).toLocaleString() : '-'}
        </span>
      ),
    },
  ];

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