import { useList } from "@refinedev/core";
import { Card, Col, Row, Statistic, Progress, Alert, Table, Typography } from "antd";
import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer
} from "recharts";
import { 
  CheckCircleOutlined, 
  WarningOutlined, 
  ArrowUpOutlined, 
  ArrowDownOutlined 
} from '@ant-design/icons';

const { Title } = Typography;

// Mock data for the chart
const performanceData = [
  { name: '00:00', cpu: 40, memory: 55, network: 20 },
  { name: '03:00', cpu: 30, memory: 58, network: 28 },
  { name: '06:00', cpu: 20, memory: 40, network: 20 },
  { name: '09:00', cpu: 27, memory: 60, network: 40 },
  { name: '12:00', cpu: 90, memory: 76, network: 60 },
  { name: '15:00', cpu: 75, memory: 65, network: 50 },
  { name: '18:00', cpu: 80, memory: 70, network: 45 },
  { name: '21:00', cpu: 65, memory: 60, network: 30 },
];

// Mock data for alerts
const alertsData = [
  { id: 1, level: 'critical', message: 'Server CPU usage exceeds 90%', timestamp: '2025-05-08T12:30:00', status: 'active' },
  { id: 2, level: 'warning', message: 'Database memory utilization above 75%', timestamp: '2025-05-08T11:15:00', status: 'active' },
  { id: 3, level: 'info', message: 'Client deployment auto-scaled to 3 instances', timestamp: '2025-05-08T09:45:00', status: 'resolved' },
  { id: 4, level: 'warning', message: 'Network latency spiked to 250ms', timestamp: '2025-05-08T08:20:00', status: 'resolved' },
];

export const MonitoringDashboard = () => {
  const { data: deploymentsData } = useList({
    resource: "deployments",
  });

  // Calculate some stats from deployments data
  const activeDeployments = deploymentsData?.data?.filter(item => item.status === "active").length || 0;
  const totalDeployments = deploymentsData?.data?.length || 0;
  const healthyDeployments = deploymentsData?.data?.filter(item => item.healthStatus === "healthy").length || 0;

  return (
    <>
      <Title level={4}>Infrastructure Monitoring</Title>
      
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="Active Deployments"
              value={activeDeployments}
              precision={0}
              valueStyle={{ color: '#3f8600' }}
              prefix={<CheckCircleOutlined />}
            />
            <div style={{ marginTop: 10 }}>
              <Progress percent={totalDeployments > 0 ? Math.round((activeDeployments / totalDeployments) * 100) : 0} size="small" />
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Health Status"
              value={`${healthyDeployments}/${totalDeployments}`}
              valueStyle={{ color: healthyDeployments === totalDeployments ? '#3f8600' : '#faad14' }}
              prefix={healthyDeployments === totalDeployments ? <CheckCircleOutlined /> : <WarningOutlined />}
              suffix="deployments healthy"
            />
            <div style={{ marginTop: 10 }}>
              <Progress percent={totalDeployments > 0 ? Math.round((healthyDeployments / totalDeployments) * 100) : 0} size="small" status={healthyDeployments === totalDeployments ? "success" : "exception"} />
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Average CPU Usage"
              value={68}
              precision={0}
              valueStyle={{ color: '#1890ff' }}
              suffix="%"
            />
            <div style={{ marginTop: 10 }}>
              <Progress percent={68} size="small" status={68 > 80 ? "exception" : "active"} />
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Average Memory Usage"
              value={72}
              precision={0}
              valueStyle={{ color: '#1890ff' }}
              suffix="%"
            />
            <div style={{ marginTop: 10 }}>
              <Progress percent={72} size="small" status={72 > 80 ? "exception" : "active"} />
            </div>
          </Card>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={16}>
          <Card title="System Performance">
            <ResponsiveContainer width="100%" height={300}>
              <AreaChart
                data={performanceData}
                margin={{ top: 10, right: 30, left: 0, bottom: 0 }}
              >
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="name" />
                <YAxis />
                <Tooltip />
                <Area type="monotone" dataKey="cpu" stackId="1" stroke="#8884d8" fill="#8884d8" name="CPU %" />
                <Area type="monotone" dataKey="memory" stackId="2" stroke="#82ca9d" fill="#82ca9d" name="Memory %" />
                <Area type="monotone" dataKey="network" stackId="3" stroke="#ffc658" fill="#ffc658" name="Network MB/s" />
              </AreaChart>
            </ResponsiveContainer>
          </Card>
        </Col>
        <Col span={8}>
          <Card title="Active Alerts" style={{ height: '100%' }}>
            {alertsData
              .filter(alert => alert.status === 'active')
              .map(alert => (
                <Alert
                  key={alert.id}
                  message={alert.message}
                  type={alert.level === 'critical' ? 'error' : alert.level === 'warning' ? 'warning' : 'info'}
                  showIcon
                  style={{ marginBottom: 10 }}
                />
              ))}
          </Card>
        </Col>
      </Row>

      <Row>
        <Col span={24}>
          <Card title="Recent System Events">
            <Table 
              dataSource={alertsData}
              pagination={{ pageSize: 5 }}
              rowKey="id"
              columns={[
                { title: 'Level', dataIndex: 'level', key: 'level', 
                  render: (text) => {
                    const color = text === 'critical' ? 'red' : text === 'warning' ? 'orange' : 'blue';
                    return <span style={{ color }}>{text.toUpperCase()}</span>;
                  }
                },
                { title: 'Message', dataIndex: 'message', key: 'message' },
                { title: 'Timestamp', dataIndex: 'timestamp', key: 'timestamp' },
                { title: 'Status', dataIndex: 'status', key: 'status',
                  render: (text) => {
                    return text === 'active' ? 
                      <span style={{ color: 'red' }}>ACTIVE</span> : 
                      <span style={{ color: 'green' }}>RESOLVED</span>;
                  }
                }
              ]}
            />
          </Card>
        </Col>
      </Row>
    </>
  );
};