import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Tag,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  message,
  Tooltip,
  Row,
  Col,
  Statistic,
  Badge,
  Dropdown,
  Menu,
  Tabs,
  Progress,
  Alert,
  Descriptions,
  Timeline,
  InputNumber,
  Switch,
  Steps,
} from 'antd';
import {
  PlayCircleOutlined,
  PauseCircleOutlined,
  StopOutlined,
  ReloadOutlined,
  SearchOutlined,
  FilterOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  SyncOutlined,
  WarningOutlined,
  MoreOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  SettingOutlined,
  RocketOutlined,
  ThunderboltOutlined,
  FileTextOutlined,
  BarChartOutlined,
} from '@ant-design/icons';
import { taskCenterDataSource, Task } from '@/services/taskCenterDataSource';
import type { ColumnsType } from 'antd/es/table';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { TabPane } = Tabs;
const { Step } = Steps;

interface Task {
  id: string;
  taskId: string;
  name: string;
  type: 'PRODUCT_SYNC' | 'ORDER_PROCESS' | 'DATA_ANALYSIS' | 'AD_OPTIMIZATION' | 'INVENTORY_CHECK' | 'CUSTOM';
  status: 'PENDING' | 'RUNNING' | 'PAUSED' | 'COMPLETED' | 'FAILED' | 'CANCELLED';
  priority: 'LOW' | 'MEDIUM' | 'HIGH' | 'URGENT';
  progress: number;
  createdAt: string;
  startedAt?: string;
  completedAt?: string;
  estimatedDuration?: number;
  actualDuration?: number;
  retryCount: number;
  maxRetries: number;
  shopId: string;
  shopName: string;
  createdBy: string;
  scheduleType: 'MANUAL' | 'SCHEDULED' | 'TRIGGERED';
  scheduleTime?: string;
  result?: any;
  errorMessage?: string;
}

const TASK_TYPE_MAP: Record<string, { color: string; text: string; icon: React.ReactNode }> = {
  PRODUCT_SYNC: { color: 'blue', text: 'Product Sync', icon: <SyncOutlined /> },
  ORDER_PROCESS: { color: 'green', text: 'Order Process', icon: <FileTextOutlined /> },
  DATA_ANALYSIS: { color: 'purple', text: 'Data Analysis', icon: <BarChartOutlined /> },
  AD_OPTIMIZATION: { color: 'orange', text: 'Ad Optimization', icon: <ThunderboltOutlined /> },
  INVENTORY_CHECK: { color: 'cyan', text: 'Inventory Check', icon: <RocketOutlined /> },
  CUSTOM: { color: 'default', text: 'Custom', icon: <SettingOutlined /> },
};

const TASK_STATUS_MAP: Record<string, { color: string; text: string; icon: React.ReactNode }> = {
  PENDING: { color: 'default', text: 'Pending', icon: <ClockCircleOutlined /> },
  RUNNING: { color: 'processing', text: 'Running', icon: <SyncOutlined spin /> },
  PAUSED: { color: 'warning', text: 'Paused', icon: <PauseCircleOutlined /> },
  COMPLETED: { color: 'success', text: 'Completed', icon: <CheckCircleOutlined /> },
  FAILED: { color: 'error', text: 'Failed', icon: <WarningOutlined /> },
  CANCELLED: { color: 'default', text: 'Cancelled', icon: <StopOutlined /> },
};

const PRIORITY_MAP: Record<string, { color: string; text: string }> = {
  LOW: { color: 'default', text: 'Low' },
  MEDIUM: { color: 'blue', text: 'Medium' },
  HIGH: { color: 'orange', text: 'High' },
  URGENT: { color: 'red', text: 'Urgent' },
};

const SCHEDULE_TYPE_MAP: Record<string, { color: string; text: string }> = {
  MANUAL: { color: 'default', text: 'Manual' },
  SCHEDULED: { color: 'blue', text: 'Scheduled' },
  TRIGGERED: { color: 'green', text: 'Triggered' },
};

export const TaskCenter: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [tasks, setTasks] = useState<Task[]>([]);
  const [selectedTask, setSelectedTask] = useState<Task | null>(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [activeTab, setActiveTab] = useState('all');
  const [searchText, setSearchText] = useState('');
  const [filterStatus, setFilterStatus] = useState<string>('');
  const [filterType, setFilterType] = useState<string>('');
  const [filterPriority, setFilterPriority] = useState<string>('');
  const [stats, setStats] = useState({
    total: 0,
    pending: 0,
    running: 0,
    completed: 0,
    failed: 0,
  });
  const [createForm] = Form.useForm();
  const [editForm] = Form.useForm();

  useEffect(() => {
    fetchTasks();
    const interval = setInterval(fetchTasks, 5000);
    return () => clearInterval(interval);
  }, []);

  const fetchTasks = async () => {
    setLoading(true);
    try {
      const mockTasks: Task[] = [
        {
          id: '1',
          taskId: 'TASK-2026-001',
          name: 'Product Sync - Amazon US',
          type: 'PRODUCT_SYNC',
          status: 'RUNNING',
          priority: 'HIGH',
          progress: 65,
          createdAt: '2026-03-18 10:00:00',
          startedAt: '2026-03-18 10:05:00',
          estimatedDuration: 30,
          retryCount: 0,
          maxRetries: 3,
          shopId: 'SHOP_001',
          shopName: 'Amazon US Store',
          createdBy: 'admin',
          scheduleType: 'MANUAL',
        },
        {
          id: '2',
          taskId: 'TASK-2026-002',
          name: 'Order Processing - Batch 001',
          type: 'ORDER_PROCESS',
          status: 'COMPLETED',
          priority: 'URGENT',
          progress: 100,
          createdAt: '2026-03-18 09:00:00',
          startedAt: '2026-03-18 09:01:00',
          completedAt: '2026-03-18 09:15:00',
          estimatedDuration: 15,
          actualDuration: 14,
          retryCount: 0,
          maxRetries: 3,
          shopId: 'SHOP_002',
          shopName: 'eBay Outlet',
          createdBy: 'admin',
          scheduleType: 'MANUAL',
          result: { processedOrders: 150, successCount: 148, failedCount: 2 },
        },
        {
          id: '3',
          taskId: 'TASK-2026-003',
          name: 'Data Analysis - Weekly Report',
          type: 'DATA_ANALYSIS',
          status: 'PENDING',
          priority: 'MEDIUM',
          progress: 0,
          createdAt: '2026-03-18 08:00:00',
          estimatedDuration: 60,
          retryCount: 0,
          maxRetries: 3,
          shopId: 'SHOP_003',
          shopName: 'Shopify Brand Store',
          createdBy: 'admin',
          scheduleType: 'SCHEDULED',
          scheduleTime: '2026-03-18 12:00:00',
        },
        {
          id: '4',
          taskId: 'TASK-2026-004',
          name: 'Ad Optimization - Campaign A',
          type: 'AD_OPTIMIZATION',
          status: 'FAILED',
          priority: 'HIGH',
          progress: 45,
          createdAt: '2026-03-18 07:30:00',
          startedAt: '2026-03-18 07:31:00',
          estimatedDuration: 20,
          actualDuration: 25,
          retryCount: 3,
          maxRetries: 3,
          shopId: 'SHOP_001',
          shopName: 'Amazon US Store',
          createdBy: 'admin',
          scheduleType: 'TRIGGERED',
          errorMessage: 'API rate limit exceeded. Please retry later.',
        },
        {
          id: '5',
          taskId: 'TASK-2026-005',
          name: 'Inventory Check - All Warehouses',
          type: 'INVENTORY_CHECK',
          status: 'PAUSED',
          priority: 'MEDIUM',
          progress: 30,
          createdAt: '2026-03-18 06:00:00',
          startedAt: '2026-03-18 06:01:00',
          estimatedDuration: 45,
          retryCount: 0,
          maxRetries: 3,
          shopId: 'SHOP_004',
          shopName: 'Shopee Mall',
          createdBy: 'admin',
          scheduleType: 'MANUAL',
        },
        {
          id: '6',
          taskId: 'TASK-2026-006',
          name: 'Custom Task - Data Export',
          type: 'CUSTOM',
          status: 'COMPLETED',
          priority: 'LOW',
          progress: 100,
          createdAt: '2026-03-17 18:00:00',
          startedAt: '2026-03-17 18:01:00',
          completedAt: '2026-03-17 18:30:00',
          estimatedDuration: 30,
          actualDuration: 29,
          retryCount: 0,
          maxRetries: 3,
          shopId: 'SHOP_005',
          shopName: 'Lazada Store',
          createdBy: 'user1',
          scheduleType: 'MANUAL',
          result: { exportedRecords: 5000, fileSize: '25MB' },
        },
      ];
      setTasks(mockTasks);
      calculateStats(mockTasks);
    } catch (error) {
      message.error('Failed to load tasks');
    } finally {
      setLoading(false);
    }
  };

  const calculateStats = (taskList: Task[]) => {
    setStats({
      total: taskList.length,
      pending: taskList.filter((t) => t.status === 'PENDING').length,
      running: taskList.filter((t) => t.status === 'RUNNING').length,
      completed: taskList.filter((t) => t.status === 'COMPLETED').length,
      failed: taskList.filter((t) => t.status === 'FAILED').length,
    });
  };

  const handleViewDetail = (task: Task) => {
    setSelectedTask(task);
    setDetailModalVisible(true);
  };

  const handleStart = async (taskId: string) => {
    setLoading(true);
    try {
      console.log('Starting task:', taskId);
      await new Promise((resolve) => setTimeout(resolve, 500));
      message.success('Task started successfully');
      fetchTasks();
    } catch (error) {
      message.error('Failed to start task');
    } finally {
      setLoading(false);
    }
  };

  const handlePause = async (taskId: string) => {
    setLoading(true);
    try {
      console.log('Pausing task:', taskId);
      await new Promise((resolve) => setTimeout(resolve, 500));
      message.success('Task paused successfully');
      fetchTasks();
    } catch (error) {
      message.error('Failed to pause task');
    } finally {
      setLoading(false);
    }
  };

  const handleStop = async (taskId: string) => {
    setLoading(true);
    try {
      console.log('Stopping task:', taskId);
      await new Promise((resolve) => setTimeout(resolve, 500));
      message.success('Task stopped successfully');
      fetchTasks();
    } catch (error) {
      message.error('Failed to stop task');
    } finally {
      setLoading(false);
    }
  };

  const handleRetry = async (taskId: string) => {
    setLoading(true);
    try {
      console.log('Retrying task:', taskId);
      await new Promise((resolve) => setTimeout(resolve, 500));
      message.success('Task retry initiated');
      fetchTasks();
    } catch (error) {
      message.error('Failed to retry task');
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (taskId: string) => {
    setLoading(true);
    try {
      console.log('Deleting task:', taskId);
      await new Promise((resolve) => setTimeout(resolve, 500));
      message.success('Task deleted successfully');
      fetchTasks();
    } catch (error) {
      message.error('Failed to delete task');
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = () => {
    createForm.resetFields();
    setCreateModalVisible(true);
  };

  const handleCreateSubmit = async () => {
    try {
      const values = await createForm.validateFields();
      console.log('Creating task:', values);
      message.success('Task created successfully');
      setCreateModalVisible(false);
      fetchTasks();
    } catch (error) {
      message.error('Failed to create task');
    }
  };

  const handleEdit = (task: Task) => {
    setSelectedTask(task);
    editForm.setFieldsValue({
      name: task.name,
      type: task.type,
      priority: task.priority,
      scheduleType: task.scheduleType,
      scheduleTime: task.scheduleTime,
      maxRetries: task.maxRetries,
    });
    setEditModalVisible(true);
  };

  const handleEditSubmit = async () => {
    try {
      const values = await editForm.validateFields();
      console.log('Updating task:', { taskId: selectedTask?.id, ...values });
      message.success('Task updated successfully');
      setEditModalVisible(false);
      fetchTasks();
    } catch (error) {
      message.error('Failed to update task');
    }
  };

  const handleSearch = (value: string) => {
    setSearchText(value);
  };

  const handleFilter = (field: string, value: string) => {
    if (field === 'status') setFilterStatus(value);
    if (field === 'type') setFilterType(value);
    if (field === 'priority') setFilterPriority(value);
  };

  const getFilteredTasks = () => {
    let filtered = tasks;

    if (activeTab !== 'all') {
      filtered = filtered.filter((t) => t.status === activeTab);
    }

    if (searchText) {
      filtered = filtered.filter(
        (t) =>
          t.taskId.toLowerCase().includes(searchText.toLowerCase()) ||
          t.name.toLowerCase().includes(searchText.toLowerCase())
      );
    }

    if (filterStatus) {
      filtered = filtered.filter((t) => t.status === filterStatus);
    }

    if (filterType) {
      filtered = filtered.filter((t) => t.type === filterType);
    }

    if (filterPriority) {
      filtered = filtered.filter((t) => t.priority === filterPriority);
    }

    return filtered;
  };

  const columns: ColumnsType<Task> = [
    {
      title: 'Task ID',
      dataIndex: 'taskId',
      key: 'taskId',
      width: 140,
      render: (text: string, record) => (
        <a onClick={() => handleViewDetail(record)}>{text}</a>
      ),
    },
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      width: 200,
    },
    {
      title: 'Type',
      dataIndex: 'type',
      key: 'type',
      width: 130,
      filters: Object.keys(TASK_TYPE_MAP).map((key) => ({
        text: TASK_TYPE_MAP[key].text,
        value: key,
      })),
      render: (type: string) => {
        const config = TASK_TYPE_MAP[type];
        return <Tag icon={config.icon} color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 110,
      filters: Object.keys(TASK_STATUS_MAP).map((key) => ({
        text: TASK_STATUS_MAP[key].text,
        value: key,
      })),
      render: (status: string) => {
        const config = TASK_STATUS_MAP[status];
        return <Tag icon={config.icon} color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: 'Priority',
      dataIndex: 'priority',
      key: 'priority',
      width: 90,
      filters: Object.keys(PRIORITY_MAP).map((key) => ({
        text: PRIORITY_MAP[key].text,
        value: key,
      })),
      render: (priority: string) => {
        const config = PRIORITY_MAP[priority];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: 'Progress',
      dataIndex: 'progress',
      key: 'progress',
      width: 150,
      render: (progress: number, record) => (
        <Progress
          percent={progress}
          status={record.status === 'FAILED' ? 'exception' : record.status === 'COMPLETED' ? 'success' : 'active'}
          size="small"
        />
      ),
    },
    {
      title: 'Shop',
      dataIndex: 'shopName',
      key: 'shopName',
      width: 150,
    },
    {
      title: 'Created',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 160,
    },
    {
      title: 'Actions',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="View Details">
            <Button type="link" icon={<EyeOutlined />} onClick={() => handleViewDetail(record)} />
          </Tooltip>
          {record.status === 'PENDING' && (
            <Tooltip title="Start Task">
              <Button type="link" icon={<PlayCircleOutlined />} onClick={() => handleStart(record.taskId)} />
            </Tooltip>
          )}
          {record.status === 'RUNNING' && (
            <Tooltip title="Pause Task">
              <Button type="link" icon={<PauseCircleOutlined />} onClick={() => handlePause(record.taskId)} />
            </Tooltip>
          )}
          {record.status === 'PAUSED' && (
            <Tooltip title="Resume Task">
              <Button type="link" icon={<PlayCircleOutlined />} onClick={() => handleStart(record.taskId)} />
            </Tooltip>
          )}
          {(record.status === 'RUNNING' || record.status === 'PAUSED') && (
            <Tooltip title="Stop Task">
              <Button type="link" danger icon={<StopOutlined />} onClick={() => handleStop(record.taskId)} />
            </Tooltip>
          )}
          {record.status === 'FAILED' && record.retryCount < record.maxRetries && (
            <Tooltip title="Retry Task">
              <Button type="link" icon={<ReloadOutlined />} onClick={() => handleRetry(record.taskId)} />
            </Tooltip>
          )}
          <Tooltip title="Edit Task">
            <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record)} />
          </Tooltip>
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item key="delete" danger onClick={() => handleDelete(record.taskId)}>
                  Delete Task
                </Menu.Item>
              </Menu>
            }
          >
            <Button type="link" icon={<MoreOutlined />} />
          </Dropdown>
        </Space>
      ),
    },
  ];

  return (
    <div className="task-center-page">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={4}>
          <Card>
            <Statistic title="Total Tasks" value={stats.total} />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="Pending"
              value={stats.pending}
              valueStyle={{ color: '#faad14' }}
              prefix={<ClockCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="Running"
              value={stats.running}
              valueStyle={{ color: '#1890ff' }}
              prefix={<SyncOutlined spin />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="Completed"
              value={stats.completed}
              valueStyle={{ color: '#52c41a' }}
              prefix={<CheckCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="Failed"
              value={stats.failed}
              valueStyle={{ color: '#ff4d4f' }}
              prefix={<WarningOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate} block>
              Create Task
            </Button>
          </Card>
        </Col>
      </Row>

      <Card
        title="Task Center"
        extra={
          <Space>
            <Button icon={<ReloadOutlined />} onClick={fetchTasks}>
              Refresh
            </Button>
          </Space>
        }
      >
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="All Tasks" key="all" />
          <TabPane tab={<Badge count={stats.pending} offset={[10, 0]} size="small">Pending</Badge>} key="PENDING" />
          <TabPane tab={<Badge count={stats.running} offset={[10, 0]} size="small">Running</Badge>} key="RUNNING" />
          <TabPane tab="Completed" key="COMPLETED" />
          <TabPane tab={<Badge count={stats.failed} offset={[10, 0]} size="small">Failed</Badge>} key="FAILED" />
        </Tabs>

        <Card size="small" style={{ marginBottom: 16 }}>
          <Row gutter={16}>
            <Col span={8}>
              <Input
                placeholder="Search task ID or name"
                prefix={<SearchOutlined />}
                value={searchText}
                onChange={(e) => handleSearch(e.target.value)}
                allowClear
              />
            </Col>
            <Col span={4}>
              <Select
                placeholder="Filter by Status"
                value={filterStatus}
                onChange={(value) => handleFilter('status', value)}
                allowClear
                style={{ width: '100%' }}
              >
                {Object.keys(TASK_STATUS_MAP).map((key) => (
                  <Option key={key} value={key}>
                    {TASK_STATUS_MAP[key].text}
                  </Option>
                ))}
              </Select>
            </Col>
            <Col span={4}>
              <Select
                placeholder="Filter by Type"
                value={filterType}
                onChange={(value) => handleFilter('type', value)}
                allowClear
                style={{ width: '100%' }}
              >
                {Object.keys(TASK_TYPE_MAP).map((key) => (
                  <Option key={key} value={key}>
                    {TASK_TYPE_MAP[key].text}
                  </Option>
                ))}
              </Select>
            </Col>
            <Col span={4}>
              <Select
                placeholder="Filter by Priority"
                value={filterPriority}
                onChange={(value) => handleFilter('priority', value)}
                allowClear
                style={{ width: '100%' }}
              >
                {Object.keys(PRIORITY_MAP).map((key) => (
                  <Option key={key} value={key}>
                    {PRIORITY_MAP[key].text}
                  </Option>
                ))}
              </Select>
            </Col>
          </Row>
        </Card>

        <Table
          columns={columns}
          dataSource={getFilteredTasks()}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1400 }}
          pagination={{
            showSizeChanger: true,
            showTotal: (total) => `Total ${total} tasks`,
          }}
        />
      </Card>

      <Modal
        title="Task Details"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            Close
          </Button>,
        ]}
        width={900}
      >
        {selectedTask && (
          <>
            {selectedTask.status === 'FAILED' && (
              <Alert
                message="Task Failed"
                description={selectedTask.errorMessage}
                type="error"
                showIcon
                style={{ marginBottom: 16 }}
              />
            )}
            <Row gutter={16}>
              <Col span={12}>
                <Card size="small" title="Task Info">
                  <p><strong>Task ID:</strong> {selectedTask.taskId}</p>
                  <p><strong>Name:</strong> {selectedTask.name}</p>
                  <p><strong>Type:</strong> <Tag icon={TASK_TYPE_MAP[selectedTask.type].icon} color={TASK_TYPE_MAP[selectedTask.type].color}>{TASK_TYPE_MAP[selectedTask.type].text}</Tag></p>
                  <p><strong>Status:</strong> <Tag icon={TASK_STATUS_MAP[selectedTask.status].icon} color={TASK_STATUS_MAP[selectedTask.status].color}>{TASK_STATUS_MAP[selectedTask.status].text}</Tag></p>
                  <p><strong>Priority:</strong> <Tag color={PRIORITY_MAP[selectedTask.priority].color}>{PRIORITY_MAP[selectedTask.priority].text}</Tag></p>
                  <p><strong>Schedule Type:</strong> <Tag color={SCHEDULE_TYPE_MAP[selectedTask.scheduleType].color}>{SCHEDULE_TYPE_MAP[selectedTask.scheduleType].text}</Tag></p>
                </Card>
              </Col>
              <Col span={12}>
                <Card size="small" title="Progress">
                  <Progress
                    percent={selectedTask.progress}
                    status={selectedTask.status === 'FAILED' ? 'exception' : selectedTask.status === 'COMPLETED' ? 'success' : 'active'}
                    strokeColor={{
                      '0%': '#108ee9',
                      '100%': '#87d068',
                    }}
                  />
                  <p style={{ marginTop: 16 }}><strong>Retry Count:</strong> {selectedTask.retryCount} / {selectedTask.maxRetries}</p>
                </Card>
              </Col>
            </Row>
            <Card size="small" title="Shop Info" style={{ marginTop: 16 }}>
              <p><strong>Shop:</strong> {selectedTask.shopName}</p>
              <p><strong>Created By:</strong> {selectedTask.createdBy}</p>
            </Card>
            <Card size="small" title="Timing" style={{ marginTop: 16 }}>
              <Descriptions column={2}>
                <Descriptions.Item label="Created At">{selectedTask.createdAt}</Descriptions.Item>
                <Descriptions.Item label="Started At">{selectedTask.startedAt || '-'}</Descriptions.Item>
                <Descriptions.Item label="Completed At">{selectedTask.completedAt || '-'}</Descriptions.Item>
                <Descriptions.Item label="Schedule Time">{selectedTask.scheduleTime || '-'}</Descriptions.Item>
                <Descriptions.Item label="Estimated Duration">{selectedTask.estimatedDuration ? `${selectedTask.estimatedDuration} min` : '-'}</Descriptions.Item>
                <Descriptions.Item label="Actual Duration">{selectedTask.actualDuration ? `${selectedTask.actualDuration} min` : '-'}</Descriptions.Item>
              </Descriptions>
            </Card>
            {selectedTask.result && (
              <Card size="small" title="Result" style={{ marginTop: 16 }}>
                <pre>{JSON.stringify(selectedTask.result, null, 2)}</pre>
              </Card>
            )}
          </>
        )}
      </Modal>

      <Modal
        title="Create New Task"
        open={createModalVisible}
        onOk={handleCreateSubmit}
        onCancel={() => setCreateModalVisible(false)}
        width={600}
      >
        <Form form={createForm} layout="vertical">
          <Form.Item
            name="name"
            label="Task Name"
            rules={[{ required: true, message: 'Please enter task name' }]}
          >
            <Input placeholder="Enter task name" />
          </Form.Item>
          <Form.Item
            name="type"
            label="Task Type"
            rules={[{ required: true, message: 'Please select task type' }]}
          >
            <Select placeholder="Select task type">
              {Object.keys(TASK_TYPE_MAP).map((key) => (
                <Option key={key} value={key}>
                  {TASK_TYPE_MAP[key].text}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="priority"
            label="Priority"
            rules={[{ required: true, message: 'Please select priority' }]}
          >
            <Select placeholder="Select priority">
              {Object.keys(PRIORITY_MAP).map((key) => (
                <Option key={key} value={key}>
                  {PRIORITY_MAP[key].text}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="scheduleType"
            label="Schedule Type"
            rules={[{ required: true, message: 'Please select schedule type' }]}
          >
            <Select placeholder="Select schedule type">
              {Object.keys(SCHEDULE_TYPE_MAP).map((key) => (
                <Option key={key} value={key}>
                  {SCHEDULE_TYPE_MAP[key].text}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="scheduleTime"
            label="Schedule Time"
          >
            <DatePicker showTime style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="maxRetries"
            label="Max Retries"
            rules={[{ required: true, message: 'Please enter max retries' }]}
          >
            <InputNumber min={0} max={10} style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Edit Task"
        open={editModalVisible}
        onOk={handleEditSubmit}
        onCancel={() => setEditModalVisible(false)}
        width={600}
      >
        <Form form={editForm} layout="vertical">
          <Form.Item
            name="name"
            label="Task Name"
            rules={[{ required: true, message: 'Please enter task name' }]}
          >
            <Input placeholder="Enter task name" />
          </Form.Item>
          <Form.Item
            name="type"
            label="Task Type"
            rules={[{ required: true, message: 'Please select task type' }]}
          >
            <Select placeholder="Select task type">
              {Object.keys(TASK_TYPE_MAP).map((key) => (
                <Option key={key} value={key}>
                  {TASK_TYPE_MAP[key].text}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="priority"
            label="Priority"
            rules={[{ required: true, message: 'Please select priority' }]}
          >
            <Select placeholder="Select priority">
              {Object.keys(PRIORITY_MAP).map((key) => (
                <Option key={key} value={key}>
                  {PRIORITY_MAP[key].text}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="scheduleType"
            label="Schedule Type"
            rules={[{ required: true, message: 'Please select schedule type' }]}
          >
            <Select placeholder="Select schedule type">
              {Object.keys(SCHEDULE_TYPE_MAP).map((key) => (
                <Option key={key} value={key}>
                  {SCHEDULE_TYPE_MAP[key].text}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="scheduleTime"
            label="Schedule Time"
          >
            <DatePicker showTime style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="maxRetries"
            label="Max Retries"
            rules={[{ required: true, message: 'Please enter max retries' }]}
          >
            <InputNumber min={0} max={10} style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default TaskCenter;
