import React, { useState } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Select,
  Slider,
  DatePicker,
  Typography,
  Alert,
  Space,
  Divider,
  Steps,
  Radio,
  InputNumber,
  Tag,
  Tooltip,
} from 'antd';
import {
  ExperimentOutlined,
  PlusOutlined,
  DeleteOutlined,
  InfoCircleOutlined,
  SaveOutlined,
  PlayCircleOutlined,
} from '@ant-design/icons';
import type { Dayjs } from 'dayjs';
import { abTestDataSource, ABTestConfig as ABTestConfigData, TestVariant } from '@/services/abTestDataSource';

const { Title, Text, Paragraph } = Typography;
const { Option } = Select;
const { Step } = Steps;
const { RangePicker } = DatePicker;

interface ABTestFormData {
  name: string;
  description: string;
  type: string;
  startDate?: Dayjs;
  endDate?: Dayjs;
  audience: {
    segments: string[];
    platforms: string[];
    countries: string[];
  };
  successCriteria: {
    metric: string;
    threshold: number;
    confidenceLevel: number;
  };
}

export const ABTestConfigPage: React.FC = () => {
  const [form] = Form.useForm();
  const [currentStep, setCurrentStep] = useState(0);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [variants, setVariants] = useState<TestVariant[]>([
    { id: 'control', name: 'Control (A)', description: 'Current version', trafficAllocation: 50, configuration: {} },
    { id: 'variant-1', name: 'Variant B', description: 'Test version', trafficAllocation: 50, configuration: {} },
  ]);

  const testTypes = [
    { value: 'UI', label: 'UI/UX Test', description: 'Test different user interface designs' },
    { value: 'PRICE', label: 'Pricing Test', description: 'Test different pricing strategies' },
    { value: 'CONTENT', label: 'Content Test', description: 'Test different content variations' },
    { value: 'FEATURE', label: 'Feature Test', description: 'Test new feature adoption' },
  ];

  const targetMetrics = [
    { value: 'conversion_rate', label: 'Conversion Rate' },
    { value: 'revenue_per_user', label: 'Revenue Per User' },
    { value: 'click_through_rate', label: 'Click-Through Rate' },
    { value: 'bounce_rate', label: 'Bounce Rate' },
    { value: 'session_duration', label: 'Session Duration' },
    { value: 'add_to_cart_rate', label: 'Add to Cart Rate' },
  ];

  const audienceSegments = [
    'New Visitors',
    'Returning Customers',
    'High Value Customers',
    'Mobile Users',
    'Desktop Users',
    'VIP Members',
  ];

  const platforms = ['Amazon', 'Temu', 'TikTok', 'Shopee', 'Lazada'];
  const countries = ['US', 'CA', 'UK', 'DE', 'FR', 'JP', 'AU'];

  const steps = [
    { title: 'Basic Info', description: 'Test details' },
    { title: 'Variants', description: 'Test variations' },
    { title: 'Audience', description: 'Target users' },
    { title: 'Review', description: 'Final check' },
  ];

  const addVariant = () => {
    const newVariant: TestVariant = {
      id: `variant-${variants.length}`,
      name: `Variant ${String.fromCharCode(66 + variants.length - 1)}`,
      description: '',
      trafficAllocation: 0,
      configuration: {},
    };
    setVariants([...variants, newVariant]);
  };

  const removeVariant = (index: number) => {
    if (variants.length <= 2) {
      setError('At least 2 variants are required');
      return;
    }
    const newVariants = variants.filter((_, i) => i !== index);
    // Redistribute traffic evenly
    const equalAllocation = Math.floor(100 / newVariants.length);
    newVariants.forEach((v, i) => {
      v.trafficAllocation = i === newVariants.length - 1 
        ? 100 - (equalAllocation * (newVariants.length - 1))
        : equalAllocation;
    });
    setVariants(newVariants);
  };

  const updateVariantAllocation = (index: number, value: number) => {
    const newVariants = [...variants];
    const oldValue = newVariants[index].trafficAllocation;
    const diff = value - oldValue;
    
    newVariants[index].trafficAllocation = value;
    
    // Distribute the difference to other variants
    const otherIndices = newVariants.map((_, i) => i).filter(i => i !== index);
    const diffPerVariant = Math.floor(diff / otherIndices.length);
    
    otherIndices.forEach(i => {
      newVariants[i].trafficAllocation = Math.max(0, newVariants[i].trafficAllocation - diffPerVariant);
    });
    
    // Ensure total is 100
    const total = newVariants.reduce((sum, v) => sum + v.trafficAllocation, 0);
    if (total !== 100) {
      newVariants[otherIndices[0]].trafficAllocation += (100 - total);
    }
    
    setVariants(newVariants);
  };

  const handleNext = async () => {
    try {
      if (currentStep === 0) {
        await form.validateFields(['name', 'type', 'targetMetric']);
      } else if (currentStep === 1) {
        const totalAllocation = variants.reduce((sum, v) => sum + v.trafficAllocation, 0);
        if (totalAllocation !== 100) {
          setError(`Traffic allocation must total 100%. Current: ${totalAllocation}%`);
          return;
        }
      }
      setError(null);
      setCurrentStep(currentStep + 1);
    } catch (err) {
      // Validation failed
    }
  };

  const handlePrev = () => {
    setCurrentStep(currentStep - 1);
    setError(null);
  };

  const handleSave = async () => {
    setLoading(true);
    try {
      const values = await form.validateFields();
      const config: ABTestConfig = {
        ...values,
        variants,
      };
      
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      // Success
      setCurrentStep(4); // Success step
    } catch (err) {
      setError('Failed to save A/B test configuration');
    } finally {
      setLoading(false);
    }
  };

  const renderStepContent = () => {
    switch (currentStep) {
      case 0:
        return (
          <Space direction="vertical" style={{ width: '100%' }} size="large">
            <Form.Item
              name="name"
              label="Test Name"
              rules={[{ required: true, message: 'Please enter test name' }]}
            >
              <Input placeholder="e.g., Homepage Banner Test Q1 2024" />
            </Form.Item>

            <Form.Item
              name="description"
              label="Description"
              rules={[{ required: true, message: 'Please enter test description' }]}
            >
              <Input.TextArea 
                rows={3} 
                placeholder="Describe the purpose and hypothesis of this A/B test"
              />
            </Form.Item>

            <Form.Item
              name="type"
              label="Test Type"
              rules={[{ required: true, message: 'Please select test type' }]}
            >
              <Select placeholder="Select test type">
                {testTypes.map(type => (
                  <Option key={type.value} value={type.value}>
                    <Space direction="vertical" size={0}>
                      <Text strong>{type.label}</Text>
                      <Text type="secondary" style={{ fontSize: 12 }}>{type.description}</Text>
                    </Space>
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="targetMetric"
              label="Primary Metric"
              rules={[{ required: true, message: 'Please select target metric' }]}
            >
              <Select placeholder="Select primary success metric">
                {targetMetrics.map(metric => (
                  <Option key={metric.value} value={metric.value}>
                    {metric.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="duration"
              label="Test Duration (days)"
              rules={[{ required: true, message: 'Please enter test duration' }]}
            >
              <InputNumber min={7} max={90} style={{ width: 200 }} />
            </Form.Item>

            <Form.Item
              name="dateRange"
              label="Schedule"
            >
              <RangePicker style={{ width: '100%' }} />
            </Form.Item>
          </Space>
        );

      case 1:
        return (
          <Space direction="vertical" style={{ width: '100%' }} size="large">
            <Alert
              message="Traffic Allocation"
              description="Distribute traffic percentage across variants. Total must equal 100%."
              type="info"
              showIcon
            />

            {variants.map((variant, index) => (
              <Card 
                key={variant.id}
                size="small"
                title={
                  <Space>
                    <Tag color={index === 0 ? 'blue' : 'green'}>
                      {variant.name}
                    </Tag>
                    {index === 0 && <Tag color="default">Control</Tag>}
                  </Space>
                }
                extra={
                  index > 0 && (
                    <Button
                      type="text"
                      danger
                      icon={<DeleteOutlined />}
                      onClick={() => removeVariant(index)}
                    />
                  )
                }
              >
                <Space direction="vertical" style={{ width: '100%' }}>
                  <Form.Item label="Description" style={{ marginBottom: 8 }}>
                    <Input
                      value={variant.description}
                      onChange={e => {
                        const newVariants = [...variants];
                        newVariants[index].description = e.target.value;
                        setVariants(newVariants);
                      }}
                      placeholder="Describe this variant"
                    />
                  </Form.Item>

                  <Form.Item label="Traffic Allocation" style={{ marginBottom: 8 }}>
                    <Slider
                      min={0}
                      max={100}
                      value={variant.trafficAllocation}
                      onChange={value => updateVariantAllocation(index, value)}
                      marks={{ 0: '0%', 50: '50%', 100: '100%' }}
                    />
                    <Text>{variant.trafficAllocation}%</Text>
                  </Form.Item>
                </Space>
              </Card>
            ))}

            <Button
              type="dashed"
              onClick={addVariant}
              block
              icon={<PlusOutlined />}
            >
              Add Variant
            </Button>

            <div style={{ textAlign: 'center' }}>
              <Text type="secondary">
                Total Allocation: {' '}
                <Text 
                  type={variants.reduce((sum, v) => sum + v.trafficAllocation, 0) === 100 ? 'success' : 'danger'}
                  strong
                >
                  {variants.reduce((sum, v) => sum + v.trafficAllocation, 0)}%
                </Text>
              </Text>
            </div>
          </Space>
        );

      case 2:
        return (
          <Space direction="vertical" style={{ width: '100%' }} size="large">
            <Form.Item
              name={['audience', 'segments']}
              label="Audience Segments"
            >
              <Select mode="multiple" placeholder="Select audience segments">
                {audienceSegments.map(segment => (
                  <Option key={segment} value={segment}>{segment}</Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name={['audience', 'platforms']}
              label="Target Platforms"
            >
              <Select mode="multiple" placeholder="Select platforms">
                {platforms.map(platform => (
                  <Option key={platform} value={platform}>{platform}</Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name={['audience', 'countries']}
              label="Target Countries"
            >
              <Select mode="multiple" placeholder="Select countries">
                {countries.map(country => (
                  <Option key={country} value={country}>{country}</Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="trafficPercentage"
              label="Traffic Percentage"
              tooltip="Percentage of eligible traffic to include in the test"
            >
              <Slider
                min={1}
                max={100}
                marks={{ 1: '1%', 25: '25%', 50: '50%', 75: '75%', 100: '100%' }}
              />
            </Form.Item>

            <Divider />

            <Title level={5}>Success Criteria</Title>

            <Form.Item
              name={['successCriteria', 'metric']}
              label="Success Metric"
            >
              <Select placeholder="Select success metric">
                {targetMetrics.map(metric => (
                  <Option key={metric.value} value={metric.value}>
                    {metric.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name={['successCriteria', 'threshold']}
              label="Minimum Improvement (%)"
              tooltip="Minimum percentage improvement to declare a winner"
            >
              <InputNumber min={1} max={50} suffix="%" style={{ width: 200 }} />
            </Form.Item>

            <Form.Item
              name={['successCriteria', 'confidenceLevel']}
              label="Confidence Level"
            >
              <Radio.Group>
                <Radio.Button value={90}>90%</Radio.Button>
                <Radio.Button value={95}>95%</Radio.Button>
                <Radio.Button value={99}>99%</Radio.Button>
              </Radio.Group>
            </Form.Item>
          </Space>
        );

      case 3:
        const values = form.getFieldsValue();
        return (
          <Space direction="vertical" style={{ width: '100%' }} size="large">
            <Alert
              message="Review Configuration"
              description="Please review all settings before launching the test."
              type="warning"
              showIcon
            />

            <Card title="Test Details" size="small">
              <Paragraph>
                <Text strong>Name: </Text>{values.name}
              </Paragraph>
              <Paragraph>
                <Text strong>Type: </Text>{testTypes.find(t => t.value === values.type)?.label}
              </Paragraph>
              <Paragraph>
                <Text strong>Target Metric: </Text>
                {targetMetrics.find(m => m.value === values.targetMetric)?.label}
              </Paragraph>
              <Paragraph>
                <Text strong>Duration: </Text>{values.duration} days
              </Paragraph>
            </Card>

            <Card title="Variants" size="small">
              {variants.map((variant, index) => (
                <Paragraph key={variant.id}>
                  <Tag color={index === 0 ? 'blue' : 'green'}>{variant.name}</Tag>
                  <Text> - {variant.trafficAllocation}% traffic</Text>
                  {variant.description && (
                    <Text type="secondary"> ({variant.description})</Text>
                  )}
                </Paragraph>
              ))}
            </Card>

            <Card title="Audience" size="small">
              <Paragraph>
                <Text strong>Platforms: </Text>
                {values.audience?.platforms?.join(', ') || 'All platforms'}
              </Paragraph>
              <Paragraph>
                <Text strong>Countries: </Text>
                {values.audience?.countries?.join(', ') || 'All countries'}
              </Paragraph>
              <Paragraph>
                <Text strong>Traffic: </Text>
                {values.trafficPercentage || 100}% of eligible users
              </Paragraph>
            </Card>
          </Space>
        );

      case 4:
        return (
          <Alert
            message="A/B Test Created Successfully!"
            description="Your test has been configured and is ready to launch. You can start the test from the test management page."
            type="success"
            showIcon
            action={
              <Button type="primary" href="/ab-test/results">
                View Test Dashboard
              </Button>
            }
          />
        );

      default:
        return null;
    }
  };

  return (
    <div style={{ padding: 24, maxWidth: 800, margin: '0 auto' }}>
      <Card>
        <Title level={3}>
          <ExperimentOutlined /> Create A/B Test
        </Title>
        <Paragraph type="secondary">
          Configure and launch A/B tests to optimize your business metrics
        </Paragraph>

        <Steps current={currentStep} style={{ marginBottom: 32 }}>
          {steps.map(step => (
            <Step key={step.title} title={step.title} description={step.description} />
          ))}
        </Steps>

        {error && (
          <Alert
            message={error}
            type="error"
            showIcon
            style={{ marginBottom: 16 }}
            closable
            onClose={() => setError(null)}
          />
        )}

        <Form form={form} layout="vertical">
          {renderStepContent()}
        </Form>

        {currentStep < 4 && (
          <div style={{ marginTop: 24, display: 'flex', justifyContent: 'space-between' }}>
            <Button onClick={handlePrev} disabled={currentStep === 0}>
              Previous
            </Button>
            <Space>
              {currentStep < 3 ? (
                <Button type="primary" onClick={handleNext}>
                  Next
                </Button>
              ) : (
                <Button 
                  type="primary" 
                  icon={<SaveOutlined />}
                  onClick={handleSave}
                  loading={loading}
                >
                  Save & Launch
                </Button>
              )}
            </Space>
          </div>
        )}
      </Card>
    </div>
  );
};

export default ABTestConfigPage;
