import React, { useState, useEffect, useContext } from 'react';
import { Link } from 'react-router-dom';
import { UserContext } from '../context/UserContext';
import axios from 'axios';
import { Box, Typography, Grid2, Card, CardContent, CardMedia } from '@mui/material';
import defaultCharacterImage from '../assets/default-character.png';

const Profile = () => {
  const { userId, username } = useContext(UserContext);
  const [characters, setCharacters] = useState([]);

  useEffect(() => {
    const fetchCharacters = async () => {
      try {
        const response = await axios.get(`http://localhost:5000/games/${userId}/characters`);
        const charactersArray = Object.values(response.data);
        setCharacters(charactersArray);
      } catch (error) {
        console.error('Error fetching characters:', error);
      }
    };

    if (userId) {
      fetchCharacters();
    }
  }, [userId]);

  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h4" sx={{ mb: 4, color: '#fff' }}>
        Benutzerprofil: {username}
      </Typography>

      <Typography variant="h5" sx={{ mb: 2, color: '#fff' }}>
        Your Characters
      </Typography>

      <Grid2 container spacing={3}>
        {characters.map((character) => (
          <Grid2 item xs={12} sm={6} md={4} key={character.CharID}>
            <Link to={`/games/${character.GameID}`} style={{ textDecoration: 'none' }}>
              <Card sx={{ border: '1px solid #444', backgroundColor: '#2e2e3f', color: '#fff', cursor: 'pointer' }}>
                <CardMedia
                  component="img"
                  height="200"
                  image={character.Img || defaultCharacterImage}
                  alt={character.CharName}
                />
                <CardContent>
                  <Typography variant="h6" component="div" sx={{ color: '#fff', mb: 1 }}>
                    {character.CharName}
                  </Typography>
                  <Typography variant="body2" sx={{ color: '#bbb', mb: 0.5 }}>
                    Race: {character.Race}
                  </Typography>
                  <Typography variant="body2" sx={{ color: '#bbb' }}>
                    Age: {character.Age}
                  </Typography>
                </CardContent>
              </Card>
            </Link>
          </Grid2>
        ))}
      </Grid2>
    </Box>
  );
};

export default Profile;