import React, { useState, useEffect } from 'react';
import {
  Card,
  Tabs,
  Table,
  Tag,
  Statistic,
  Row,
  Col,
  Spin,
  message,
  Button,
  Modal,
  Form,
  Switch,
  InputNumber,
  Select,
  Timeline,
  Badge,
  Typography,
  Space,
  Divider,
  Alert,
  Tooltip,
  Progress
} from 'antd';
import {
  RobotOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  StopOutlined,
  WarningOutlined,
  SettingOutlined,
  HistoryOutlined,
  DashboardOutlined,
  ThunderboltOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  SyncOutlined,
  ClockCircleOutlined,
  DollarOutlined,
  ShoppingCartOutlined,
  ToolOutlined,
  PlusOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { TabPane } = Tabs;
const { Option } = Select;
const { Title, Text, Paragraph } = Typography;

interface AutopilotSession {
  id: string;
  tenant_id: string;
  shop_id: string;
  status: 'IDLE' | 'RUNNING' | 'PAUSED' | 'STOPPED' | 'ERROR';
  mode: 'FULL_AUTO' | 'SEMI_AUTO' | 'MANUAL';
  config: any;
  enabled_features: string[];
  total_revenue: number;
  total_orders: number;
  total_profit: number;
  tasks_completed: number;
  tasks_failed: number;
  started_at: string | null;
  stopped_at: string | null;
  last_activity_at: string | null;
  error_message: string | null;
  created_at: string;
}

interface AutopilotLog {
  id: string;
  session_id: string;
  log_type: 'TASK' | 'DECISION' | 'ERROR' | 'WARNING' | 'INFO';
  task_type: string | null;
  task_status: 'PENDING' | 'RUNNING' | 'COMPLETED' | 'FAILED';
  description: string;
  input_data: any;
  output_data: any;
  error_details: any;
  duration_ms: number;
  is_auto_executed: boolean;
  trace_id: string | null;
  created_at: string;
}

interface AutopilotConfig {
  features: {
    pricing: boolean;
    inventory: boolean;
    advertising: boolean;
    orderFulfillment: boolean;
    customerService: boolean;
  };
  thresholds: {
    minProfitMargin: number;
    maxInventoryDays: number;
    minAdRoi: number;
  };
  notifications: {
    email: boolean;
    sms: boolean;
    webhook: string | null;
  };
}

const statusColors: Record<string, string> = {
  IDLE: 'default',
  RUNNING: 'processing',
  PAUSED: 'warning',
  STOPPED: 'default',
  ERROR: 'error'
};

const statusIcons: Record<string, React.ReactNode> = {
  IDLE: <ClockCircleOutlined />,
  RUNNING: <SyncOutlined spin />,
  PAUSED: <PauseCircleOutlined />,
  STOPPED: <StopOutlined />,
  ERROR: <WarningOutlined />
};

const modeColors: Record<string, string> = {
  FULL_AUTO: 'red',
  SEMI_AUTO: 'orange',
  MANUAL: 'blue'
};

const logTypeColors: Record<string, string> = {
  TASK: 'blue',
  DECISION: 'purple',
  ERROR: 'red',
  WARNING: 'orange',
  INFO: 'default'
};

const taskStatusColors: Record<string, string> = {
  PENDING: 'default',
  RUNNING: 'processing',
  COMPLETED: 'success',
  FAILED: 'error'
};

const AutoPilotPage: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [sessions, setSessions] = useState<AutopilotSession[]>([]);
  const [selectedSession, setSelectedSession] = useState<AutopilotSession | null>(null);
  const [logs, setLogs] = useState<AutopilotLog[]>([]);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [configModalVisible, setConfigModalVisible] = useState(false);
  const [emergencyStopModalVisible, setEmergencyStopModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [configForm] = Form.useForm();

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

  useEffect(() => {
    if (selectedSession) {
      fetchSessionLogs(selectedSession.id);
      const interval = setInterval(() => {
        fetchSessionLogs(selectedSession.id);
      }, 10000);
      return () => clearInterval(interval);
    }
  }, [selectedSession]);

  const fetchSessions = async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/v1/autopilot/sessions');
      const data = await res.json();
      if (data.success) {
        setSessions(data.data);
        if (data.data.length > 0 && !selectedSession) {
          setSelectedSession(data.data[0]);
        }
      }
    } catch (error) {
      message.error('Failed to fetch sessions');
    } finally {
      setLoading(false);
    }
  };

  const fetchSessionLogs = async (sessionId: string) => {
    try {
      const res = await fetch(`/api/v1/autopilot/sessions/${sessionId}/logs?limit=100`);
      const data = await res.json();
      if (data.success) {
        setLogs(data.data);
      }
    } catch (error) {
      console.error('Failed to fetch logs:', error);
    }
  };

  const handleCreateSession = async (values: any) => {
    try {
      const res = await fetch('/api/v1/autopilot/sessions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(values)
      });
      const data = await res.json();

      if (data.success) {
        message.success('Session created successfully');
        setCreateModalVisible(false);
        form.resetFields();
        fetchSessions();
      } else {
        message.error(data.message || 'Failed to create session');
      }
    } catch (error) {
      message.error('Failed to create session');
    }
  };

  const handleStartSession = async (sessionId: string) => {
    try {
      const res = await fetch(`/api/v1/autopilot/sessions/${sessionId}/start`, {
        method: 'POST'
      });
      const data = await res.json();

      if (data.success) {
        message.success('Session started successfully');
        fetchSessions();
      } else {
        message.error(data.message || 'Failed to start session');
      }
    } catch (error) {
      message.error('Failed to start session');
    }
  };

  const handlePauseSession = async (sessionId: string) => {
    try {
      const res = await fetch(`/api/v1/autopilot/sessions/${sessionId}/pause`, {
        method: 'POST'
      });
      const data = await res.json();

      if (data.success) {
        message.success('Session paused');
        fetchSessions();
      } else {
        message.error(data.message || 'Failed to pause session');
      }
    } catch (error) {
      message.error('Failed to pause session');
    }
  };

  const handleResumeSession = async (sessionId: string) => {
    try {
      const res = await fetch(`/api/v1/autopilot/sessions/${sessionId}/resume`, {
        method: 'POST'
      });
      const data = await res.json();

      if (data.success) {
        message.success('Session resumed');
        fetchSessions();
      } else {
        message.error(data.message || 'Failed to resume session');
      }
    } catch (error) {
      message.error('Failed to resume session');
    }
  };

  const handleStopSession = async (sessionId: string, reason?: string) => {
    try {
      const res = await fetch(`/api/v1/autopilot/sessions/${sessionId}/stop`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ reason })
      });
      const data = await res.json();

      if (data.success) {
        message.success('Session stopped');
        fetchSessions();
      } else {
        message.error(data.message || 'Failed to stop session');
      }
    } catch (error) {
      message.error('Failed to stop session');
    }
  };

  const handleEmergencyStop = async (sessionId: string, reason: string) => {
    try {
      const res = await fetch(`/api/v1/autopilot/sessions/${sessionId}/emergency-stop`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ reason })
      });
      const data = await res.json();

      if (data.success) {
        message.warning('Emergency stop executed!');
        setEmergencyStopModalVisible(false);
        fetchSessions();
      } else {
        message.error(data.message || 'Failed to execute emergency stop');
      }
    } catch (error) {
      message.error('Failed to execute emergency stop');
    }
  };

  const handleUpdateConfig = async (sessionId: string, config: Partial<AutopilotConfig>) => {
    try {
      const res = await fetch(`/api/v1/autopilot/sessions/${sessionId}/config`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(config)
      });
      const data = await res.json();

      if (data.success) {
        message.success('Config updated');
        setConfigModalVisible(false);
        fetchSessions();
      } else {
        message.error(data.message || 'Failed to update config');
      }
    } catch (error) {
      message.error('Failed to update config');
    }
  };

  const renderSessionCard = (session: AutopilotSession) => (
    <Card
      hoverable
      style={{ marginBottom: 16 }}
      onClick={() => setSelectedSession(session)}
      className={selectedSession?.id === session.id ? 'ant-card-bordered' : ''}
    >
      <Row gutter={16} align="middle">
        <Col flex="auto">
          <Space direction="vertical" size="small" style={{ width: '100%' }}>
            <Space>
              <Text strong style={{ fontSize: 16 }}>
                <RobotOutlined /> Session {session.id.slice(0, 8)}
              </Text>
              <Tag color={statusColors[session.status]} icon={statusIcons[session.status]}>
                {session.status}
              </Tag>
              <Tag color={modeColors[session.mode]}>{session.mode}</Tag>
            </Space>
            <Space>
              <Text type="secondary">Shop: {session.shop_id}</Text>
              <Divider type="vertical" />
              <Text type="secondary">
                Started: {session.started_at ? new Date(session.started_at).toLocaleString() : 'Not started'}
              </Text>
            </Space>
            <Row gutter={16}>
              <Col>
                <Statistic
                  title="Revenue"
                  value={session.total_revenue}
                  prefix="$"
                  valueStyle={{ fontSize: 14 }}
                />
              </Col>
              <Col>
                <Statistic
                  title="Orders"
                  value={session.total_orders}
                  valueStyle={{ fontSize: 14 }}
                />
              </Col>
              <Col>
                <Statistic
                  title="Profit"
                  value={session.total_profit}
                  prefix="$"
                  valueStyle={{ fontSize: 14, color: session.total_profit >= 0 ? '#52c41a' : '#ff4d4f' }}
                />
              </Col>
              <Col>
                <Statistic
                  title="Tasks"
                  value={session.tasks_completed}
                  suffix={`/ ${session.tasks_completed + session.tasks_failed}`}
                  valueStyle={{ fontSize: 14 }}
                />
              </Col>
            </Row>
          </Space>
        </Col>
        <Col>
          <Space direction="vertical">
            {session.status === 'IDLE' && (
              <Button type="primary" icon={<PlayCircleOutlined />} onClick={(e) => { e.stopPropagation(); handleStartSession(session.id); }}>
                Start
              </Button>
            )}
            {session.status === 'RUNNING' && (
              <>
                <Button icon={<PauseCircleOutlined />} onClick={(e) => { e.stopPropagation(); handlePauseSession(session.id); }}>
                  Pause
                </Button>
                <Button danger icon={<StopOutlined />} onClick={(e) => { e.stopPropagation(); handleStopSession(session.id); }}>
                  Stop
                </Button>
              </>
            )}
            {session.status === 'PAUSED' && (
              <>
                <Button type="primary" icon={<PlayCircleOutlined />} onClick={(e) => { e.stopPropagation(); handleResumeSession(session.id); }}>
                  Resume
                </Button>
                <Button danger icon={<StopOutlined />} onClick={(e) => { e.stopPropagation(); handleStopSession(session.id); }}>
                  Stop
                </Button>
              </>
            )}
          </Space>
        </Col>
      </Row>
      {session.error_message && (
        <Alert type="error" message={session.error_message} style={{ marginTop: 12 }} />
      )}
    </Card>
  );

  const logsColumns: ColumnsType<AutopilotLog> = [
    {
      title: 'Time',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 150,
      render: (date: string) => new Date(date).toLocaleTimeString()
    },
    {
      title: 'Type',
      dataIndex: 'log_type',
      key: 'log_type',
      width: 100,
      render: (type: string) => <Tag color={logTypeColors[type]}>{type}</Tag>
    },
    {
      title: 'Task',
      dataIndex: 'task_type',
      key: 'task_type',
      width: 150,
      render: (task: string | null) => task || '-'
    },
    {
      title: 'Status',
      dataIndex: 'task_status',
      key: 'task_status',
      width: 100,
      render: (status: string) => (
        <Tag color={taskStatusColors[status]} icon={
          status === 'COMPLETED' ? <CheckCircleOutlined /> :
          status === 'FAILED' ? <CloseCircleOutlined /> :
          status === 'RUNNING' ? <SyncOutlined spin /> : null
        }>
          {status}
        </Tag>
      )
    },
    {
      title: 'Description',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true
    },
    {
      title: 'Duration',
      dataIndex: 'duration_ms',
      key: 'duration_ms',
      width: 100,
      render: (ms: number) => ms ? `${ms}ms` : '-'
    },
    {
      title: 'Auto',
      dataIndex: 'is_auto_executed',
      key: 'is_auto_executed',
      width: 80,
      render: (auto: boolean) => auto ? <Badge status="processing" text="Auto" /> : <Badge status="default" text="Manual" />
    }
  ];

  const renderConfigForm = () => (
    <Form form={configForm} layout="vertical" initialValues={selectedSession?.config}>
      <Title level={5}>Enabled Features</Title>
      <Row gutter={16}>
        <Col span={12}>
          <Form.Item name={['features', 'pricing']} label="Auto Pricing" valuePropName="checked">
            <Switch />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item name={['features', 'inventory']} label="Inventory Management" valuePropName="checked">
            <Switch />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item name={['features', 'advertising']} label="Ad Optimization" valuePropName="checked">
            <Switch />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item name={['features', 'orderFulfillment']} label="Order Fulfillment" valuePropName="checked">
            <Switch />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item name={['features', 'customerService']} label="Customer Service" valuePropName="checked">
            <Switch />
          </Form.Item>
        </Col>
      </Row>

      <Divider />

      <Title level={5}>Thresholds</Title>
      <Row gutter={16}>
        <Col span={8}>
          <Form.Item name={['thresholds', 'minProfitMargin']} label="Min Profit Margin (%)">
            <InputNumber min={0} max={100} style={{ width: '100%' }} />
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item name={['thresholds', 'maxInventoryDays']} label="Max Inventory Days">
            <InputNumber min={1} style={{ width: '100%' }} />
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item name={['thresholds', 'minAdRoi']} label="Min Ad ROI (%)">
            <InputNumber min={0} style={{ width: '100%' }} />
          </Form.Item>
        </Col>
      </Row>

      <Divider />

      <Title level={5}>Notifications</Title>
      <Row gutter={16}>
        <Col span={12}>
          <Form.Item name={['notifications', 'email']} label="Email Notifications" valuePropName="checked">
            <Switch />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item name={['notifications', 'sms']} label="SMS Notifications" valuePropName="checked">
            <Switch />
          </Form.Item>
        </Col>
      </Row>
    </Form>
  );

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '100px 0' }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div style={{ padding: 24 }}>
      <Row gutter={[16, 16]}>
        <Col span={24}>
          <Card>
            <Row gutter={16} align="middle">
              <Col flex="auto">
                <Title level={3} style={{ margin: 0 }}>
                  <RobotOutlined /> AI AutoPilot
                </Title>
                <Text type="secondary">
                  Automate your store operations with AI-powered decision making
                </Text>
              </Col>
              <Col>
                <Space>
                  <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={() => setCreateModalVisible(true)}
                  >
                    New Session
                  </Button>
                  {selectedSession && (
                    <Button
                      icon={<SettingOutlined />}
                      onClick={() => {
                        configForm.setFieldsValue(selectedSession.config);
                        setConfigModalVisible(true);
                      }}
                    >
                      Configure
                    </Button>
                  )}
                  {selectedSession && selectedSession.status === 'RUNNING' && (
                    <Button
                      danger
                      icon={<WarningOutlined />}
                      onClick={() => setEmergencyStopModalVisible(true)}
                    >
                      Emergency Stop
                    </Button>
                  )}
                </Space>
              </Col>
            </Row>
          </Card>
        </Col>

        <Col span={24}>
          <Tabs defaultActiveKey="sessions">
            <TabPane tab={<span><DashboardOutlined /> Sessions</span>} key="sessions">
              {sessions.length === 0 ? (
                <Card>
                  <div style={{ textAlign: 'center', padding: '40px 0' }}>
                    <RobotOutlined style={{ fontSize: 48, color: '#d9d9d9' }} />
                    <Paragraph type="secondary" style={{ marginTop: 16 }}>
                      No autopilot sessions yet. Create one to start automating your store.
                    </Paragraph>
                    <Button type="primary" onClick={() => setCreateModalVisible(true)}>
                      Create First Session
                    </Button>
                  </div>
                </Card>
              ) : (
                sessions.map(session => renderSessionCard(session))
              )}
            </TabPane>

            <TabPane tab={<span><HistoryOutlined /> Activity Log</span>} key="logs" disabled={!selectedSession}>
              {selectedSession && (
                <Card title={`Session ${selectedSession.id.slice(0, 8)} - Activity Log`}>
                  <Table
                    columns={logsColumns}
                    dataSource={logs}
                    rowKey="id"
                    pagination={{ pageSize: 20 }}
                    size="small"
                  />
                </Card>
              )}
            </TabPane>

            <TabPane tab={<span><ThunderboltOutlined /> Features</span>} key="features" disabled={!selectedSession}>
              {selectedSession && (
                <Card>
                  <Row gutter={[16, 16]}>
                    {selectedSession.enabled_features.map(feature => (
                      <Col span={8} key={feature}>
                        <Card size="small">
                          <Statistic
                            title={feature.replace(/([A-Z])/g, ' $1').trim()}
                            value="Active"
                            valueStyle={{ color: '#52c41a', fontSize: 14 }}
                            prefix={<CheckCircleOutlined />}
                          />
                        </Card>
                      </Col>
                    ))}
                  </Row>
                </Card>
              )}
            </TabPane>
          </Tabs>
        </Col>
      </Row>

      <Modal
        title="Create New Autopilot Session"
        open={createModalVisible}
        onCancel={() => setCreateModalVisible(false)}
        onOk={() => form.submit()}
        width={600}
      >
        <Form form={form} layout="vertical" onFinish={handleCreateSession}>
          <Form.Item name="shopId" label="Shop ID" rules={[{ required: true }]}>
            <Select placeholder="Select a shop">
              <Option value="shop-1">Shop 1</Option>
              <Option value="shop-2">Shop 2</Option>
            </Select>
          </Form.Item>
          <Form.Item name="mode" label="Automation Mode" rules={[{ required: true }]}>
            <Select placeholder="Select mode">
              <Option value="FULL_AUTO">
                <Tag color="red">Full Auto</Tag> - AI makes all decisions
              </Option>
              <Option value="SEMI_AUTO">
                <Tag color="orange">Semi Auto</Tag> - AI suggests, you approve
              </Option>
              <Option value="MANUAL">
                <Tag color="blue">Manual</Tag> - AI only monitors
              </Option>
            </Select>
          </Form.Item>
          <Alert
            message="Warning"
            description="Full Auto mode allows AI to make decisions without human approval. Use with caution."
            type="warning"
            showIcon
            style={{ marginBottom: 16 }}
          />
        </Form>
      </Modal>

      <Modal
        title="Session Configuration"
        open={configModalVisible}
        onCancel={() => setConfigModalVisible(false)}
        onOk={() => handleUpdateConfig(selectedSession?.id || '', configForm.getFieldsValue())}
        width={700}
      >
        {renderConfigForm()}
      </Modal>

      <Modal
        title={<span style={{ color: '#ff4d4f' }}><WarningOutlined /> Emergency Stop</span>}
        open={emergencyStopModalVisible}
        onCancel={() => setEmergencyStopModalVisible(false)}
        onOk={() => {
          const reason = 'User initiated emergency stop';
          handleEmergencyStop(selectedSession?.id || '', reason);
        }}
        okText="Confirm Emergency Stop"
        okButtonProps={{ danger: true }}
      >
        <Alert
          message="Warning"
          description="Emergency stop will immediately halt all automated operations. This action cannot be undone."
          type="error"
          showIcon
        />
        <Paragraph style={{ marginTop: 16 }}>
          Are you sure you want to execute an emergency stop for session {selectedSession?.id.slice(0, 8)}?
        </Paragraph>
      </Modal>
    </div>
  );
};

export default AutoPilotPage;
