import {
  useState,
  Card,
  Space,
  Tag,
  Button,
  Divider,
  Descriptions,
  List,
  Collapse,
  Tooltip,
  Progress,
  Badge,
  Alert,
  Statistic,
  Row,
  Col,
  Table,
  Popover,
  RobotOutlined,
  FileTextOutlined,
  BarChartOutlined,
  LineChartOutlined,
  PieChartOutlined,
  InfoCircleOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  QuestionCircleOutlined,
  Panel,
  FC,
} from '@/imports';

interface AISuggestion {
  id: string;
  type: string;
  title: string;
  description: string;
  confidence: number;
  priority: 'low' | 'medium' | 'high' | 'urgent';
  dataSources: string[];
  reasoning: string[];
  expectedImpact: {
    metric: string;
    value: number;
    unit: string;
    direction: 'positive' | 'negative' | 'neutral';
  };
  alternatives?: {
    id: string;
    title: string;
    description: string;
    confidence: number;
    expectedImpact: {
      metric: string;
      value: number;
      unit: string;
      direction: 'positive' | 'negative' | 'neutral';
    };
  }[];
  supportingData?: {
    id: string;
    title: string;
    type: 'chart' | 'table' | 'text';
    data: any;
  }[];
  createdAt: string;
  updatedAt: string;
}

interface AISuggestionDisplayProps {
  suggestion: AISuggestion;
  onApprove?: () => void;
  onReject?: () => void;
  onModify?: () => void;
  showActions?: boolean;
}

const PRIORITY_CONFIG: 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 IMPACT_DIRECTION_CONFIG: Record<string, { icon: React.ReactNode; color: string }> = {
  positive: { icon: <ArrowUpOutlined />, color: 'green' },
  negative: { icon: <ArrowDownOutlined />, color: 'red' },
  neutral: { icon: <InfoCircleOutlined />, color: 'default' },
};

const AISuggestionDisplay: FC<AISuggestionDisplayProps> = ({
  suggestion,
  onApprove,
  onReject,
  onModify,
  showActions = true,
}) => {
  const [activeKey, setActiveKey] = useState<string>('reasoning');

  const handleCollapseChange = (key: string | string[]) => {
    setActiveKey(Array.isArray(key) ? key[0] : key);
  };

  const renderSupportingData = (data: any, type: string) => {
    switch (type) {
      case 'chart':
        return (
          <div style={{ height: 300, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <div style={{ textAlign: 'center' }}>
              <BarChartOutlined style={{ fontSize: 48, color: '#1890ff' }} />
              <p>Chart visualization would appear here</p>
            </div>
          </div>
        );
      case 'table':
        return (
          <Table
            dataSource={data}
            columns={[
              { title: 'Metric', dataIndex: 'metric', key: 'metric' },
              { title: 'Value', dataIndex: 'value', key: 'value' },
              { title: 'Unit', dataIndex: 'unit', key: 'unit' },
            ]}
            pagination={false}
            size="small"
          />
        );
      case 'text':
        return <div>{data}</div>;
      default:
        return null;
    }
  };

  return (
    <Card
      title={
        <Space size="middle">
          <RobotOutlined style={{ color: '#1890ff' }} />
          <span>AI Suggestion: {suggestion.title}</span>
          <Badge
            status="processing"
            text={`Confidence: ${suggestion.confidence}%`}
            style={{ marginLeft: 'auto' }}
          />
        </Space>
      }
      extra={
        <Tag color={PRIORITY_CONFIG[suggestion.priority].color}>
          {PRIORITY_CONFIG[suggestion.priority].text} Priority
        </Tag>
      }
    >
      <Descriptions column={2} bordered>
        <Descriptions.Item label="Suggestion Type">{suggestion.type}</Descriptions.Item>
        <Descriptions.Item label="Created At">{suggestion.createdAt}</Descriptions.Item>
        <Descriptions.Item label="Updated At">{suggestion.updatedAt}</Descriptions.Item>
        <Descriptions.Item label="Data Sources">
          <Space wrap>
            {suggestion.dataSources.map((source) => (
              <Tag key={source}>{source}</Tag>
            ))}
          </Space>
        </Descriptions.Item>
      </Descriptions>

      <Divider orientation="left">Description</Divider>
      <p>{suggestion.description}</p>

      <Divider orientation="left">Expected Impact</Divider>
      <Row gutter={16}>
        <Col span={8}>
          <Card size="small">
            <Statistic
              title={suggestion.expectedImpact.metric}
              value={suggestion.expectedImpact.value}
              suffix={suggestion.expectedImpact.unit}
              valueStyle={{
                color: IMPACT_DIRECTION_CONFIG[suggestion.expectedImpact.direction].color,
              }}
              prefix={IMPACT_DIRECTION_CONFIG[suggestion.expectedImpact.direction].icon}
            />
          </Card>
        </Col>
      </Row>

      <Collapse
        activeKey={activeKey}
        onChange={handleCollapseChange}
        style={{ marginTop: 16 }}
      >
        <Panel header="Reasoning" key="reasoning">
          <List
            itemLayout="horizontal"
            dataSource={suggestion.reasoning}
            renderItem={(item, index) => (
              <List.Item>
                <List.Item.Meta
                  avatar={<CheckCircleOutlined style={{ color: '#52c41a' }} />}
                  title={`Reason ${index + 1}`}
                  description={item}
                />
              </List.Item>
            )}
          />
        </Panel>

        {suggestion.alternatives && suggestion.alternatives.length > 0 && (
          <Panel header="Alternative Suggestions" key="alternatives">
            <List
              itemLayout="vertical"
              dataSource={suggestion.alternatives}
              renderItem={(alternative) => (
                <List.Item
                  extra={
                    <Space>
                      <Tag color="blue">Confidence: {alternative.confidence}%</Tag>
                      <Tag
                        color={
                          IMPACT_DIRECTION_CONFIG[alternative.expectedImpact.direction].color
                        }
                      >
                        {alternative.expectedImpact.metric}: {alternative.expectedImpact.value}{alternative.expectedImpact.unit}
                      </Tag>
                    </Space>
                  }
                >
                  <List.Item.Meta
                    title={alternative.title}
                    description={alternative.description}
                  />
                </List.Item>
              )}
            />
          </Panel>
        )}

        {suggestion.supportingData && suggestion.supportingData.length > 0 && (
          <Panel header="Supporting Data" key="supportingData">
            {suggestion.supportingData.map((data) => (
              <Card
                key={data.id}
                title={data.title}
                size="small"
                style={{ marginBottom: 16 }}
              >
                {renderSupportingData(data.data, data.type)}
              </Card>
            ))}
          </Panel>
        )}

        <Panel header="Confidence Breakdown" key="confidence">
          <div style={{ marginBottom: 16 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
              <span>Overall Confidence</span>
              <span>{suggestion.confidence}%</span>
            </div>
            <Progress percent={suggestion.confidence} status="active" />
          </div>
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
              <span>Data Quality</span>
              <span>85%</span>
            </div>
            <Progress percent={85} status="active" />
          </div>
          <div style={{ marginTop: 8 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
              <span>Model Accuracy</span>
              <span>92%</span>
            </div>
            <Progress percent={92} status="active" />
          </div>
          <div style={{ marginTop: 8 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
              <span>Context Relevance</span>
              <span>78%</span>
            </div>
            <Progress percent={78} status="active" />
          </div>
        </Panel>
      </Collapse>

      {showActions && (
        <div style={{ marginTop: 24, textAlign: 'right' }}>
          <Space size="middle">
            <Button onClick={onModify}>
              Modify
            </Button>
            <Button danger onClick={onReject}>
              Reject
            </Button>
            <Button type="primary" onClick={onApprove}>
              Approve
            </Button>
          </Space>
        </div>
      )}
    </Card>
  );
};

export default AISuggestionDisplay;
