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 } 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([]);

  // Fix useEffect data fetching
  useEffect(() => {
    const fetchData = async () => {
      try {
        // Fetch player characters
        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));

        // Fetch NPCs with different structure
        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));

        // Fetch Items
        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);
      }
    };

    fetchData();
    const interval = setInterval(fetchData, 5000);
    return () => clearInterval(interval);
  }, [gameId]);

  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}>
            <Card sx={{
              backgroundColor: '#1e1e2f',
              color: '#fff',
              height: '95%', // Reduced height
              border: '1px solid #444',
            }}>
              <Box sx={{
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                padding: '8px'
              }}>
                <CardMedia
                  component="img"
                  height="135" // Reduced from 140
                  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>
          </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 sx={{
                backgroundColor: '#1e1e2f',
                color: '#fff',
                border: '1px solid #444',
                height: '100%'
              }}>
                <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 sx={{
                backgroundColor: '#1e1e2f',
                color: '#fff',
                border: '1px solid #444',
                height: '100%'
              }}>
                <Box sx={{
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                  padding: '8px'
                }}>
                  <CardMedia
                    component="img"
                    height="140"
                    image={npc.Img || defaultCharacterImage}
                    alt={npc.CharName}
                    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"
      />
    </Box>
  );
};

export default GameMasterPage;