import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Box,
  Button,
  Container,
  Divider,
  IconButton,
  List,
  ListItem,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Modal,
  Paper,
  Tooltip,
  Typography,
  Collapse,
} from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import CodeIcon from '@mui/icons-material/Code';
import JavascriptIcon from '@mui/icons-material/Javascript';
import CloudIcon from '@mui/icons-material/Cloud';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import ExpandLessIcon from '@mui/icons-material/ExpandLess';
import VisibilityIcon from '@mui/icons-material/Visibility';
import SpeedIcon from '@mui/icons-material/Speed';
import Chip from '@mui/material/Chip';

// Моковые данные для отображения
const mockFunctions = [
  {
    id: 'func1',
    name: 'API Gateway Handler',
    language: 'python',
    platform: 'yandex',
    versions: [
      { version: 1, type: 'manual', createdAt: '2024-03-10' },
      { version: 2, type: 'auto', createdAt: '2024-03-11' },
      { version: 3, type: 'manual', createdAt: '2024-03-12' }
    ]
  },
  {
    id: 'func2',
    name: 'Database Worker',
    language: 'nodejs',
    platform: 'yandex',
    versions: [
      { version: 1, type: 'manual', createdAt: '2024-03-14' },
      { version: 2, type: 'auto', createdAt: '2024-03-15' }
    ]
  },
  {
    id: 'func3',
    name: 'Image Processor',
    language: 'python',
    platform: 'yandex',
    versions: [
      { version: 1, type: 'manual', createdAt: '2024-03-20' }
    ]
  }
];

const modalStyle = {
  position: 'absolute',
  top: '50%',
  left: '50%',
  transform: 'translate(-50%, -50%)',
  width: 400,
  bgcolor: 'background.paper',
  borderRadius: 1,
  boxShadow: 24,
  p: 4,
};

function FunctionsPage() {
  const navigate = useNavigate();
  const [expandedFunctions, setExpandedFunctions] = useState({});
  const [selectedVersion, setSelectedVersion] = useState(null);
  const [modalOpen, setModalOpen] = useState(false);

  const toggleFunction = (id) => {
    setExpandedFunctions(prev => ({
      ...prev,
      [id]: !prev[id]
    }));
  };

  const openVersionModal = (func, version) => {
    setSelectedVersion({ functionId: func.id, functionName: func.name, ...version });
    setModalOpen(true);
  };

  const closeModal = () => {
    setModalOpen(false);
  };

  const handleViewClick = () => {
    navigate(`/optimization/${selectedVersion.functionId}/${selectedVersion.version}`);
    closeModal();
  };

  const handleTestClick = () => {
    navigate(`/testing/${selectedVersion.functionId}/${selectedVersion.version}`);
    closeModal();
  };

  const getLanguageIcon = (language) => {
    switch (language) {
      case 'python':
        return <CodeIcon fontSize="small" color="primary" />;
      case 'nodejs':
        return <JavascriptIcon fontSize="small" color="warning" />;
      default:
        return <CodeIcon fontSize="small" />;
    }
  };

  const getPlatformIcon = (platform) => {
    return <CloudIcon fontSize="small" color="info" />;
  };

  const getVersionTypeChip = (type) => {
    if (type === 'auto') {
      return <Chip label="Auto" size="small" color="secondary" variant="outlined" sx={{ ml: 1 }} />;
    }
    return <Chip label="Manual" size="small" color="primary" variant="outlined" sx={{ ml: 1 }} />;
  };

  return (
    <Container maxWidth="lg">
      <Box sx={{ my: 4 }}>
        <Typography variant="h4" component="h1" gutterBottom>
          Сохраненные функции
        </Typography>
        <Paper elevation={2} sx={{ p: 0, mb: 4 }}>
          <List sx={{ width: '100%' }}>
            {mockFunctions.map((func) => (
              <React.Fragment key={func.id}>
                <ListItem
                  secondaryAction={
                    <IconButton edge="end" onClick={() => toggleFunction(func.id)}>
                      {expandedFunctions[func.id] ? <ExpandLessIcon /> : <ExpandMoreIcon />}
                    </IconButton>
                  }
                  disablePadding
                >
                  <ListItemButton onClick={() => toggleFunction(func.id)}>
                    <ListItemIcon>
                      {getLanguageIcon(func.language)}
                    </ListItemIcon>
                    <ListItemText 
                      primary={func.name} 
                      primaryTypographyProps={{ fontWeight: 'medium' }}
                    />
                    <Box sx={{ display: 'flex', alignItems: 'center', mr: 2 }}>
                      <Tooltip title={func.language === 'python' ? 'Python' : 'Node.js'}>
                        {getLanguageIcon(func.language)}
                      </Tooltip>
                      <Box sx={{ mx: 0.5 }} />
                      <Tooltip title="Yandex Cloud Functions">
                        {getPlatformIcon(func.platform)}
                      </Tooltip>
                    </Box>
                  </ListItemButton>
                </ListItem>
                
                <Collapse in={expandedFunctions[func.id]} timeout="auto" unmountOnExit>
                  <List component="div" disablePadding>
                    {func.versions.map((version) => (
                      <ListItem 
                        key={`${func.id}-v${version.version}`}
                        sx={{ pl: 4 }}
                        secondaryAction={
                          <IconButton edge="end" onClick={() => openVersionModal(func, version)}>
                            <VisibilityIcon fontSize="small" />
                          </IconButton>
                        }
                      >
                        <ListItemButton onClick={() => openVersionModal(func, version)}>
                          <ListItemText 
                            primary={`Версия ${version.version}`} 
                            secondary={version.createdAt}
                          />
                          {getVersionTypeChip(version.type)}
                        </ListItemButton>
                      </ListItem>
                    ))}
                  </List>
                </Collapse>
                <Divider component="li" />
              </React.Fragment>
            ))}
          </List>
        </Paper>

        <Button
          variant="contained"
          color="primary"
          startIcon={<AddIcon />}
          onClick={() => navigate('/optimization')}
          sx={{ mb: 4 }}
        >
          Новая функция
        </Button>

        <Modal
          open={modalOpen}
          onClose={closeModal}
          aria-labelledby="version-modal-title"
        >
          <Box sx={modalStyle}>
            <Typography id="version-modal-title" variant="h6" component="h2" gutterBottom>
              {selectedVersion && `${selectedVersion.functionName} - Версия ${selectedVersion.version}`}
            </Typography>
            <Typography variant="body2" color="text.secondary" gutterBottom>
              {selectedVersion && `Создана: ${selectedVersion.createdAt}`}
            </Typography>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', mt: 3 }}>
              <Button
                variant="outlined"
                startIcon={<VisibilityIcon />}
                onClick={handleViewClick}
              >
                Просмотр
              </Button>
              <Button
                variant="contained"
                startIcon={<SpeedIcon />}
                onClick={handleTestClick}
              >
                Тестирование
              </Button>
            </Box>
          </Box>
        </Modal>
      </Box>
    </Container>
  );
}

export default FunctionsPage; 