import {
  useState,
  useEffect,
  Card,
  Table,
  Tag,
  Button,
  Space,
  Modal,
  Descriptions,
  Timeline,
  Badge,
  Tabs,
  Select,
  Input,
  DatePicker,
  message,
  Row,
  Col,
  Statistic,
  Progress,
  Alert,
  Tooltip,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ClockCircleOutlined,
  EyeOutlined,
  ReloadOutlined,
  DownloadOutlined,
  FilterOutlined,
  SearchOutlined,
  CalendarOutlined,
  BarChartOutlined,
  InfoCircleOutlined,
  executionResultDataSource,
  Option,
  RangePicker,
  FC,
} from '@/imports';
import type { ExecutionResult, StatData } from '../services/executionResultDataSource';
import dayjs from 'dayjs';

const ExecutionResults: FC = () => {
  const [results, setResults] = useState<ExecutionResult[]>([]);
  const [selectedResult, setSelectedResult] = useState<ExecutionResult | null>(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [filters, setFilters] = useState({
    status: 'all',
    actionType: 'all',
    dateRange: null as any,
    search: '',
  });
  const [stats, setStats] = useState<StatData>({
    total: 0,
    success: 0,
    failed: 0,
    inProgress: 0,
    successRate: 0,
    avgDuration: 0,
  });

  useEffect(() => {
    fetchResults();
  }, [filters]);

  const fetchResults = async () => {
    setLoading(true);
    try {
      const results = await executionResultDataSource.fetchResults({
        status: filters.status !== 'all' ? filters.status : undefined,
        actionType: filters.actionType !== 'all' ? filters.actionType : undefined,
        startDate: filters.dateRange ? filters.dateRange[0].format('YYYY-MM-DD') : undefined,
        endDate: filters.dateRange ? filters.dateRange[1].format('YYYY-MM-DD') : undefined,
        search: filters.search || undefined,
      });
      setResults(results);
      calculateStats(results);
    } catch (error) {
      message.error('Failed to load execution results');
    } finally {
      setLoading(false);
    }
  };

  const calculateStats = (results: ExecutionResult[]) => {
    const total = results.length;
    const success = results.filter(r => r.status === 'success').length;
    const failed = results.filter(r => r.status === 'failed').length;
    const inProgress = results.filter(r => r.status === 'in_progress').length;
    const successRate = total > 0 ? (success / total) * 100 : 0;
    const completedResults = results.filter(r => r.duration);
    const avgDuration = completedResults.length > 0
      ? completedResults.reduce((sum, r) => sum + (r.duration || 0), 0) / completedResults.length
      : 0;

    setStats({
      total,
      success,
      failed,
      inProgress,
      successRate,
      avgDuration,
    });
  };

  const handleViewDetail = (result: ExecutionResult) => {
    setSelectedResult(result);
    setDetailModalVisible(true);
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'success':
        return <CheckCircleOutlined style={{ color: '#52c41a' }} />;
      case 'failed':
        return <CloseCircleOutlined style={{ color: '#ff4d4f' }} />;
      case 'in_progress':
        return <ClockCircleOutlined style={{ color: '#1890ff' }} />;
      case 'pending':
        return <ClockCircleOutlined style={{ color: '#faad14' }} />;
      default:
        return null;
    }
  };

  const getStatusTag = (status: string) => {
    let color = 'default';
    switch (status) {
      case 'success':
        color = 'success';
        break;
      case 'failed':
        color = 'error';
        break;
      case 'in_progress':
        color = 'processing';
        break;
      case 'pending':
        color = 'warning';
        break;
    }
    return <Tag color={color}>{status}</Tag>;
  };

  const getLogLevelBadge = (level: 'info' | 'warn' | 'error') => {
    let status: 'success' | 'default' | 'error' | 'processing' | 'warning' = 'default';
    switch (level) {
      case 'info':
        status = 'success';
        break;
      case 'warn':
        status = 'warning';
        break;
      case 'error':
        status = 'error';
        break;
    }
    return <Badge status={status} text={level} />;
  };

  const filteredResults = results.filter(result => {
    if (filters.status !== 'all' && result.status !== filters.status) {
      return false;
    }
    if (filters.actionType !== 'all' && result.actionType !== filters.actionType) {
      return false;
    }
    if (filters.search && !(
      result.taskId.includes(filters.search) ||
      result.actionType.includes(filters.search) ||
      result.clientId.includes(filters.search) ||
      result.metadata.platform.includes(filters.search)
    )) {
      return false;
    }
    if (filters.dateRange) {
      const startDate = filters.dateRange[0].startOf('day').valueOf();
      const endDate = filters.dateRange[1].endOf('day').valueOf();
      const resultTime = result.startTime.getTime();
      if (resultTime < startDate || resultTime > endDate) {
        return false;
      }
    }
    return true;
  });

  const columns = [
    {
      title: 'Task ID',
      dataIndex: 'taskId',
      key: 'taskId',
    },
    {
      title: 'Action Type',
      dataIndex: 'actionType',
      key: 'actionType',
      render: (actionType: string) => (
        <Tag>{actionType}</Tag>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Space size="middle">
          {getStatusIcon(status)}
          {getStatusTag(status)}
        </Space>
      ),
    },
    {
      title: 'Start Time',
      dataIndex: 'startTime',
      key: 'startTime',
      render: (startTime: Date) => new Date(startTime).toLocaleString(),
    },
    {
      title: 'Duration',
      dataIndex: 'duration',
      key: 'duration',
      render: (duration: number) => duration ? `${duration}s` : 'N/A',
    },
    {
      title: 'Client',
      dataIndex: 'clientId',
      key: 'clientId',
    },
    {
      title: 'Platform',
      dataIndex: 'metadata',
      key: 'platform',
      render: (metadata: any) => metadata.platform,
    },
    {
      title: 'Result',
      dataIndex: 'result',
      key: 'result',
      render: (result: { message: string }) => (
        <Tooltip title={result.message}>
          <span>{result.message.length > 20 ? result.message.substring(0, 20) + '...' : result.message}</span>
        </Tooltip>
      ),
    },
    {
      title: 'Actions',
      key: 'action',
      render: (_: any, record: ExecutionResult) => (
        <Space size="small">
          <Button type="link" icon={<EyeOutlined />} onClick={() => handleViewDetail(record)}>
            View
          </Button>
          <Button type="link" icon={<DownloadOutlined />}>
            Export
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="execution-results">
      <Card
        title={
          <Space size="middle">
            <BarChartOutlined style={{ color: '#1890ff' }} />
            <span>Execution Results</span>
          </Space>
        }
        extra={
          <Button icon={<ReloadOutlined />} onClick={fetchResults} loading={loading}>
            Refresh
          </Button>
        }
      >
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={6}>
            <Card size="small">
              <Statistic
                title="Total Executions"
                value={stats.total}
                prefix={<InfoCircleOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <Statistic
                title="Success Rate"
                value={stats.successRate.toFixed(1)}
                suffix="%"
                prefix={<CheckCircleOutlined style={{ color: '#52c41a' }} />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <Statistic
                title="Avg. Duration"
                value={stats.avgDuration.toFixed(1)}
                suffix="s"
                prefix={<ClockCircleOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <Space direction="vertical" style={{ width: '100%' }}>
                <div>Success: <Tag color="success">{stats.success}</Tag></div>
                <div>Failed: <Tag color="error">{stats.failed}</Tag></div>
                <div>In Progress: <Tag color="processing">{stats.inProgress}</Tag></div>
              </Space>
            </Card>
          </Col>
        </Row>

        <Card size="small" style={{ marginBottom: 16 }}>
          <Row gutter={16}>
            <Col span={6}>
              <Select
                placeholder="Filter by status"
                style={{ width: '100%' }}
                value={filters.status}
                onChange={(value) => setFilters({ ...filters, status: value })}
              >
                <Option value="all">All Statuses</Option>
                <Option value="success">Success</Option>
                <Option value="failed">Failed</Option>
                <Option value="in_progress">In Progress</Option>
                <Option value="pending">Pending</Option>
              </Select>
            </Col>
            <Col span={6}>
              <Select
                placeholder="Filter by action type"
                style={{ width: '100%' }}
                value={filters.actionType}
                onChange={(value) => setFilters({ ...filters, actionType: value })}
              >
                <Option value="all">All Action Types</Option>
                <Option value="price_update">Price Update</Option>
                <Option value="inventory_sync">Inventory Sync</Option>
                <Option value="order_processing">Order Processing</Option>
              </Select>
            </Col>
            <Col span={6}>
              <RangePicker
                style={{ width: '100%' }}
                onChange={(dates) => setFilters({ ...filters, dateRange: dates })}
                placeholder={['Start Date', 'End Date']}
              />
            </Col>
            <Col span={6}>
              <Input
                placeholder="Search (task ID, action type, client, platform)"
                prefix={<SearchOutlined />}
                value={filters.search}
                onChange={(e) => setFilters({ ...filters, search: e.target.value })}
              />
            </Col>
          </Row>
        </Card>

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

      <Modal
        title="Execution Detail"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            Close
          </Button>,
        ]}
        width={800}
      >
        {selectedResult && (
          <>
            <Descriptions column={2} bordered>
              <Descriptions.Item label="Task ID">{selectedResult.taskId}</Descriptions.Item>
              <Descriptions.Item label="Action Type">{selectedResult.actionType}</Descriptions.Item>
              <Descriptions.Item label="Status">
                <Space size="middle">
                  {getStatusIcon(selectedResult.status)}
                  {getStatusTag(selectedResult.status)}
                </Space>
              </Descriptions.Item>
              <Descriptions.Item label="Client">{selectedResult.clientId}</Descriptions.Item>
              <Descriptions.Item label="Start Time">{new Date(selectedResult.startTime).toLocaleString()}</Descriptions.Item>
              <Descriptions.Item label="End Time">
                {selectedResult.endTime ? new Date(selectedResult.endTime).toLocaleString() : 'N/A'}
              </Descriptions.Item>
              <Descriptions.Item label="Duration">
                {selectedResult.duration ? `${selectedResult.duration} seconds` : 'N/A'}
              </Descriptions.Item>
              <Descriptions.Item label="Platform">{selectedResult.metadata.platform}</Descriptions.Item>
              <Descriptions.Item label="User ID">{selectedResult.metadata.userId}</Descriptions.Item>
              <Descriptions.Item label="Attempt">{selectedResult.metadata.attempt}</Descriptions.Item>
              <Descriptions.Item label="Correlation ID" span={2}>
                {selectedResult.metadata.correlationId}
              </Descriptions.Item>
            </Descriptions>

            <Card title="Execution Result" style={{ marginTop: 16 }}>
              <Alert
                message={selectedResult.result.success ? 'Success' : 'Failed'}
                description={selectedResult.result.message}
                type={selectedResult.result.success ? 'success' : 'error'}
                showIcon
              />
              {selectedResult.result.error && (
                <Alert
                  message="Error Details"
                  description={selectedResult.result.error}
                  type="error"
                  style={{ marginTop: 16 }}
                />
              )}
              {selectedResult.result.data && (
                <Card size="small" title="Result Data" style={{ marginTop: 16 }}>
                  <pre style={{ whiteSpace: 'pre-wrap' }}>
                    {JSON.stringify(selectedResult.result.data, null, 2)}
                  </pre>
                </Card>
              )}
            </Card>

            <Card title="Execution Logs" style={{ marginTop: 16 }}>
              <Timeline>
                {selectedResult.logs.map((log, index) => (
                  <Timeline.Item key={index} color={log.level === 'error' ? 'red' : log.level === 'warn' ? 'orange' : 'blue'}>
                    <div>
                      <Space size="middle">
                        {getLogLevelBadge(log.level)}
                        <span>{new Date(log.timestamp).toLocaleString()}</span>
                      </Space>
                      <p style={{ marginTop: 8 }}>{log.message}</p>
                    </div>
                  </Timeline.Item>
                ))}
              </Timeline>
            </Card>
          </>
        )}
      </Modal>
    </div>
  );
};

export default ExecutionResults;
