import React, { useState } from 'react';
import {
  Box,
  Button,
  Card,
  CardContent,
  Container,
  Divider,
  FormControl,
  FormControlLabel,
  FormGroup,
  FormLabel,
  Grid,
  InputLabel,
  MenuItem,
  Paper,
  Select,
  Slider,
  Switch,
  TextField,
  Typography,
  Alert,
  Snackbar,
} from '@mui/material';
import SaveIcon from '@mui/icons-material/Save';
import RestartAltIcon from '@mui/icons-material/RestartAlt';
import SettingsBackupRestoreIcon from '@mui/icons-material/SettingsBackupRestore';

function ConfigurationPage() {
  const [cloudProvider, setCloudProvider] = useState('yandex');
  const [testScenario, setTestScenario] = useState('all');
  const [memoryLimit, setMemoryLimit] = useState(512);
  const [iterationsCount, setIterationsCount] = useState(100);
  const [concurrentRequests, setConcurrentRequests] = useState(10);
  const [timeoutSeconds, setTimeoutSeconds] = useState(60);
  const [saveSnackbarOpen, setSaveSnackbarOpen] = useState(false);
  
  // Оптимизации
  const [optimizations, setOptimizations] = useState({
    caching: true,
    packageOptimization: true,
    prewarming: true,
    connectionPooling: true,
    streamProcessing: false,
    asyncProcessing: false,
    compressionOptimization: true
  });

  const handleOptimizationChange = (event) => {
    setOptimizations({
      ...optimizations,
      [event.target.name]: event.target.checked,
    });
  };

  const handleSaveSettings = () => {
    setSaveSnackbarOpen(true);
  };

  const handleCloseSnackbar = () => {
    setSaveSnackbarOpen(false);
  };

  return (
    <Container maxWidth="lg">
      <Box sx={{ my: 4 }}>
        <Typography variant="h4" component="h1" gutterBottom>
          Конфигурация тестирования
        </Typography>
        <Typography variant="body1" paragraph>
          Настройте параметры тестирования и оптимизации serverless-функций.
        </Typography>

        <Grid container spacing={4}>
          <Grid item xs={12} md={6} sx={{ display: 'flex', flexDirection: 'column' }}>
            <Paper sx={{ p: 3, mb: 3, display: 'flex', flexDirection: 'column', flexGrow: 1 }}>
              <Typography variant="h6" gutterBottom>
                Основные параметры
              </Typography>
              <FormControl fullWidth margin="normal">
                <InputLabel>Облачный провайдер</InputLabel>
                <Select
                  value={cloudProvider}
                  label="Облачный провайдер"
                  onChange={(e) => setCloudProvider(e.target.value)}
                >
                  <MenuItem value="yandex">Яндекс Облако</MenuItem>
                  <MenuItem value="sber">SberCloud</MenuItem>
                  <MenuItem value="mail">Mail.ru Cloud Solutions</MenuItem>
                  <MenuItem value="selectel">Selectel</MenuItem>
                </Select>
              </FormControl>

              <FormControl fullWidth margin="normal">
                <InputLabel>Сценарий тестирования</InputLabel>
                <Select
                  value={testScenario}
                  label="Сценарий тестирования"
                  onChange={(e) => setTestScenario(e.target.value)}
                >
                  <MenuItem value="all">Все сценарии</MenuItem>
                  <MenuItem value="api">API Gateway</MenuItem>
                  <MenuItem value="processing">Обработка данных</MenuItem>
                  <MenuItem value="database">Работа с БД</MenuItem>
                  <MenuItem value="images">Обработка изображений</MenuItem>
                </Select>
              </FormControl>

              <Box sx={{ mt: 3 }}>
                <Typography gutterBottom>
                  Лимит памяти (МБ): {memoryLimit}
                </Typography>
                <Slider
                  value={memoryLimit}
                  onChange={(e, newValue) => setMemoryLimit(newValue)}
                  min={128}
                  max={2048}
                  step={128}
                  valueLabelDisplay="auto"
                  marks={[
                    { value: 128, label: '128' },
                    { value: 512, label: '512' },
                    { value: 1024, label: '1024' },
                    { value: 2048, label: '2048' },
                  ]}
                />
              </Box>

              <Grid container spacing={2} sx={{ mt: 1 }}>
                <Grid item xs={6}>
                  <TextField
                    fullWidth
                    label="Кол-во итераций"
                    type="number"
                    value={iterationsCount}
                    onChange={(e) => setIterationsCount(Number(e.target.value))}
                  />
                </Grid>
                <Grid item xs={6}>
                  <TextField
                    fullWidth
                    label="Одновременные запросы"
                    type="number"
                    value={concurrentRequests}
                    onChange={(e) => setConcurrentRequests(Number(e.target.value))}
                  />
                </Grid>
              </Grid>

              <TextField
                fullWidth
                margin="normal"
                label="Таймаут (секунды)"
                type="number"
                value={timeoutSeconds}
                onChange={(e) => setTimeoutSeconds(Number(e.target.value))}
              />
            </Paper>

            <Paper sx={{ p: 3, display: 'flex', flexDirection: 'column', flexGrow: 1 }}>
              <Typography variant="h6" gutterBottom>
                Дополнительные параметры
              </Typography>
              <FormControl fullWidth margin="normal">
                <TextField
                  fullWidth
                  label="Путь к тестовым данным"
                  defaultValue="/data/test_payload.json"
                />
              </FormControl>
              <FormControl fullWidth margin="normal">
                <TextField
                  fullWidth
                  label="Директория для выгрузки результатов"
                  defaultValue="/reports/"
                />
              </FormControl>
              <FormControl fullWidth margin="normal">
                <TextField
                  fullWidth
                  label="Имя файла отчёта"
                  defaultValue="serverless_test_report"
                />
              </FormControl>
              <Box sx={{ flexGrow: 1 }} />
            </Paper>
          </Grid>

          <Grid item xs={12} md={6} sx={{ display: 'flex', flexDirection: 'column' }}>
            <Paper sx={{ p: 3, mb: 3, display: 'flex', flexDirection: 'column', flexGrow: 1 }}>
              <Typography variant="h6" gutterBottom>
                Настройки оптимизации
              </Typography>
              <Typography variant="body2" paragraph>
                Выберите оптимизации, которые система будет применять к функциям.
              </Typography>

              <FormControl component="fieldset" sx={{ mt: 2 }}>
                <FormLabel component="legend">Оптимизации производительности</FormLabel>
                <FormGroup>
                  <FormControlLabel
                    control={
                      <Switch
                        checked={optimizations.caching}
                        onChange={handleOptimizationChange}
                        name="caching"
                      />
                    }
                    label="Кэширование результатов"
                  />
                  <FormControlLabel
                    control={
                      <Switch
                        checked={optimizations.packageOptimization}
                        onChange={handleOptimizationChange}
                        name="packageOptimization"
                      />
                    }
                    label="Оптимизация пакета зависимостей"
                  />
                  <FormControlLabel
                    control={
                      <Switch
                        checked={optimizations.prewarming}
                        onChange={handleOptimizationChange}
                        name="prewarming"
                      />
                    }
                    label="Предварительный разогрев функций"
                  />
                  <FormControlLabel
                    control={
                      <Switch
                        checked={optimizations.connectionPooling}
                        onChange={handleOptimizationChange}
                        name="connectionPooling"
                      />
                    }
                    label="Пулинг соединений"
                  />
                </FormGroup>
              </FormControl>

              <Divider sx={{ my: 2 }} />

              <FormControl component="fieldset">
                <FormLabel component="legend">Оптимизации обработки данных</FormLabel>
                <FormGroup>
                  <FormControlLabel
                    control={
                      <Switch
                        checked={optimizations.streamProcessing}
                        onChange={handleOptimizationChange}
                        name="streamProcessing"
                      />
                    }
                    label="Потоковая обработка данных"
                  />
                  <FormControlLabel
                    control={
                      <Switch
                        checked={optimizations.asyncProcessing}
                        onChange={handleOptimizationChange}
                        name="asyncProcessing"
                      />
                    }
                    label="Асинхронная обработка запросов"
                  />
                  <FormControlLabel
                    control={
                      <Switch
                        checked={optimizations.compressionOptimization}
                        onChange={handleOptimizationChange}
                        name="compressionOptimization"
                      />
                    }
                    label="Оптимизация сжатия данных"
                  />
                </FormGroup>
              </FormControl>
              <Box sx={{ flexGrow: 1 }} />
            </Paper>

            <Card sx={{ display: 'flex', flexDirection: 'column', flexGrow: 1 }}>
              <CardContent sx={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
                <Typography variant="h6" gutterBottom>
                  Шаблоны оптимизации
                </Typography>
                <Typography variant="body2" paragraph>
                  Выберите готовый шаблон оптимизации или сохраните текущие настройки как шаблон.
                </Typography>
                <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                  <Button
                    variant="outlined"
                    startIcon={<SettingsBackupRestoreIcon />}
                    onClick={() => {
                      setOptimizations({
                        caching: true,
                        packageOptimization: true,
                        prewarming: true,
                        connectionPooling: true,
                        streamProcessing: false,
                        asyncProcessing: false,
                        compressionOptimization: true,
                      });
                    }}
                  >
                    Загрузить базовые оптимизации
                  </Button>
                  <Button
                    variant="outlined"
                    startIcon={<SettingsBackupRestoreIcon />}
                    onClick={() => {
                      setOptimizations({
                        caching: true,
                        packageOptimization: true,
                        prewarming: true,
                        connectionPooling: true,
                        streamProcessing: true,
                        asyncProcessing: true,
                        compressionOptimization: true,
                      });
                    }}
                  >
                    Загрузить максимальные оптимизации
                  </Button>
                  <Button
                    variant="outlined"
                    startIcon={<SaveIcon />}
                  >
                    Сохранить текущие настройки как шаблон
                  </Button>
                </Box>
                <Box sx={{ flexGrow: 1 }} />
              </CardContent>
            </Card>
          </Grid>
        </Grid>

        <Box sx={{ mt: 4, display: 'flex', justifyContent: 'flex-end', gap: 2 }}>
          <Button
            variant="outlined"
            startIcon={<RestartAltIcon />}
            onClick={() => {
              setCloudProvider('yandex');
              setTestScenario('all');
              setMemoryLimit(512);
              setIterationsCount(100);
              setConcurrentRequests(10);
              setTimeoutSeconds(60);
              setOptimizations({
                caching: true,
                packageOptimization: true,
                prewarming: true,
                connectionPooling: true,
                streamProcessing: false,
                asyncProcessing: false,
                compressionOptimization: true,
              });
            }}
          >
            Сбросить настройки
          </Button>
          <Button
            variant="contained"
            startIcon={<SaveIcon />}
            onClick={handleSaveSettings}
          >
            Сохранить настройки
          </Button>
        </Box>

        <Snackbar
          open={saveSnackbarOpen}
          autoHideDuration={6000}
          onClose={handleCloseSnackbar}
        >
          <Alert 
            onClose={handleCloseSnackbar} 
            severity="success" 
            variant="filled"
          >
            Настройки успешно сохранены!
          </Alert>
        </Snackbar>
      </Box>
    </Container>
  );
}

export default ConfigurationPage; 