import { useEffect, useCallback, useState } from 'react';
import { Button, Input, message, Modal, Space, Table, Tag } from 'antd';
import { CheckOutlined, CloseOutlined, SendOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import {
  listPendingTasks,
  completeTask,
  delegateTask,
  type TaskInfo,
} from '../../api/workflowTasks';
import { useThemeMode } from '../../hooks/useThemeMode';

export default function PendingTasks() {
  const [data, setData] = useState<TaskInfo[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [completeModal, setCompleteModal] = useState<TaskInfo | null>(null);
  const [outcome, setOutcome] = useState('approved');
  const [delegateModal, setDelegateModal] = useState<TaskInfo | null>(null);
  const [delegateTo, setDelegateTo] = useState('');
  const isDark = useThemeMode();

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

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

  const handleComplete = async () => {
    if (!completeModal) return;
    try {
      await completeTask(completeModal.id, { outcome });
      message.success('审批完成');
      setCompleteModal(null);
      fetchData();
    } catch {
      message.error('审批失败');
    }
  };

  const handleDelegate = async () => {
    if (!delegateModal || !delegateTo.trim()) {
      message.warning('请输入委派目标用户 ID');
      return;
    }
    try {
      await delegateTask(delegateModal.id, { delegate_to: delegateTo.trim() });
      message.success('委派成功');
      setDelegateModal(null);
      setDelegateTo('');
      fetchData();
    } catch {
      message.error('委派失败');
    }
  };

  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 ? (
        <Tag style={{
          background: isDark ? '#0f172a' : '#f8fafc',
          border: 'none',
          color: isDark ? '#94a3b8' : '#475569',
          fontFamily: 'monospace',
          fontSize: 12,
        }}>
          {v}
        </Tag>
      ) : '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (s: string) => (
        <Tag style={{
          background: isDark ? '#172554' : '#eff6ff',
          border: 'none',
          color: isDark ? '#60a5fa' : '#2563eb',
          fontWeight: 500,
        }}>
          {s}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (v: string) => (
        <span style={{ color: isDark ? '#475569' : '#94a3b8', fontSize: 13 }}>
          {new Date(v).toLocaleString()}
        </span>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 160,
      render: (_, record) => (
        <Space size={4}>
          <Button
            size="small"
            type="primary"
            icon={<CheckOutlined />}
            onClick={() => { setCompleteModal(record); setOutcome('approved'); }}
          >
            审批
          </Button>
          <Button
            size="small"
            type="text"
            icon={<SendOutlined />}
            onClick={() => { setDelegateModal(record); setDelegateTo(''); }}
          >
            委派
          </Button>
        </Space>
      ),
    },
  ];

  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>

      <Modal
        title="审批任务"
        open={!!completeModal}
        onOk={handleComplete}
        onCancel={() => setCompleteModal(null)}
      >
        <div style={{ marginTop: 8 }}>
          <p style={{ fontWeight: 500, marginBottom: 16 }}>
            任务: {completeModal?.node_name}
          </p>
          <Space size={12}>
            <Button
              type="primary"
              icon={<CheckOutlined />}
              onClick={() => setOutcome('approved')}
              ghost={outcome !== 'approved'}
            >
              同意
            </Button>
            <Button
              danger
              icon={<CloseOutlined />}
              onClick={() => setOutcome('rejected')}
              ghost={outcome !== 'rejected'}
            >
              拒绝
            </Button>
          </Space>
        </div>
      </Modal>

      <Modal
        title="委派任务"
        open={!!delegateModal}
        onOk={handleDelegate}
        onCancel={() => { setDelegateModal(null); setDelegateTo(''); }}
        okText="确认委派"
      >
        <div style={{ marginTop: 8 }}>
          <p style={{ fontWeight: 500, marginBottom: 16 }}>
            任务: {delegateModal?.node_name}
          </p>
          {/* TODO: 替换为 UserSelect 用户搜索选择组件，支持按姓名/工号搜索 */}
          <Input
            placeholder="输入目标用户 ID (UUID)"
            value={delegateTo}
            onChange={(e) => setDelegateTo(e.target.value)}
          />
        </div>
      </Modal>
    </>
  );
}
