import {
  useState,
  useEffect,
  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,
  PlayCircleOutlined,
  PauseCircleOutlined,
  StopOutlined,
  ReloadOutlined,
  SearchOutlined,
  FilterOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  SyncOutlined,
  WarningOutlined,
  MoreOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  SettingOutlined,
  RocketOutlined,
  ThunderboltOutlined,
  FileTextOutlined,
  BarChartOutlined,
  UserOutlined,
  RobotOutlined,
  ArrowRightOutlined,
  aiActionTaskDataSource,
  Option,
  RangePicker,
  Step,
  FC,
} from '@/imports';
import type { AITask } from '@/services/aiActionTaskDataSource';
import type { ColumnsType } from 'antd/es/table';

const ACTION_TYPE_MAP: Record<string, { color: string; text: string; icon: React.ReactNode }> = {
  PRICING_OPTIMIZATION: { color: 'blue', text: 'Pricing Optimization', icon: <BarChartOutlined /> },
  ORDER_PROCESSING: { color: 'green', text: 'Order Processing', icon: <FileTextOutlined /> },
  INVENTORY_MANAGEMENT: { color: 'purple', text: 'Inventory Management', icon: <RocketOutlined /> },
  MARKETING_CAMPAIGN: { color: 'orange', text: 'Marketing Campaign', icon: <ThunderboltOutlined /> },
  PRODUCT_OPTIMIZATION: { color: 'cyan', text: 'Product Optimization', icon: <SettingOutlined /> },
  CUSTOM: { color: 'default', text: 'Custom Action', icon: <SettingOutlined /> },
};

const TASK_STATUS_MAP: Record<string, { color: string; text: string; icon: React.ReactNode }> = {
  PENDING: { color: 'default', text: 'Pending', icon: <ClockCircleOutlined /> },
  AI_ANALYZING: { color: 'processing', text: 'AI Analyzing', icon: <RobotOutlined /> },
  PENDING_REVIEW: { color: 'warning', text: 'Pending Review', icon: <UserOutlined /> },
  APPROVED: { color: 'success', text: 'Approved', icon: <CheckCircleOutlined /> },
  REJECTED: { color: 'error', text: 'Rejected', icon: <StopOutlined /> },
  AI_EXECUTING: { color: 'processing', text: 'AI Executing', icon: <RobotOutlined /> },
  COMPLETED: { color: 'success', text: 'Completed', icon: <CheckCircleOutlined /> },
  FAILED: { color: 'error', text: 'Failed', icon: <WarningOutlined /> },
};

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 AIActionTaskManager: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [tasks, setTasks] = useState<AITask[]>([]);
  const [selectedTask, setSelectedTask] = useState<AITask | 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,
    analyzing: 0,
    pendingReview: 0,
    approved: 0,
    rejected: 0,
    executing: 0,
    completed: 0,
    failed: 0,
  });
  const [createForm] = Form.useForm();
  const [editForm] = Form.useForm();

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

  const fetchTasks = async () => {
    setLoading(true);
    try {
      const [tasks, stats] = await Promise.all([
        aiActionTaskDataSource.fetchTasks({
          status: activeTab !== 'all' ? activeTab : undefined,
          search: searchText || undefined,
          actionType: filterType || undefined,
          priority: filterPriority || undefined,
        }),
        aiActionTaskDataSource.getTaskStats(),
      ]);
      setTasks(tasks);
      setStats(stats);
    } catch (error) {
      message.error('Failed to load tasks');
    } finally {
      setLoading(false);
    }
  };

  const calculateStats = (taskList: AITask[]) => {
    setStats({
      total: taskList.length,
      pending: taskList.filter((t) => t.status === 'PENDING').length,
      analyzing: taskList.filter((t) => t.status === 'AI_ANALYZING').length,
      pendingReview: taskList.filter((t) => t.status === 'PENDING_REVIEW').length,
      approved: taskList.filter((t) => t.status === 'APPROVED').length,
      rejected: taskList.filter((t) => t.status === 'REJECTED').length,
      executing: taskList.filter((t) => t.status === 'AI_EXECUTING').length,
      completed: taskList.filter((t) => t.status === 'COMPLETED').length,
      failed: taskList.filter((t) => t.status === 'FAILED').length,
    });
  };

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

  const handleStart = async (taskId: string) => {
    setLoading(true);
    try {
      await aiActionTaskDataSource.startTask(taskId);
      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 {
      await aiActionTaskDataSource.pauseTask(taskId);
      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 {
      await aiActionTaskDataSource.stopTask(taskId);
      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 {
      await aiActionTaskDataSource.retryTask(taskId);
      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 {
      await aiActionTaskDataSource.deleteTask(taskId);
      message.success('Task deleted successfully');
      fetchTasks();
    } catch (error) {
      message.error('Failed to delete task');
    } finally {
      setLoading(false);
    }
  };

  const handleApprove = async (taskId: string) => {
    setLoading(true);
    try {
      await aiActionTaskDataSource.approveTask(taskId);
      message.success('Task approved successfully');
      fetchTasks();
    } catch (error) {
      message.error('Failed to approve task');
    } finally {
      setLoading(false);
    }
  };

  const handleReject = async (taskId: string) => {
    setLoading(true);
    try {
      await aiActionTaskDataSource.rejectTask(taskId);
      message.success('Task rejected successfully');
      fetchTasks();
    } catch (error) {
      message.error('Failed to reject task');
    } finally {
      setLoading(false);
    }
  };

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

  const handleCreateSubmit = async () => {
    try {
      const values = await createForm.validateFields();
      await aiActionTaskDataSource.createTask({
        name: values.name,
        actionType: values.actionType,
        priority: values.priority,
        estimatedDuration: values.estimatedDuration,
        maxRetries: values.maxRetries,
        shopId: 'SHOP_001',
        shopName: 'Amazon US Store',
        createdBy: 'admin',
      });
      message.success('Task created successfully');
      setCreateModalVisible(false);
      fetchTasks();
    } catch (error) {
      message.error('Failed to create task');
    }
  };

  const handleEdit = (task: AITask) => {
    setSelectedTask(task);
    editForm.setFieldsValue({
      name: task.name,
      actionType: task.actionType,
      priority: task.priority,
      maxRetries: task.maxRetries,
    });
    setEditModalVisible(true);
  };

  const handleEditSubmit = async () => {
    try {
      const values = await editForm.validateFields();
      if (selectedTask) {
        await aiActionTaskDataSource.updateTask(selectedTask.id, {
          name: values.name,
          actionType: values.actionType,
          priority: values.priority,
          maxRetries: values.maxRetries,
        });
        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 = () => {
    return tasks;
  };

  const columns: ColumnsType<AITask> = [
    {
      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: 'Action Type',
      dataIndex: 'actionType',
      key: 'actionType',
      width: 150,
      filters: Object.keys(ACTION_TYPE_MAP).map((key) => ({
        text: ACTION_TYPE_MAP[key].text,
        value: key,
      })),
      render: (type: string) => {
        const config = ACTION_TYPE_MAP[type];
        return <Tag icon={config.icon} color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 130,
      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: 250,
      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={() => record.taskId && handleStart(record.taskId)} />
            </Tooltip>
          )}
          {record.status === 'AI_ANALYZING' && (
            <Tooltip title="Stop Task">
              <Button type="link" danger icon={<StopOutlined />} onClick={() => record.taskId && handleStop(record.taskId)} />
            </Tooltip>
          )}
          {record.status === 'PENDING_REVIEW' && (
            <>
              <Tooltip title="Approve">
                <Button type="link" icon={<CheckCircleOutlined />} onClick={() => record.taskId && handleApprove(record.taskId)} />
              </Tooltip>
              <Tooltip title="Reject">
                <Button type="link" danger icon={<StopOutlined />} onClick={() => record.taskId && handleReject(record.taskId)} />
              </Tooltip>
            </>
          )}
          {record.status === 'AI_EXECUTING' && (
            <Tooltip title="Stop Task">
              <Button type="link" danger icon={<StopOutlined />} onClick={() => record.taskId && handleStop(record.taskId)} />
            </Tooltip>
          )}
          {record.status === 'FAILED' && (record.retryCount || 0) < (record.maxRetries || 0) && (
            <Tooltip title="Retry Task">
              <Button type="link" icon={<ReloadOutlined />} onClick={() => record.taskId && 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={() => record.taskId && handleDelete(record.taskId)}>
                  Delete Task
                </Menu.Item>
              </Menu>
            }
          >
            <Button type="link" icon={<MoreOutlined />} />
          </Dropdown>
        </Space>
      ),
    },
  ];

  return (
    <div className="ai-action-task-manager">
      <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="Analyzing"
              value={stats.analyzing}
              valueStyle={{ color: '#1890ff' }}
              prefix={<RobotOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="Pending Review"
              value={stats.pendingReview}
              valueStyle={{ color: '#fa8c16' }}
              prefix={<UserOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="Executing"
              value={stats.executing}
              valueStyle={{ color: '#1890ff' }}
              prefix={<RobotOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate} block>
              Create Task
            </Button>
          </Card>
        </Col>
      </Row>

      <Card
        title="AI Action Task Manager"
        extra={
          <Space size="middle">
            <Input.Search
              placeholder="Search tasks..."
              onSearch={handleSearch}
              style={{ width: 200 }}
            />
            <Select
              placeholder="Filter by status"
              style={{ width: 120 }}
              onChange={(value) => handleFilter('status', value)}
            >
              <Option value="">All</Option>
              {Object.keys(TASK_STATUS_MAP).map((key) => (
                <Option key={key} value={key}>{TASK_STATUS_MAP[key].text}</Option>
              ))}
            </Select>
            <Select
              placeholder="Filter by type"
              style={{ width: 150 }}
              onChange={(value) => handleFilter('type', value)}
            >
              <Option value="">All</Option>
              {Object.keys(ACTION_TYPE_MAP).map((key) => (
                <Option key={key} value={key}>{ACTION_TYPE_MAP[key].text}</Option>
              ))}
            </Select>
            <Select
              placeholder="Filter by priority"
              style={{ width: 100 }}
              onChange={(value) => handleFilter('priority', value)}
            >
              <Option value="">All</Option>
              {Object.keys(PRIORITY_MAP).map((key) => (
                <Option key={key} value={key}>{PRIORITY_MAP[key].text}</Option>
              ))}
            </Select>
          </Space>
        }
      >
        <Tabs 
          activeKey={activeTab} 
          onChange={setActiveTab}
          items={[
            { label: 'All', key: 'all' },
            { label: 'Pending', key: 'PENDING' },
            { label: 'Analyzing', key: 'AI_ANALYZING' },
            { label: 'Pending Review', key: 'PENDING_REVIEW' },
            { label: 'Executing', key: 'AI_EXECUTING' },
            { label: 'Completed', key: 'COMPLETED' },
            { label: 'Failed', key: 'FAILED' },
          ]}
        />

        <Table
          columns={columns}
          dataSource={getFilteredTasks()}
          rowKey="id"
          loading={loading}
          pagination={{ pageSize: 10 }}
        />
      </Card>

      <Modal
        title="Task Details"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            Close
          </Button>,
        ]}
        width={800}
      >
        {selectedTask && (
          <div>
            <Descriptions title="Task Information" bordered>
              <Descriptions.Item label="Task ID">{selectedTask.taskId}</Descriptions.Item>
              <Descriptions.Item label="Name">{selectedTask.name}</Descriptions.Item>
              <Descriptions.Item label="Action Type">
                <Tag color={ACTION_TYPE_MAP[selectedTask.actionType]?.color}>
                  {ACTION_TYPE_MAP[selectedTask.actionType]?.text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Status">
                <Tag color={TASK_STATUS_MAP[selectedTask.status]?.color}>
                  {TASK_STATUS_MAP[selectedTask.status]?.text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Priority">
                <Tag color={PRIORITY_MAP[selectedTask.priority]?.color}>
                  {PRIORITY_MAP[selectedTask.priority]?.text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Progress">
                <Progress percent={selectedTask.progress} size="small" />
              </Descriptions.Item>
              <Descriptions.Item label="Shop">{selectedTask.shopName}</Descriptions.Item>
              <Descriptions.Item label="Created By">{selectedTask.createdBy}</Descriptions.Item>
              <Descriptions.Item label="Created At" span={3}>{selectedTask.createdAt}</Descriptions.Item>
              {selectedTask.startedAt && (
                <Descriptions.Item label="Started At" span={3}>{selectedTask.startedAt}</Descriptions.Item>
              )}
              {selectedTask.completedAt && (
                <Descriptions.Item label="Completed At" span={3}>{selectedTask.completedAt}</Descriptions.Item>
              )}
              <Descriptions.Item label="Estimated Duration" span={1}>{selectedTask.estimatedDuration} minutes</Descriptions.Item>
              {selectedTask.actualDuration && (
                <Descriptions.Item label="Actual Duration" span={2}>{selectedTask.actualDuration} minutes</Descriptions.Item>
              )}
              <Descriptions.Item label="Retry Count" span={1}>{selectedTask.retryCount}/{selectedTask.maxRetries}</Descriptions.Item>
              {selectedTask.errorMessage && (
                <Descriptions.Item label="Error Message" span={3}>
                  <Alert message={selectedTask.errorMessage} type="error" showIcon />
                </Descriptions.Item>
              )}
            </Descriptions>

            {selectedTask.aiSuggestion && (
              <div style={{ marginTop: 20 }}>
                <h3>AI Suggestion</h3>
                <Card>
                  {Object.entries(selectedTask.aiSuggestion).map(([key, value]) => (
                    <p key={key}>
                      <strong>{key}:</strong> {typeof value === 'object' ? JSON.stringify(value) : String(value)}
                    </p>
                  ))}
                </Card>
              </div>
            )}

            {selectedTask.executionResult && (
              <div style={{ marginTop: 20 }}>
                <h3>Execution Result</h3>
                <Card>
                  {Object.entries(selectedTask.executionResult).map(([key, value]) => (
                    <p key={key}>
                      <strong>{key}:</strong> {typeof value === 'object' ? JSON.stringify(value) : String(value)}
                    </p>
                  ))}
                </Card>
              </div>
            )}

            <div style={{ marginTop: 20 }}>
              <h3>Task Timeline</h3>
              <Timeline>
                <Timeline.Item>Task created at {selectedTask.createdAt}</Timeline.Item>
                {selectedTask.startedAt && (
                  <Timeline.Item>Task started at {selectedTask.startedAt}</Timeline.Item>
                )}
                {selectedTask.status === 'COMPLETED' && selectedTask.completedAt && (
                  <Timeline.Item color="green">Task completed at {selectedTask.completedAt}</Timeline.Item>
                )}
                {selectedTask.status === 'FAILED' && (
                  <Timeline.Item color="red">Task failed</Timeline.Item>
                )}
              </Timeline>
            </div>
          </div>
        )}
      </Modal>

      <Modal
        title="Create Task"
        open={createModalVisible}
        onCancel={() => setCreateModalVisible(false)}
        onOk={handleCreateSubmit}
      >
        <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="actionType"
            label="Action Type"
            rules={[{ required: true, message: 'Please select action type' }]}
          >
            <Select placeholder="Select action type">
              {Object.keys(ACTION_TYPE_MAP).map((key) => (
                <Option key={key} value={key}>{ACTION_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="maxRetries"
            label="Max Retries"
            rules={[{ required: true, message: 'Please enter max retries' }]}
          >
            <InputNumber min={0} max={10} defaultValue={3} />
          </Form.Item>
          <Form.Item
            name="estimatedDuration"
            label="Estimated Duration (minutes)"
            rules={[{ required: true, message: 'Please enter estimated duration' }]}
          >
            <InputNumber min={1} defaultValue={30} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Edit Task"
        open={editModalVisible}
        onCancel={() => setEditModalVisible(false)}
        onOk={handleEditSubmit}
      >
        <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="actionType"
            label="Action Type"
            rules={[{ required: true, message: 'Please select action type' }]}
          >
            <Select placeholder="Select action type">
              {Object.keys(ACTION_TYPE_MAP).map((key) => (
                <Option key={key} value={key}>{ACTION_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="maxRetries"
            label="Max Retries"
            rules={[{ required: true, message: 'Please enter max retries' }]}
          >
            <InputNumber min={0} max={10} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default AIActionTaskManager;