import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Tag,
  Typography,
  Statistic,
  Row,
  Col,
  Progress,
  Alert,
  Button,
  Space,
  Tabs,
  DatePicker,
  Select,
  Tooltip,
  Badge,
  Divider,
  Empty,
} from 'antd';
import {
  ExperimentOutlined,
  TrophyOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  InfoCircleOutlined,
  DownloadOutlined,
  SyncOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  MinusCircleOutlined,
} from '@ant-design/icons';
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
  BarChart,
  Bar,
  PieChart,
  Pie,
  Cell,
} from 'recharts';
import type { Dayjs } from 'dayjs';
import { abTestDataSource, ABTestResult } from '@/services/abTestDataSource';

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

interface TestResult {
  id: string;
  name: string;
  status: 'RUNNING' | 'COMPLETED' | 'PAUSED' | 'DRAFT';
  type: string;
  startDate: string;
  endDate?: string;
  totalVisitors: number;
  totalConversions: number;
  confidenceLevel: number;
  winner?: string;
  variants: VariantResult[];
}

interface VariantResult {
  id: string;
  name: string;
  isControl: boolean;
  visitors: number;
  conversions: number;
  conversionRate: number;
  improvement: number;
  confidenceInterval: [number, number];
  isWinner: boolean;
  isSignificant: boolean;
}

interface DailyMetric {
  date: string;
  control: number;
  variant: number;
}

export const ABTestResultsPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [selectedTest, setSelectedTest] = useState<string | null>(null);
  const [dateRange, setDateRange] = useState<[Dayjs, Dayjs] | null>(null);
  const [activeTab, setActiveTab] = useState('overview');

  // Mock data
  const testResults: TestResult[] = [
    {
      id: 'test-001',
      name: 'Homepage Banner Test',
      status: 'COMPLETED',
      type: 'UI',
      startDate: '2024-03-01',
      endDate: '2024-03-15',
      totalVisitors: 50000,
      totalConversions: 2500,
      confidenceLevel: 95,
      winner: 'Variant B',
      variants: [
        {
          id: 'control',
          name: 'Control (A)',
          isControl: true,
          visitors: 25000,
          conversions: 1125,
          conversionRate: 4.5,
          improvement: 0,
          confidenceInterval: [4.2, 4.8],
          isWinner: false,
          isSignificant: false,
        },
        {
          id: 'variant-b',
          name: 'Variant B',
          isControl: false,
          visitors: 25000,
          conversions: 1375,
          conversionRate: 5.5,
          improvement: 22.2,
          confidenceInterval: [5.2, 5.8],
          isWinner: true,
          isSignificant: true,
        },
      ],
    },
    {
      id: 'test-002',
      name: 'Pricing Strategy Test',
      status: 'RUNNING',
      type: 'PRICE',
      startDate: '2024-03-10',
      totalVisitors: 30000,
      totalConversions: 1200,
      confidenceLevel: 0,
      variants: [
        {
          id: 'control',
          name: 'Control ($99)',
          isControl: true,
          visitors: 15000,
          conversions: 600,
          conversionRate: 4.0,
          improvement: 0,
          confidenceInterval: [3.7, 4.3],
          isWinner: false,
          isSignificant: false,
        },
        {
          id: 'variant-b',
          name: 'Variant B ($89)',
          isControl: false,
          visitors: 15000,
          conversions: 600,
          conversionRate: 4.0,
          improvement: 0,
          confidenceInterval: [3.7, 4.3],
          isWinner: false,
          isSignificant: false,
        },
      ],
    },
  ];

  const dailyMetrics: DailyMetric[] = [
    { date: '2024-03-01', control: 4.2, variant: 4.5 },
    { date: '2024-03-02', control: 4.3, variant: 4.8 },
    { date: '2024-03-03', control: 4.1, variant: 4.6 },
    { date: '2024-03-04', control: 4.4, variant: 5.0 },
    { date: '2024-03-05', control: 4.5, variant: 5.2 },
    { date: '2024-03-06', control: 4.3, variant: 5.1 },
    { date: '2024-03-07', control: 4.6, variant: 5.3 },
  ];

  const trafficDistribution = [
    { name: 'Control', value: 50, color: '#1890ff' },
    { name: 'Variant B', value: 50, color: '#52c41a' },
  ];

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'RUNNING': return 'processing';
      case 'COMPLETED': return 'success';
      case 'PAUSED': return 'warning';
      case 'DRAFT': return 'default';
      default: return 'default';
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'RUNNING': return <SyncOutlined spin />;
      case 'COMPLETED': return <CheckCircleOutlined />;
      case 'PAUSED': return <MinusCircleOutlined />;
      case 'DRAFT': return <InfoCircleOutlined />;
      default: return null;
    }
  };

  const columns = [
    {
      title: 'Test Name',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: TestResult) => (
        <Space>
          <Text strong>{text}</Text>
          <Tag color={getStatusColor(record.status)}>
            {getStatusIcon(record.status)} {record.status}
          </Tag>
        </Space>
      ),
    },
    {
      title: 'Type',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => (
        <Tag>{type}</Tag>
      ),
    },
    {
      title: 'Duration',
      key: 'duration',
      render: (_: any, record: TestResult) => (
        <Text>{record.startDate} {record.endDate ? `to ${record.endDate}` : 'to present'}</Text>
      ),
    },
    {
      title: 'Visitors',
      dataIndex: 'totalVisitors',
      key: 'visitors',
      render: (value: number) => value.toLocaleString(),
    },
    {
      title: 'Winner',
      key: 'winner',
      render: (_: any, record: TestResult) => (
        record.winner ? (
          <Space>
            <TrophyOutlined style={{ color: '#faad14' }} />
            <Text type="success" strong>{record.winner}</Text>
          </Space>
        ) : (
          <Text type="secondary">No winner yet</Text>
        )
      ),
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_: any, record: TestResult) => (
        <Space>
          <Button type="link" onClick={() => setSelectedTest(record.id)}>
            View Details
          </Button>
          <Button type="link" icon={<DownloadOutlined />}>
            Export
          </Button>
        </Space>
      ),
    },
  ];

  const selectedTestData = testResults.find(t => t.id === selectedTest);

  return (
    <div style={{ padding: 24 }}>
      <Title level={3}>
        <ExperimentOutlined /> A/B Test Results
      </Title>
      <Paragraph type="secondary">
        Monitor and analyze your A/B test performance
      </Paragraph>

      <Card style={{ marginBottom: 24 }}>
        <Space style={{ marginBottom: 16 }}>
          <RangePicker onChange={dates => setDateRange(dates as [Dayjs, Dayjs])} />
          <Select defaultValue="all" style={{ width: 120 }}>
            <Option value="all">All Tests</Option>
            <Option value="running">Running</Option>
            <Option value="completed">Completed</Option>
            <Option value="paused">Paused</Option>
          </Select>
          <Button type="primary" icon={<SyncOutlined />} loading={loading}>
            Refresh
          </Button>
        </Space>

        <Table
          columns={columns}
          dataSource={testResults}
          rowKey="id"
          loading={loading}
        />
      </Card>

      {selectedTestData && (
        <Card>
          <Tabs activeKey={activeTab} onChange={setActiveTab}>
            <TabPane tab="Overview" key="overview">
              <Row gutter={16} style={{ marginBottom: 24 }}>
                <Col span={6}>
                  <Statistic
                    title="Total Visitors"
                    value={selectedTestData.totalVisitors}
                    formatter={value => (value as number).toLocaleString()}
                  />
                </Col>
                <Col span={6}>
                  <Statistic
                    title="Total Conversions"
                    value={selectedTestData.totalConversions}
                    formatter={value => (value as number).toLocaleString()}
                  />
                </Col>
                <Col span={6}>
                  <Statistic
                    title="Overall Conversion Rate"
                    value={((selectedTestData.totalConversions / selectedTestData.totalVisitors) * 100).toFixed(2)}
                    suffix="%"
                  />
                </Col>
                <Col span={6}>
                  <Statistic
                    title="Confidence Level"
                    value={selectedTestData.confidenceLevel}
                    suffix="%"
                    valueStyle={{ color: selectedTestData.confidenceLevel >= 95 ? '#52c41a' : '#faad14' }}
                  />
                </Col>
              </Row>

              {selectedTestData.winner && (
                <Alert
                  message="Test Completed"
                  description={
                    <Space>
                      <TrophyOutlined style={{ color: '#faad14' }} />
                      <Text strong>{selectedTestData.winner}</Text>
                      <Text>is the winner with</Text>
                      <Text type="success" strong>
                        +{selectedTestData.variants.find(v => v.name === selectedTestData.winner)?.improvement.toFixed(1)}% improvement
                      </Text>
                    </Space>
                  }
                  type="success"
                  showIcon
                  style={{ marginBottom: 24 }}
                />
              )}

              <Title level={5}>Variant Performance</Title>
              <Row gutter={16}>
                {selectedTestData.variants.map(variant => (
                  <Col span={12} key={variant.id}>
                    <Card
                      size="small"
                      title={
                        <Space>
                          <Text strong>{variant.name}</Text>
                          {variant.isWinner && (
                            <Tag color="success" icon={<TrophyOutlined />}>Winner</Tag>
                          )}
                          {variant.isControl && (
                            <Tag>Control</Tag>
                          )}
                        </Space>
                      }
                    >
                      <Row gutter={16}>
                        <Col span={12}>
                          <Statistic
                            title="Visitors"
                            value={variant.visitors}
                            formatter={value => (value as number).toLocaleString()}
                          />
                        </Col>
                        <Col span={12}>
                          <Statistic
                            title="Conversions"
                            value={variant.conversions}
                            formatter={value => (value as number).toLocaleString()}
                          />
                        </Col>
                      </Row>
                      <Divider style={{ margin: '12px 0' }} />
                      <Row gutter={16}>
                        <Col span={12}>
                          <Statistic
                            title="Conversion Rate"
                            value={variant.conversionRate}
                            suffix="%"
                            precision={2}
                          />
                        </Col>
                        <Col span={12}>
                          <Statistic
                            title="Improvement"
                            value={variant.improvement}
                            suffix="%"
                            precision={1}
                            valueStyle={{ color: variant.improvement > 0 ? '#52c41a' : variant.improvement < 0 ? '#ff4d4f' : '#666' }}
                            prefix={variant.improvement > 0 ? <ArrowUpOutlined /> : variant.improvement < 0 ? <ArrowDownOutlined /> : null}
                          />
                        </Col>
                      </Row>
                      <div style={{ marginTop: 12 }}>
                        <Text type="secondary" style={{ fontSize: 12 }}>
                          Confidence Interval: [{variant.confidenceInterval[0].toFixed(1)}%, {variant.confidenceInterval[1].toFixed(1)}%]
                        </Text>
                        {variant.isSignificant && (
                          <Tag color="success" style={{ marginLeft: 8 }}>Statistically Significant</Tag>
                        )}
                      </div>
                    </Card>
                  </Col>
                ))}
              </Row>
            </TabPane>

            <TabPane tab="Trends" key="trends">
              <Card title="Conversion Rate Over Time" size="small">
                <ResponsiveContainer width="100%" height={300}>
                  <LineChart data={dailyMetrics}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="date" />
                    <YAxis domain={[0, 6]} />
                    <RechartsTooltip formatter={(value: number) => `${value.toFixed(2)}%`} />
                    <Legend />
                    <Line type="monotone" dataKey="control" name="Control" stroke="#1890ff" strokeWidth={2} />
                    <Line type="monotone" dataKey="variant" name="Variant B" stroke="#52c41a" strokeWidth={2} />
                  </LineChart>
                </ResponsiveContainer>
              </Card>

              <Row gutter={16} style={{ marginTop: 16 }}>
                <Col span={12}>
                  <Card title="Traffic Distribution" size="small">
                    <ResponsiveContainer width="100%" height={250}>
                      <PieChart>
                        <Pie
                          data={trafficDistribution}
                          cx="50%"
                          cy="50%"
                          innerRadius={60}
                          outerRadius={80}
                          paddingAngle={5}
                          dataKey="value"
                        >
                          {trafficDistribution.map((entry, index) => (
                            <Cell key={`cell-${index}`} fill={entry.color} />
                          ))}
                        </Pie>
                        <RechartsTooltip />
                        <Legend />
                      </PieChart>
                    </ResponsiveContainer>
                  </Card>
                </Col>
                <Col span={12}>
                  <Card title="Daily Visitors" size="small">
                    <ResponsiveContainer width="100%" height={250}>
                      <BarChart data={dailyMetrics}>
                        <CartesianGrid strokeDasharray="3 3" />
                        <XAxis dataKey="date" />
                        <YAxis />
                        <RechartsTooltip />
                        <Legend />
                        <Bar dataKey="control" name="Control" fill="#1890ff" />
                        <Bar dataKey="variant" name="Variant B" fill="#52c41a" />
                      </BarChart>
                    </ResponsiveContainer>
                  </Card>
                </Col>
              </Row>
            </TabPane>

            <TabPane tab="Statistical Analysis" key="statistics">
              <Card title="Statistical Significance">
                <Row gutter={16}>
                  <Col span={8}>
                    <Statistic
                      title="P-Value"
                      value={0.023}
                      precision={3}
                      valueStyle={{ color: '#52c41a' }}
                    />
                    <Text type="secondary">P &lt; 0.05 indicates statistical significance</Text>
                  </Col>
                  <Col span={8}>
                    <Statistic
                      title="Z-Score"
                      value={2.31}
                      precision={2}
                    />
                  </Col>
                  <Col span={8}>
                    <Statistic
                      title="Power"
                      value={85}
                      suffix="%"
                    />
                    <Text type="secondary">Probability of detecting true effect</Text>
                  </Col>
                </Row>

                <Divider />

                <Title level={5}>Sample Size Analysis</Title>
                <Progress
                  percent={75}
                  status="active"
                  format={percent => `${percent}% of required sample`}
                />
                <Paragraph type="secondary">
                  Current sample size is sufficient for detecting a 20% improvement with 95% confidence.
                </Paragraph>
              </Card>
            </TabPane>
          </Tabs>
        </Card>
      )}

      {!selectedTestData && (
        <Card>
          <Empty
            description="Select a test from the table above to view detailed results"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
        </Card>
      )}
    </div>
  );
};

export default ABTestResultsPage;
