import {
  useState,
  useEffect,
  Card,
  Table,
  Tag,
  Button,
  Space,
  Modal,
  message,
  Row,
  Col,
  Input,
  Select,
  Badge,
  Tabs,
  CheckCircleOutlined,
  CloseCircleOutlined,
  EyeOutlined,
  ClockCircleOutlined,
  SearchOutlined,
  FilterOutlined,
  ReloadOutlined,
  humanApprovalDataSource,
  Option,
  FC,
} from '@/imports';
import type { Task } from '../services/humanApprovalDataSource';
import HumanApprovalForm from '../components/human-approval/HumanApprovalForm';
import AISuggestionDisplay from '../components/ai-suggestion/AISuggestionDisplay';

const ACTION_TYPE_MAP: Record<string, { color: string; text: string }> = {
  PRICING_OPTIMIZATION: { color: 'blue', text: 'Pricing Optimization' },
  ORDER_PROCESSING: { color: 'green', text: 'Order Processing' },
  INVENTORY_MANAGEMENT: { color: 'purple', text: 'Inventory Management' },
  MARKETING_CAMPAIGN: { color: 'orange', text: 'Marketing Campaign' },
  PRODUCT_OPTIMIZATION: { color: 'cyan', text: 'Product Optimization' },
  CUSTOM: { color: 'default', text: 'Custom Action' },
};

const TASK_STATUS_MAP: Record<string, { color: string; text: string }> = {
  PENDING: { color: 'default', text: 'Pending' },
  AI_ANALYZING: { color: 'processing', text: 'AI Analyzing' },
  PENDING_REVIEW: { color: 'warning', text: 'Pending Review' },
  APPROVED: { color: 'success', text: 'Approved' },
  REJECTED: { color: 'error', text: 'Rejected' },
  AI_EXECUTING: { color: 'processing', text: 'AI Executing' },
  COMPLETED: { color: 'success', text: 'Completed' },
  FAILED: { color: 'error', text: 'Failed' },
};

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 HumanApprovalPage: FC = () => {
  const [tasks, setTasks] = useState<Task[]>([]);
  const [selectedTask, setSelectedTask] = useState<Task | null>(null);
  const [approvalModalVisible, setApprovalModalVisible] = useState(false);
  const [suggestionModalVisible, setSuggestionModalVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [filterType, setFilterType] = useState<string>('');
  const [filterPriority, setFilterPriority] = useState<string>('');
  const [activeTab, setActiveTab] = useState('pending');

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

  const fetchTasks = async () => {
    setLoading(true);
    try {
      const tasks = await humanApprovalDataSource.fetchTasks({
        status: activeTab === 'pending' ? 'PENDING_REVIEW' : 
                activeTab === 'approved' ? 'APPROVED' : 
                activeTab === 'rejected' ? 'REJECTED' : undefined,
        actionType: filterType || undefined,
        priority: filterPriority || undefined,
        search: searchText || undefined,
      });
      setTasks(tasks);
    } catch (error) {
      message.error('Failed to load tasks');
    } finally {
      setLoading(false);
    }
  };

  const handleApprove = async (formData: any) => {
    setLoading(true);
    try {
      if (selectedTask) {
        await humanApprovalDataSource.approveTask(selectedTask.id, formData);
        message.success('Task approved successfully');
        setApprovalModalVisible(false);
        fetchTasks();
      }
    } catch (error) {
      message.error('Failed to approve task');
    } finally {
      setLoading(false);
    }
  };

  const handleReject = async (reason: string) => {
    setLoading(true);
    try {
      if (selectedTask) {
        await humanApprovalDataSource.rejectTask(selectedTask.id, reason);
        message.success('Task rejected successfully');
        setApprovalModalVisible(false);
        fetchTasks();
      }
    } catch (error) {
      message.error('Failed to reject task');
    } finally {
      setLoading(false);
    }
  };

  const handleModify = async (modifiedData: any) => {
    setLoading(true);
    try {
      if (selectedTask) {
        await humanApprovalDataSource.modifyTask(selectedTask.id, modifiedData);
        message.success('Task modified and approved successfully');
        setApprovalModalVisible(false);
        fetchTasks();
      }
    } catch (error) {
      message.error('Failed to modify task');
    } finally {
      setLoading(false);
    }
  };

  const handleViewSuggestion = (task: Task) => {
    setSelectedTask(task);
    setSuggestionModalVisible(true);
  };

  const handleApproveTask = (task: Task) => {
    setSelectedTask(task);
    setApprovalModalVisible(true);
  };

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

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

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

    if (activeTab === 'pending') {
      filtered = filtered.filter((t) => t.status === 'PENDING_REVIEW');
    } else if (activeTab === 'approved') {
      filtered = filtered.filter((t) => t.status === 'APPROVED');
    } else if (activeTab === 'rejected') {
      filtered = filtered.filter((t) => t.status === 'REJECTED');
    }

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

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

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

    return filtered;
  };

  const columns = [
    {
      title: 'Task ID',
      dataIndex: 'taskId',
      key: 'taskId',
      width: 140,
    },
    {
      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 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 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: 'Shop',
      dataIndex: 'shopName',
      key: 'shopName',
      width: 150,
    },
    {
      title: 'Created',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 160,
    },
    {
      title: 'Actions',
      key: 'action',
      width: 200,
      render: (_: any, record: any) => (
        <Space size="small">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleViewSuggestion(record)}
          >
            View Suggestion
          </Button>
          {record.status === 'PENDING_REVIEW' && (
            <Button
              type="primary"
              icon={<CheckCircleOutlined />}
              onClick={() => handleApproveTask(record)}
            >
              Approve
            </Button>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div className="human-approval-page">
      <Card
        title={
          <Space size="middle">
            <ClockCircleOutlined style={{ color: '#1890ff' }} />
            <span>Human Approval Center</span>
          </Space>
        }
        extra={
          <Button icon={<ReloadOutlined />} onClick={fetchTasks}>
            Refresh
          </Button>
        }
      >
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <Tabs.TabPane tab="Pending Review" key="pending" />
          <Tabs.TabPane tab="Approved" key="approved" />
          <Tabs.TabPane tab="Rejected" key="rejected" />
        </Tabs>

        <Card size="small" style={{ marginBottom: 16, marginTop: 16 }}>
          <Row gutter={16}>
            <Col span={8}>
              <Input
                placeholder="Search tasks"
                prefix={<SearchOutlined />}
                value={searchText}
                onChange={(e) => handleSearch(e.target.value)}
                allowClear
              />
            </Col>
            <Col span={6}>
              <Select
                placeholder="Filter by type"
                value={filterType}
                onChange={(value) => handleFilter('type', value)}
                allowClear
                style={{ width: '100%' }}
              >
                {Object.keys(ACTION_TYPE_MAP).map((key) => (
                  <Option key={key} value={key}>
                    {ACTION_TYPE_MAP[key].text}
                  </Option>
                ))}
              </Select>
            </Col>
            <Col span={6}>
              <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="AI Suggestion Details"
        open={suggestionModalVisible}
        onCancel={() => setSuggestionModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setSuggestionModalVisible(false)}>
            Close
          </Button>,
        ]}
        width={800}
      >
        {selectedTask?.aiSuggestion && (
          <AISuggestionDisplay
            suggestion={{
              id: selectedTask.id,
              type: selectedTask.actionType,
              title: selectedTask.aiSuggestion.title,
              description: selectedTask.aiSuggestion.description,
              confidence: 85,
              priority: selectedTask.priority.toLowerCase() as 'low' | 'medium' | 'high' | 'urgent',
              dataSources: ['AI Model', 'Historical Data', 'Market Trends'],
              reasoning: [
                'Based on historical sales data',
                'Analyzed competitor pricing',
                'Considered market trends',
                'Evaluated profit margins',
              ],
              expectedImpact: {
                metric: 'Sales Volume',
                value: 15,
                unit: '%',
                direction: 'positive',
              },
              createdAt: selectedTask.createdAt,
              updatedAt: selectedTask.createdAt,
            }}
            showActions={false}
          />
        )}
      </Modal>

      <Modal
        title="Approve Task"
        open={approvalModalVisible}
        onCancel={() => setApprovalModalVisible(false)}
        footer={null}
        width={800}
      >
        {selectedTask?.aiSuggestion && (
          <HumanApprovalForm
            taskId={selectedTask.taskId}
            aiSuggestion={selectedTask.aiSuggestion}
            onApprove={handleApprove}
            onReject={handleReject}
            onModify={handleModify}
            loading={loading}
          />
        )}
      </Modal>
    </div>
  );
};

export default HumanApprovalPage;
