import React, { useState } from 'react';
import {
  Box,
  Paper,
  IconButton,
  Typography,
  Grid,
  Card,
  CardContent,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  List,
  ListItem,
  ListItemButton,
  ListItemText,
  ListItemAvatar,
  Avatar,
  Chip,
  Tooltip
} from '@mui/material';
import {
  Add,
  Close,
  ViewModule,
  ViewComfy,
  GridView,
  SwapHoriz
} from '@mui/icons-material';
import VideoPlayer from './VideoPlayer';
import Logo from './Logo';

function MultiScreen({ channels }) {
  const [screens, setScreens] = useState([null, null]); // Start with 2 screens
  const [layout, setLayout] = useState('2x1'); // '2x1', '2x2', '3x1', '1x2'
  const [selectDialogOpen, setSelectDialogOpen] = useState(false);
  const [selectingScreenIndex, setSelectingScreenIndex] = useState(null);

  const layouts = [
    { value: '1x2', label: '1×2', icon: <ViewModule />, screens: 2, cols: 1, rows: 2 },
    { value: '2x1', label: '2×1', icon: <ViewComfy />, screens: 2, cols: 2, rows: 1 },
    { value: '2x2', label: '2×2', icon: <GridView />, screens: 4, cols: 2, rows: 2 },
    { value: '3x1', label: '3×1', icon: <ViewModule />, screens: 3, cols: 3, rows: 1 }
  ];

  const currentLayout = layouts.find(l => l.value === layout) || layouts[1];

  const handleLayoutChange = (newLayout) => {
    const newLayoutConfig = layouts.find(l => l.value === newLayout);
    setLayout(newLayout);
    
    // Adjust screens array to match new layout
    const newScreens = [...screens];
    while (newScreens.length < newLayoutConfig.screens) {
      newScreens.push(null);
    }
    while (newScreens.length > newLayoutConfig.screens) {
      newScreens.pop();
    }
    setScreens(newScreens);
  };

  const handleOpenSelectDialog = (screenIndex) => {
    setSelectingScreenIndex(screenIndex);
    setSelectDialogOpen(true);
  };

  const handleSelectChannel = (channel) => {
    const newScreens = [...screens];
    newScreens[selectingScreenIndex] = channel;
    setScreens(newScreens);
    setSelectDialogOpen(false);
  };

  const handleRemoveChannel = (screenIndex) => {
    const newScreens = [...screens];
    newScreens[screenIndex] = null;
    setScreens(newScreens);
  };

  const handleSwapScreens = (index1, index2) => {
    const newScreens = [...screens];
    [newScreens[index1], newScreens[index2]] = [newScreens[index2], newScreens[index1]];
    setScreens(newScreens);
  };

  return (
    <Box>
      {/* Layout Controls */}
      <Paper sx={{ p: 2, mb: 2 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <Box>
            <Typography variant="h6" fontWeight="bold" gutterBottom>
              Multi-Screen View
            </Typography>
            <Typography variant="caption" color="text.secondary">
              Watch up to {currentLayout.screens} channels simultaneously
            </Typography>
          </Box>
          
          <Box sx={{ display: 'flex', gap: 1 }}>
            {layouts.map((layoutOption) => (
              <Tooltip key={layoutOption.value} title={layoutOption.label}>
                <IconButton
                  onClick={() => handleLayoutChange(layoutOption.value)}
                  color={layout === layoutOption.value ? 'primary' : 'default'}
                  sx={{
                    border: layout === layoutOption.value ? 2 : 1,
                    borderColor: layout === layoutOption.value ? 'primary.main' : 'divider'
                  }}
                >
                  {layoutOption.icon}
                </IconButton>
              </Tooltip>
            ))}
          </Box>
        </Box>
      </Paper>

      {/* Multi-Screen Grid */}
      <Grid container spacing={2}>
        {screens.map((channel, index) => (
          <Grid 
            item 
            key={index}
            xs={12 / currentLayout.cols}
            md={12 / currentLayout.cols}
          >
            <Paper
              sx={{
                position: 'relative',
                aspectRatio: '16/9',
                bgcolor: 'background.paper',
                borderRadius: 2,
                overflow: 'hidden',
                border: 2,
                borderColor: channel ? 'primary.main' : 'divider'
              }}
            >
              {channel ? (
                <>
                  {/* Screen Controls */}
                  <Box
                    sx={{
                      position: 'absolute',
                      top: 8,
                      right: 8,
                      zIndex: 10,
                      display: 'flex',
                      gap: 0.5
                    }}
                  >
                    <Chip
                      label={`Screen ${index + 1}`}
                      size="small"
                      sx={{ bgcolor: 'rgba(0,0,0,0.7)', color: 'white' }}
                    />
                    {index < screens.length - 1 && screens[index + 1] && (
                      <Tooltip title="Swap with next">
                        <IconButton
                          size="small"
                          onClick={() => handleSwapScreens(index, index + 1)}
                          sx={{ bgcolor: 'rgba(0,0,0,0.7)', color: 'white', '&:hover': { bgcolor: 'rgba(0,0,0,0.9)' } }}
                        >
                          <SwapHoriz fontSize="small" />
                        </IconButton>
                      </Tooltip>
                    )}
                    <Tooltip title="Remove channel">
                      <IconButton
                        size="small"
                        onClick={() => handleRemoveChannel(index)}
                        sx={{ bgcolor: 'rgba(0,0,0,0.7)', color: 'white', '&:hover': { bgcolor: 'rgba(0,0,0,0.9)' } }}
                      >
                        <Close fontSize="small" />
                      </IconButton>
                    </Tooltip>
                  </Box>

                  {/* Video Player (PiP disabled for multi-screen) */}
                  <VideoPlayer channel={channel} enablePip={false} />
                </>
              ) : (
                <Box
                  sx={{
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    justifyContent: 'center',
                    height: '100%',
                    gap: 2,
                    bgcolor: 'action.hover'
                  }}
                >
                  <Logo size={80} />
                  <Typography variant="h6" color="text.secondary">
                    Screen {index + 1}
                  </Typography>
                  <Button
                    variant="contained"
                    startIcon={<Add />}
                    onClick={() => handleOpenSelectDialog(index)}
                  >
                    Select Channel
                  </Button>
                </Box>
              )}
            </Paper>
          </Grid>
        ))}
      </Grid>

      {/* Channel Selection Dialog */}
      <Dialog
        open={selectDialogOpen}
        onClose={() => setSelectDialogOpen(false)}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>
          Select Channel for Screen {selectingScreenIndex !== null ? selectingScreenIndex + 1 : ''}
        </DialogTitle>
        <DialogContent>
          <List>
            {channels.map((channel) => {
              const alreadySelected = screens.some(s => s?.id === channel.id);
              return (
                <ListItem key={channel.id} disablePadding>
                  <ListItemButton
                    onClick={() => handleSelectChannel(channel)}
                    disabled={alreadySelected}
                  >
                    <ListItemAvatar>
                      {channel.logo ? (
                        <Avatar
                          src={channel.logo.startsWith('http') ? channel.logo : `/logos/${channel.logo}`}
                          alt={channel.name}
                          variant="rounded"
                        />
                      ) : (
                        <Avatar variant="rounded">
                          <Logo size={32} />
                        </Avatar>
                      )}
                    </ListItemAvatar>
                    <ListItemText
                      primary={channel.name}
                      secondary={channel.group_name}
                    />
                    {alreadySelected && (
                      <Chip label="In Use" size="small" color="primary" />
                    )}
                  </ListItemButton>
                </ListItem>
              );
            })}
          </List>
        </DialogContent>
      </Dialog>
    </Box>
  );
}

export default MultiScreen;
