import { useEffect, useState } from 'react';
import {
  Box,
  Typography,
  Grid,
  Card,
  CardMedia,
  CardContent,
  CardActions,
  Button,
  CircularProgress,
  Modal,
  List,
  ListItem,
  ListItemText,
  IconButton,
} from '@mui/material';
import { useNavigate } from 'react-router-dom';
import AddIcon from '@mui/icons-material/Add';
import DownloadIcon from '@mui/icons-material/Download';

interface VersionCardProps {
  id: string;
  name: string;
  imageUrl: string;
  version: string;
  onSelect: (id: string) => void;
  isHovered: boolean;
  onHover: (id: string | null) => void;
  hoveredCardId: string | null;
}

export const VersionCard: React.FC<VersionCardProps> = ({
  id,
  name,
  imageUrl,
  version,
  onSelect,
  isHovered,
  onHover,
  hoveredCardId,
}) => {
  return (
    <Card
      sx={{
        backgroundColor: 'rgba(30, 30, 50, 0.8)',
        backdropFilter: 'blur(10px)',
        width: '35vw',
        height: '35vh',
        minWidth: 'unset',
        minHeight: 'unset',
        display: 'flex',
        flexDirection: 'column',
        borderRadius: '16px',
        boxShadow: '0 8px 32px rgba(0, 0, 0, 0.3)',
        transition: 'transform 0.3s, box-shadow 0.3s, filter 0.3s',
        overflow: 'hidden',
        cursor: 'pointer',
        filter: hoveredCardId && !isHovered ? 'blur(5px)' : 'blur(0px)',
        transform: isHovered ? 'scale(1.03)' : 'scale(1)',
        zIndex: isHovered ? 10 : 1,
        '&:hover': {
          boxShadow: '0 12px 40px rgba(0, 0, 0, 0.5)',
        },
      }}
      onClick={() => onSelect(id)}
      onMouseEnter={() => onHover(id)}
      onMouseLeave={() => onHover(null)}
    >
      <CardContent
        sx={{
          flexGrow: 1,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          height: '10%',
        }}
      >
        <Typography
          gutterBottom
          variant="h5"
          component="div"
          sx={{
            fontWeight: 'bold',
            color: '#ffffff',
            fontSize: '1.5rem',
          }}
        >
          {name}
        </Typography>
      </CardContent>
    </Card>
  );
};

interface VersionInfo {
  id: string;
  name: string;
  version: string;
  imageUrl?: string;
  config?: {
    downloadUrl: string;
    apiReleaseUrl: string;
    versionFileName: string;
    packName: string;
    memory: number;
    baseVersion: string;
    serverIp: string;
    fabricVersion: string;
    preserveFiles: string[];
  };
}

interface AvailableVersionInfo {
  id: string;
  name: string;
  version: string;
  imageUrl?: string;
  config: {
    downloadUrl: string;
    apiReleaseUrl: string;
    versionFileName: string;
    packName: string;
    memory: number;
    baseVersion: string;
    serverIp: string;
    fabricVersion: string;
    preserveFiles: string[];
  };
}

// В компоненте VersionsExplorer
export const VersionsExplorer = () => {
  const [installedVersions, setInstalledVersions] = useState<VersionInfo[]>([]);
  const [availableVersions, setAvailableVersions] = useState<
    AvailableVersionInfo[]
  >([]);
  const [loading, setLoading] = useState(true);
  const [modalOpen, setModalOpen] = useState(false);
  const [downloadLoading, setDownloadLoading] = useState<string | null>(null);
  const [hoveredCardId, setHoveredCardId] = useState<string | null>(null);
  const navigate = useNavigate();

  useEffect(() => {
    const fetchVersions = async () => {
      try {
        setLoading(true);

        // Получаем список установленных версий через IPC
        const installedResult = await window.electron.ipcRenderer.invoke(
          'get-installed-versions',
        );
        if (installedResult.success) {
          setInstalledVersions(installedResult.versions);
        }

        // Получаем доступные версии с GitHub Gist
        const availableResult = await window.electron.ipcRenderer.invoke(
          'get-available-versions',
          {
            gistUrl:
              'https://gist.githubusercontent.com/DIKER0K/06cd12fb3a4d08b1f0f8c763a7d05e06/raw/versions.json',
          },
        );
        if (availableResult.success) {
          setAvailableVersions(availableResult.versions);
        }
      } catch (error) {
        console.error('Ошибка при загрузке версий:', error);
        // Можно добавить обработку ошибки, например показать уведомление
      } finally {
        setLoading(false);
      }
    };

    fetchVersions();
  }, []);

  const handleSelectVersion = (version: VersionInfo) => {
    localStorage.setItem(
      'selected_version_config',
      JSON.stringify(version.config || {}),
    );
    navigate(`/launch/${version.id}`);
  };

  const handleAddVersion = () => {
    setModalOpen(true);
  };

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

  const handleDownloadVersion = async (version: AvailableVersionInfo) => {
    try {
      setDownloadLoading(version.id);

      // Скачивание и установка выбранной версии
      const downloadResult = await window.electron.ipcRenderer.invoke(
        'download-and-extract',
        {
          downloadUrl: version.config.downloadUrl,
          apiReleaseUrl: version.config.apiReleaseUrl,
          versionFileName: version.config.versionFileName,
          packName: version.id,
          preserveFiles: version.config.preserveFiles || [],
        },
      );

      if (downloadResult?.success) {
        // Добавляем скачанную версию в список установленных
        setInstalledVersions((prev) => [...prev, version]);
        setModalOpen(false);
      }
    } catch (error) {
      console.error(`Ошибка при скачивании версии ${version.id}:`, error);
    } finally {
      setDownloadLoading(null);
    }
  };

  // Карточка добавления новой версии
  const AddVersionCard = () => (
    <Card
      sx={{
        backgroundColor: 'rgba(30, 30, 50, 0.8)',
        backdropFilter: 'blur(10px)',
        width: '35vw',
        height: '35vh',
        minWidth: 'unset',
        minHeight: 'unset',
        display: 'flex',
        flexDirection: 'column',
        borderRadius: '16px',
        boxShadow: '0 8px 32px rgba(0, 0, 0, 0.3)',
        transition: 'transform 0.3s, box-shadow 0.3s, filter 0.3s',
        overflow: 'hidden',
        justifyContent: 'center',
        alignItems: 'center',
        cursor: 'pointer',
        filter: hoveredCardId && hoveredCardId !== 'add' ? 'blur(5px)' : 'blur(0)',
        transform: hoveredCardId === 'add' ? 'scale(1.03)' : 'scale(1)',
        zIndex: hoveredCardId === 'add' ? 10 : 1,
        '&:hover': {
          boxShadow: '0 12px 40px rgba(0, 0, 0, 0.5)',
        },
      }}
      onClick={handleAddVersion}
      onMouseEnter={() => setHoveredCardId('add')}
      onMouseLeave={() => setHoveredCardId(null)}
    >
      <AddIcon sx={{ fontSize: 60, color: '#fff' }} />
      <Typography
        variant="h6"
        sx={{
          color: '#fff',
        }}
      >
        Добавить
      </Typography>
      <Typography
        variant="h6"
        sx={{
          color: '#fff',
        }}
      >
        версию
      </Typography>
    </Card>
  );

  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        paddingLeft: '5vw',
        paddingRight: '5vw',
        position: 'relative',
        flexGrow: 1,
        height: 'calc(100vh - 64px)',
        overflow: 'hidden',
      }}
    >
      {/* Глобальный фоновый слой для размытия всего интерфейса */}
      <Box
        sx={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backdropFilter: hoveredCardId ? 'blur(10px)' : 'blur(0)',
          transition: 'backdrop-filter 0.3s ease-in-out',
          zIndex: 5,
          pointerEvents: 'none',
        }}
      />

      {loading ? (
        <Box display="flex" justifyContent="center" my={5}>
          <CircularProgress />
        </Box>
      ) : (
        <Grid
          container
          spacing={3}
          sx={{
            width: '100%',
            height: '100%',
            overflowY: 'auto',
            justifyContent: 'center',
            alignContent: 'center',
            position: 'relative',
            zIndex: 6,
            padding: '2vh 0',
          }}
        >
          {/* Показываем установленные версии или дефолтную, если она есть */}
          {installedVersions.length > 0 ? (
            installedVersions.map((version) => (
              <Grid
                key={version.id}
                item
                xs={12}
                sm={6}
                md={4}
                sx={{
                  display: 'flex',
                  justifyContent: 'center',
                  marginBottom: '2vh',
                }}
              >
                <VersionCard
                  id={version.id}
                  name={version.name}
                  imageUrl={
                    version.imageUrl ||
                    'https://via.placeholder.com/300x140?text=Minecraft'
                  }
                  version={version.version}
                  onSelect={() => handleSelectVersion(version)}
                  isHovered={hoveredCardId === version.id}
                  onHover={setHoveredCardId}
                  hoveredCardId={hoveredCardId}
                />
              </Grid>
            ))
          ) : (
            // Если нет ни одной версии, показываем карточку добавления
            <Grid
              item
              xs={12}
              sm={6}
              md={4}
              sx={{
                display: 'flex',
                justifyContent: 'center',
                marginBottom: '2vh',
              }}
            >
              <AddVersionCard />
            </Grid>
          )}

          {/* Всегда добавляем карточку для добавления новых версий */}
          {installedVersions.length > 0 && (
            <Grid
              item
              xs={12}
              sm={6}
              md={4}
              sx={{
                display: 'flex',
                justifyContent: 'center',
                marginBottom: '2vh',
              }}
            >
              <AddVersionCard />
            </Grid>
          )}
        </Grid>
      )}

      {/* Модальное окно для выбора версии для скачивания */}
      <Modal
        open={modalOpen}
        onClose={handleCloseModal}
        aria-labelledby="modal-versions"
        aria-describedby="modal-available-versions"
      >
        <Box
          sx={{
            position: 'absolute',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            width: 400,
            maxHeight: '80vh',
            overflowY: 'auto',
            background: 'linear-gradient(45deg, #000000 10%, #3b4187 184.73%)',
            border: '2px solid #000',
            boxShadow: 24,
            p: 4,
            borderRadius: '3vw',
            gap: '1vh',
            display: 'flex',
            flexDirection: 'column',
            backdropFilter: 'blur(10px)',
          }}
        >
          <Typography variant="h6" component="h2" sx={{ color: '#fff' }}>
            Доступные версии для скачивания
          </Typography>

          {availableVersions.length === 0 ? (
            <Typography sx={{ color: '#fff', mt: 2 }}>
              Загрузка доступных версий...
            </Typography>
          ) : (
            <List sx={{ mt: 2 }}>
              {availableVersions.map((version) => (
                <ListItem
                  key={version.id}
                  sx={{
                    borderRadius: '8px',
                    mb: 1,
                    backgroundColor: 'rgba(255, 255, 255, 0.1)',
                    cursor: 'pointer',
                    '&:hover': {
                      backgroundColor: 'rgba(255, 255, 255, 0.2)',
                    },
                  }}
                  onClick={() => handleSelectVersion(version)}
                >
                  <ListItemText
                    primary={version.name}
                    secondary={version.version}
                    primaryTypographyProps={{ color: '#fff' }}
                    secondaryTypographyProps={{
                      color: 'rgba(255,255,255,0.7)',
                    }}
                  />
                </ListItem>
              ))}
            </List>
          )}

          <Button
            onClick={handleCloseModal}
            variant="outlined"
            sx={{
              mt: 3,
              alignSelf: 'center',
              borderColor: '#fff',
              color: '#fff',
              '&:hover': {
                borderColor: '#ccc',
                backgroundColor: 'rgba(255,255,255,0.1)',
              },
            }}
          >
            Закрыть
          </Button>
        </Box>
      </Modal>
    </Box>
  );
};
