import React, { useState, useEffect, useContext } from 'react';
import { Link, useParams } from 'react-router-dom';
import { UserContext } from '../context/UserContext';
import axios from 'axios';
import { Box, Typography, Grid2, Card, CardContent, CardMedia, Button, IconButton, Dialog, DialogTitle, DialogContent, DialogActions, TextField, FormControl, InputLabel, Select, MenuItem, Tooltip } from '@mui/material';
import AddIcon from '@mui/icons-material/Add';

import defaultCharacterImage from '../assets/default-character.png';
import defaultItemImage from '../assets/default-item.png';

const GameMasterPage = () => {
  const { userId } = useContext(UserContext);
  const { gameId } = useParams();
  const [playerCharacters, setPlayerCharacters] = useState([]);
  const [npcs, setNpcs] = useState([]);
  const [items, setItems] = useState([]);
  const [editModalOpen, setEditModalOpen] = useState(false);
  const [selectedItem, setSelectedItem] = useState(null);
  const [editType, setEditType] = useState(''); // 'item', 'npc', or 'character'
  const [isEditing, setIsEditing] = useState(false);
  const [allOwners, setAllOwners] = useState([]);
  const [formData, setFormData] = useState(null);

  // Update useEffect for data fetching
  useEffect(() => {
    const fetchData = async () => {
      try {
        const pcsResponse = await axios.get(`http://localhost:5000/games/${gameId}/playerchars`);
        const processedPCs = Array.isArray(pcsResponse.data) ? pcsResponse.data : [pcsResponse.data];
        setPlayerCharacters(processedPCs.filter(pc => pc !== null));

        const npcsResponse = await axios.get(`http://localhost:5000/games/${gameId}/npcs`);
        const processedNPCs = Array.isArray(npcsResponse.data) ? npcsResponse.data : [npcsResponse.data];
        setNpcs(processedNPCs.filter(npc => npc !== null));

        const itemsResponse = await axios.get(`http://localhost:5000/games/${gameId}/items`);
        const processedItems = Array.isArray(itemsResponse.data) ? itemsResponse.data : [itemsResponse.data];
        setItems(processedItems.filter(item => item !== null));
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    // Initial fetch only if no modal is open
    if (!editModalOpen) {
      fetchData();
    }
    
    // Set up polling only if modal is closed
    let interval;
    if (!editModalOpen) {
      interval = setInterval(fetchData, 5000);
    }
    
    return () => {
      if (interval) clearInterval(interval);
    };
  }, [gameId, editModalOpen]);

  useEffect(() => {
    const fetchOwners = async () => {
      try {
        // Only fetch player characters
        const pcsResponse = await axios.get(`http://localhost:5000/games/${gameId}/playerchars`);
        
        const pcs = pcsResponse.data.map(pc => ({
          id: pc.CharID,
          name: pc.CharName,
          type: 'Player Character'
        }));
        
        setAllOwners([
          { id: null, name: 'Unassigned', type: 'None' },
          ...pcs
        ]);
      } catch (error) {
        console.error('Error fetching potential owners:', error);
      }
    };

    fetchOwners();
  }, [gameId]);

  const handleItemClick = (item) => {
    setSelectedItem(item);
    setFormData({...item});
    setEditType('item');
    setEditModalOpen(true);
    setIsEditing(true); // Stops the polling
  };

  const handleNpcClick = (npc) => {
    setSelectedItem(npc);
    setFormData({...npc});
    setEditType('npc');
    setEditModalOpen(true);
    setIsEditing(true);
  };

  const handleCharacterClick = (character) => {
    setSelectedItem(character);
    setFormData({...character});
    setEditType('character');
    setEditModalOpen(true);
    setIsEditing(true);
  };

  // Update handleUpdate to fetch once after saving
  const handleUpdate = async () => {
    try {
      let response;
      if (editType === 'item') {
        response = await axios.put(`http://localhost:5000/games/item/${selectedItem.ItemID}`, formData);
      } else if (editType === 'npc') {
        response = await axios.put(`http://localhost:5000/games/npc/${selectedItem.NPCID}`, formData);
      } else if (editType === 'character') {
        response = await axios.put(`http://localhost:5000/games/character/${selectedItem.CharID}`, formData);
      }
      
      if (response.status === 200) {
        const fetchData = async () => {
          try {
            const pcsResponse = await axios.get(`http://localhost:5000/games/${gameId}/playerchars`);
            const processedPCs = Array.isArray(pcsResponse.data) ? pcsResponse.data : [pcsResponse.data];
            setPlayerCharacters(processedPCs.filter(pc => pc !== null));

            const npcsResponse = await axios.get(`http://localhost:5000/games/${gameId}/npcs`);
            const processedNPCs = Array.isArray(npcsResponse.data) ? npcsResponse.data : [npcsResponse.data];
            setNpcs(processedNPCs.filter(npc => npc !== null));

            const itemsResponse = await axios.get(`http://localhost:5000/games/${gameId}/items`);
            const processedItems = Array.isArray(itemsResponse.data) ? itemsResponse.data : [itemsResponse.data];
            setItems(processedItems.filter(item => item !== null));
          } catch (error) {
            console.error('Error fetching data:', error);
          }
        };
        await fetchData(); // Fetch once after successful update
        setEditModalOpen(false);
        setFormData(null);
      }
    } catch (error) {
      console.error('Error updating:', error);
    }
  };

  const handleModalClose = () => {
    setEditModalOpen(false);
    setIsEditing(false); // Restarts the polling
    setFormData(null);
  };

  // First, define the common input styles at component level
  const commonStyles = {
    dialog: {
      '& .MuiPaper-root': {
        backgroundColor: '#1e1e2f',
        color: '#fff',
        border: '1px solid #444',
        borderRadius: '8px',
        minWidth: '500px'
      }
    },
    input: {
      '& .MuiOutlinedInput-root': {
        color: '#fff',
        '& fieldset': { borderColor: '#444' },
        '&:hover fieldset': { borderColor: '#764ACB' },
        '&.Mui-focused fieldset': { borderColor: '#764ACB' },
      },
      '& .MuiInputLabel-root': { 
        color: '#fff',
        '&.Mui-focused': {
          color: '#764ACB'
        }
      },
      '& .MuiInputBase-input': { color: '#fff' }
    },
    select: {
      color: '#fff',
      '.MuiInputLabel-root': { 
        color: '#fff',
        '&.Mui-focused': {
          color: '#764ACB'
        }
      },
      '.MuiSelect-select': { 
        color: '#fff',
        backgroundColor: '#1e1e2f'
      },
      '.MuiOutlinedInput-root': {
        color: '#fff',
        backgroundColor: '#1e1e2f',
        '& fieldset': { borderColor: '#444' },
        '&:hover fieldset': { borderColor: '#764ACB' },
        '&.Mui-focused fieldset': { borderColor: '#764ACB' }
      },
      '.MuiSelect-icon': { color: '#fff' }
    },
    menuItem: {
      backgroundColor: '#1e1e2f',
      color: '#fff',
      '&:hover': {
        backgroundColor: '#2e2e3f'
      },
      '&.Mui-selected': {
        backgroundColor: '#764ACB',
        '&:hover': {
          backgroundColor: '#9865f7'
        }
      }
    }
  };

  // Add new handler for form changes
  const handleFormChange = (key, value) => {
    setFormData(prev => ({
      ...prev,
      [key]: value
    }));
  };

  // Update the EditModal component
  const EditModal = () => {
    const nonEditableFields = [
      'GameID', 'CharID', 'ItemID', 'NPCID', 'Img', 'img', 
      'GameId', 'NpcID', 'itemID', 'PlayerID', 'OwnerName'
    ];
    
    const renderField = (key) => {
      if (key === 'Allied') {
        return (
          <FormControl fullWidth key={key} sx={{ mb: 2, ...commonStyles.select }}>
            <InputLabel>Status</InputLabel>
            <Select
              value={formData[key] || 0}
              label="Status"
              onChange={(e) => handleFormChange(key, e.target.value)}
            >
              <MenuItem value={0}>Allied</MenuItem>
              <MenuItem value={1}>Neutral</MenuItem>
              <MenuItem value={2}>Enemy</MenuItem>
            </Select>
          </FormControl>
        );
      }
      
      if (key === 'Sex') {
        return (
          <FormControl fullWidth key={key} sx={{ mb: 2, ...commonStyles.select }}>
            <InputLabel>Sex</InputLabel>
            <Select
              value={formData[key] || ''}
              label="Sex"
              onChange={(e) => handleFormChange(key, e.target.value)}
            >
              <MenuItem value="Male">Male</MenuItem>
              <MenuItem value="Female">Female</MenuItem>
              <MenuItem value="Other">Other</MenuItem>
            </Select>
          </FormControl>
        );
      }

      if (key === 'Rarity') {
        return (
          <FormControl fullWidth key={key} sx={{ mb: 2, ...commonStyles.select }}>
            <InputLabel>Rarity</InputLabel>
            <Select
              value={formData[key] || 1}
              label="Rarity"
              onChange={(e) => handleFormChange(key, e.target.value)}
            >
              <MenuItem value={1}>Poor</MenuItem>
              <MenuItem value={2}>Common</MenuItem>
              <MenuItem value={3}>Uncommon</MenuItem>
              <MenuItem value={4}>Rare</MenuItem>
              <MenuItem value={5}>Epic</MenuItem>
              <MenuItem value={6}>Legendary</MenuItem>
              <MenuItem value={7}>Artifact</MenuItem>
            </Select>
          </FormControl>
        );
      }

      if (key === 'Type') {
        return (
          <FormControl fullWidth key={key} sx={{ mb: 2, ...commonStyles.select }}>
            <InputLabel>Type</InputLabel>
            <Select
              value={formData[key] || ''}
              label="Type"
              onChange={(e) => handleFormChange(key, e.target.value)}
            >
              <MenuItem value="Weapon">Weapon</MenuItem>
              <MenuItem value="Armor">Armor</MenuItem>
              <MenuItem value="Consumable">Consumable</MenuItem>
              <MenuItem value="Quest">Quest Item</MenuItem>
              <MenuItem value="Other">Other</MenuItem>
            </Select>
          </FormControl>
        );
      }

      if (key === 'Art') {
        return (
          <FormControl fullWidth key={key} sx={{ mb: 2, ...commonStyles.select }}>
            <InputLabel>Art</InputLabel>
            <Select
              value={formData[key] || ''}
              label="Art"
              onChange={(e) => handleFormChange(key, e.target.value)}
            >
              <MenuItem value="Sword">Sword</MenuItem>
              <MenuItem value="Axe">Axe</MenuItem>
              <MenuItem value="Bow">Bow</MenuItem>
              <MenuItem value="Shield">Shield</MenuItem>
              <MenuItem value="Staff">Staff</MenuItem>
              <MenuItem value="Potion">Potion</MenuItem>
              <MenuItem value="Other">Other</MenuItem>
            </Select>
          </FormControl>
        );
      }

      if (key === 'OwnerID') {
        return (
          <FormControl fullWidth key={key} sx={{ mb: 2, ...commonStyles.select }}>
            <InputLabel sx={{ color: '#fff' }}>Owner</InputLabel>
            <Select
              value={formData[key] || ''}
              label="Owner"
              onChange={(e) => handleFormChange(key, e.target.value)}
              sx={{
                color: '#fff',
                '& .MuiOutlinedInput-notchedOutline': { borderColor: '#444' },
                '&:hover .MuiOutlinedInput-notchedOutline': { borderColor: '#764ACB' },
              }}
            >
              {allOwners.map((owner) => (
                <MenuItem 
                  key={owner.id} 
                  value={owner.id || ''}
                  sx={{ 
                    ...commonStyles.menuItem,
                    display: 'flex', 
                    justifyContent: 'space-between' 
                  }}
                >
                  <span>{owner.name}</span>
                  {owner.type !== 'None' && (
                    <Typography 
                      variant="caption" 
                      sx={{ 
                        ml: 2,
                        color: '#764ACB'
                      }}
                    >
                      {owner.type}
                    </Typography>
                  )}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
        );
      }

      return (
        <TextField
          key={key}
          fullWidth
          label={key}
          value={formData[key] || ''}
          onChange={(e) => handleFormChange(key, e.target.value)}
          sx={{ ...commonStyles.input, mb: 2 }}
        />
      );
    };

    return (
      <Dialog 
        open={editModalOpen} 
        onClose={handleModalClose}
        sx={commonStyles.dialog}
      >
        <DialogTitle sx={{ 
          borderBottom: '1px solid #444',
          color: '#fff',
          backgroundColor: '#2e2e3f',
          padding: '16px 24px'
        }}>
          {editType === 'item' ? 'Edit Item' : editType === 'npc' ? 'Edit NPC' : 'Edit Character'}
        </DialogTitle>
        <DialogContent sx={{ 
          p: 3,
          backgroundColor: '#1e1e2f'
        }}>
          {formData && (
            <Box sx={{ p: 2 }}>
              {Object.keys(formData)
                .filter(key => !nonEditableFields.includes(key))
                .map(key => renderField(key))}
            </Box>
          )}
        </DialogContent>
        <DialogActions sx={{ 
          borderTop: '1px solid #444',
          p: 2,
          backgroundColor: '#2e2e3f',
          '& .MuiButton-root': {
            textTransform: 'none',
            fontSize: '1rem',
            padding: '6px 16px'
          }
        }}>
          <Button 
            onClick={handleModalClose}
            variant="outlined"
            sx={{
              color: '#fff',
              borderColor: '#444',
              '&:hover': { 
                borderColor: '#764ACB',
                backgroundColor: 'rgba(118, 74, 203, 0.1)'
              }
            }}
          >
            Cancel
          </Button>
          <Button 
            onClick={handleUpdate}
            variant="contained"
            sx={{
              backgroundColor: '#764ACB',
              color: '#fff',
              '&:hover': { 
                backgroundColor: '#9865f7'
              }
            }}
          >
            Save Changes
          </Button>
        </DialogActions>
      </Dialog>
    );
  };

  const Section = ({ title, items, createPath, createText }) => (
    <Box sx={{
      mb: 4,
      backgroundColor: '#2e2e3f',
      p: 2,
      borderRadius: '8px',
      border: '1px solid #444',
      height: '345px'
    }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Typography variant="h5" sx={{ color: '#fff' }}>{title}</Typography>
        <Button
          variant="contained"
          component={Link}
          to={`${createPath}?gameId=${gameId}`}
          startIcon={<AddIcon />}
          sx={{
            backgroundColor: '#764ACB',
            '&:hover': { backgroundColor: '#9865f7' }
          }}
        >
          {createText}
        </Button>
      </Box>
      <Grid2 container spacing={2}>
        {items.map((item, index) => (
          <Grid2 item xs={12} sm={6} md={3} key={index}>
            <Tooltip title={item.Abilities || 'No description available'} arrow>
              <Card 
                onClick={() => handleItemClick(item)}
                sx={{ 
                  backgroundColor: '#1e1e2f', 
                  color: '#fff',
                  border: '1px solid #444',
                  height: '95%',
                  cursor: 'pointer',
                  transition: 'border-color 0.2s',
                  '&:hover': {
                    borderColor: '#764ACB'
                  }
                }}
              >
                <Box sx={{
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                  padding: '8px'
                }}>
                  <CardMedia
                    component="img"
                    height="135" 
                    image={item.Img || defaultItemImage} 
                    alt={item.ItemName}
                    className={`rarity-${item.Rarity} rarity-image`}
                    sx={{
                      objectFit: 'contain',
                      width: '128px'
                    }}
                  />
                </Box>
                <CardContent>
                  <Typography
                    variant="h6"
                    component="div"
                    className={`rarity-name-${item.Rarity}`}
                  >
                    {item.ItemName}
                  </Typography>
                  <Typography variant="body2" sx={{ color: '#bbb' }}>
                    Type: {item.Type}
                  </Typography>
                  <Typography variant="body2" sx={{ color: '#bbb' }}>
                    Value: {item.GoldValue}
                  </Typography>
                  <Typography variant="body2" sx={{ color: '#bbb' }}>
                    Owner: {item.OwnerName || 'Unassigned'}
                  </Typography>
                </CardContent>
              </Card>
            </Tooltip>
          </Grid2>
        ))}
      </Grid2>
    </Box>
  );

  return (
    // Update main container Box styling
    <Box sx={{
      p: 3,
      background: 'rgba(30, 30, 47, 0.9)',
      borderRadius: '8px',
      width: '1200px',
      margin: '100px auto -600px auto', // Increased top margin
      position: 'relative'
      // Removed minHeight calculation
    }}>
      <Typography variant="h4" sx={{ mb: 4, color: '#fff' }}>
        Game Master Dashboard
      </Typography>

      {/* Player Characters Section */}
      <Box sx={{
        mb: 4,
        backgroundColor: '#2e2e3f',
        p: 2,
        borderRadius: '8px',
        border: '1px solid #444',
        height: '345px'
      }}>
        <Typography variant="h5" sx={{ color: '#fff', mb: 2 }}>Player Characters</Typography>
        <Grid2 container spacing={2}>
          {playerCharacters.map((character, index) => (
            <Grid2 item xs={12} sm={6} md={3} key={index}>
              <Card 
                onClick={() => handleCharacterClick(character)}
                sx={{ 
                  backgroundColor: '#1e1e2f', 
                  color: '#fff',
                  border: '1px solid #444',
                  height: '100%',
                  cursor: 'pointer',
                  transition: 'border-color 0.2s',
                  '&:hover': {
                    borderColor: '#764ACB'
                  }
                }}
              >
                <Box sx={{
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                  padding: '8px'
                }}>
                  <CardMedia
                    component="img"
                    height="140"
                    image={character.Img || defaultCharacterImage}
                    alt={character.CharName}
                    sx={{
                      objectFit: 'contain',
                      width: '140px',
                      borderRadius: '3px'
                    }}
                  />
                </Box>
                <CardContent>
                  <Typography variant="h6" component="div">
                    {character.CharName}
                  </Typography>
                  <Typography variant="body2" sx={{ color: '#bbb' }}>
                    {character.Race} - Level {character.Level}
                  </Typography>
                  <Typography variant="body2" sx={{ color: '#bbb' }}>
                    {character.Job}
                  </Typography>
                </CardContent>
              </Card>
            </Grid2>
          ))}
        </Grid2>
      </Box>

      {/* NPCs Section */}
      <Box sx={{
        mb: 4,
        backgroundColor: '#2e2e3f',
        p: 2,
        borderRadius: '8px',
        border: '1px solid #444',
        height: '345px'
      }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
          <Typography variant="h5" sx={{ color: '#fff' }}>NPCs</Typography>
          <Button
            variant="contained"
            component={Link}
            to={`/create-npc?gameId=${gameId}`}
            startIcon={<AddIcon />}
            sx={{
              backgroundColor: '#764ACB',
              '&:hover': { backgroundColor: '#9865f7' }
            }}
          >
            Create NPC
          </Button>
        </Box>
        <Grid2 container spacing={2}>
          {npcs.map((npc, index) => (
            <Grid2 item xs={12} sm={6} md={3} key={index}>
              <Card 
                onClick={() => handleNpcClick(npc)}
                sx={{ 
                  backgroundColor: '#1e1e2f', 
                  color: '#fff',
                  border: '1px solid #444',
                  height: '100%',
                  cursor: 'pointer',
                  transition: 'border-color 0.2s',
                  '&:hover': {
                    borderColor: '#764ACB'
                  }
                }}
              >
                <Box sx={{
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                  padding: '8px'
                }}>
                  <CardMedia
                    component="img"
                    height="140"
                    image={npc.Img || defaultCharacterImage}
                    alt={npc.Name || 'NPC'}
                    sx={{
                      objectFit: 'contain',
                      width: '140px',
                      borderRadius: '3px'
                    }}
                  />
                </Box>
                <CardContent>
                  <Typography variant="h6" component="div">
                    {npc.Name}
                  </Typography>
                  <Typography variant="body2" sx={{ color: '#bbb' }}>
                    {npc.Race} - Level {npc.Level}
                  </Typography>
                  <Typography variant="body2" sx={{ color: '#bbb' }}>
                    Job: {npc.Job}
                  </Typography>
                  <Typography variant="body2" sx={{
                    color: npc.Allied === 0
                      ? '#1eff00'
                      : npc.Allied === 1
                        ? '#ffd100'
                        : '#ff0000'
                  }}>
                    Status: {npc.Allied === 0
                      ? 'Allied'
                      : npc.Allied === 1
                        ? 'Neutral'
                        : 'Enemy'}
                  </Typography>
                </CardContent>
              </Card>
            </Grid2>
          ))}
        </Grid2>
      </Box>

      {/* Items Section */}
      <Section
        title="Items"
        items={items}
        createPath="/create-item"
        createText="Create Item"
      />
      <EditModal />
    </Box>
  );
};

export default GameMasterPage;