import React, { useState, useContext } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { UserContext } from '../context/UserContext';
import axios from 'axios';
import { Box, TextField, Button, Typography, Select, MenuItem, FormControl, InputLabel, Grid2, Card, CardContent, CardMedia } from '@mui/material';

// Import the same icons as games.jsx
import PaidIcon from '@mui/icons-material/Paid';
import CalendarTodayIcon from '@mui/icons-material/CalendarToday';
import PetsIcon from '@mui/icons-material/Pets';
import WcIcon from '@mui/icons-material/Wc';
import WorkIcon from '@mui/icons-material/Work';
import HeartIcon from '@mui/icons-material/Favorite';
import WaterDropIcon from '@mui/icons-material/WaterDrop';
import KeyboardDoubleArrowUpIcon from '@mui/icons-material/KeyboardDoubleArrowUp';
import SecurityIcon from '@mui/icons-material/Security';

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

const CreateNpc = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { userId } = useContext(UserContext);
  const gameId = new URLSearchParams(location.search).get('gameId');

  const [formData, setFormData] = useState({
    Name: '',
    Race: '',
    Sex: '',
    Age: '',
    Job: '',
    Description: '',
    MaxHealth: 100,
    MaxMana: 100,
    Strength: 10,
    Dexterity: 10,
    Agility: 10,
    Endurance: 10,
    Allied: 0, // 0 = Allied, 1 = Neutral, 2 = Enemy
    Level: 1,
    GameID: gameId
  });

  const [selectedImage, setSelectedImage] = useState(null);
  const [imagePreview, setImagePreview] = useState(null);

  const handleChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    });
  };

  const handleImageChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      setSelectedImage(file);
      setImagePreview(URL.createObjectURL(file));
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const formDataToSend = new FormData();

    Object.keys(formData).forEach(key => {
      formDataToSend.append(key, formData[key]);
    });

    if (selectedImage) {
      formDataToSend.append('image', selectedImage);
    }

    try {
      const response = await axios.post(
        'http://localhost:5000/games/npc/create',
        formDataToSend,
        {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
      );

      if (response.status === 201) {
        navigate(`/games/${gameId}/master`);
      }
    } catch (error) {
      console.error('Error creating NPC:', error);
    }
  };

  const inputStyles = {
    '& .MuiOutlinedInput-root': {
      '& fieldset': { borderColor: '#444' },
      '&:hover fieldset': { borderColor: '#764ACB' },
      '&.Mui-focused fieldset': { borderColor: '#764ACB' },
    },
    '& .MuiInputLabel-root': { color: '#fff' },
    '& .MuiInputBase-input': { color: '#fff' }
  };

  return (
    <Box sx={{ p: 3, background: 'rgba(30, 30, 47, 0.9)', borderRadius: '8px', marginTop: '40px' }}>

      <form onSubmit={handleSubmit}>
        <Grid2 container spacing={3}>
          {/* NPC Image and Basic Info */}
          <Grid2 item xs={12} md={4}>
            <Box sx={{ border: '1px solid #444', borderRadius: '3px', p: 2, backgroundColor: '#2e2e3f' }}>
              <Card sx={{ width: '400px', backgroundColor: '#1e1e2f', color: '#fff', height: '635px' }}>
                {/* Image Upload Section - Similar to CreateCharacter */}
                {imagePreview ? (
                  <Box component="label" htmlFor="image-upload" sx={{ cursor: 'pointer', position: 'relative' }}>
                    <input
                      accept="image/*"
                      type="file"
                      id="image-upload"
                      style={{ display: 'none' }}
                      onChange={handleImageChange}
                    />
                    <CardMedia
                      component="img"
                      height="300"
                      image={imagePreview}
                      alt="NPC Preview"
                      sx={{ borderRadius: '3px', objectFit: 'contain', margin: '0 auto', borderBottom: '1px solid #444' }}
                    />
                  </Box>
                ) : (
                  <Box
                    component="label"
                    htmlFor="image-upload"
                    sx={{
                      height: 300,
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      backgroundColor: '#2e2e3f',
                      borderRadius: '3px',
                      cursor: 'pointer'
                    }}
                  >
                    <input
                      accept="image/*"
                      type="file"
                      id="image-upload"
                      style={{ display: 'none' }}
                      onChange={handleImageChange}
                    />
                    <Button
                      variant="contained"
                      component="span"
                      sx={{
                        backgroundColor: '#764ACB',
                        '&:hover': { backgroundColor: '#9865f7' }
                      }}
                    >
                      Bild Hochladen
                    </Button>
                  </Box>
                )}

                <CardContent sx={{ p: 3 }}>
                  <TextField
                    fullWidth
                    label="Name des NPCs"
                    name="Name"
                    value={formData.Name}
                    onChange={handleChange}
                    required
                    sx={{ ...inputStyles, mb: 2, width: '347px'}}
                  />

                  <Grid2 container spacing={2}>
                    <Grid2 item xs={6}>
                      <TextField
                        fullWidth
                        label="Alter"
                        name="Age"
                        type="number"
                        value={formData.Age}
                        onChange={handleChange}
                        required
                        sx={{ ...inputStyles, width: '165px' }}
                      />
                    </Grid2>
                    <Grid2 item xs={6}>
                      <TextField
                        fullWidth
                        label="Rasse"
                        name="Race"
                        value={formData.Race}
                        onChange={handleChange}
                        required
                        sx={{ ...inputStyles, width: '165px' }}
                      />
                    </Grid2>
                  </Grid2>

                  <Grid2 container spacing={2} sx={{ mt: 1 }}>
                    <Grid2 item xs={6}>
                      <FormControl sx={{ width: '165px' }}>
                        <InputLabel sx={{ color: '#fff' }}>Geschlecht</InputLabel>
                        <Select
                          name="Sex"
                          value={formData.Sex}
                          onChange={handleChange}
                          required
                          sx={{
                            color: '#fff',
                            '& .MuiOutlinedInput-notchedOutline': { borderColor: '#444' },
                            '&:hover .MuiOutlinedInput-notchedOutline': { borderColor: '#764ACB' },
                          }}
                        >
                          <MenuItem value="Male">Männlich</MenuItem>
                          <MenuItem value="Female">Weiblich</MenuItem>
                          <MenuItem value="Other">Divers</MenuItem>
                        </Select>
                      </FormControl>
                    </Grid2>
                    <Grid2 item xs={6}>
                      <FormControl sx={{ width: '165px' }}>
                        <InputLabel sx={{ color: '#fff' }}>Status</InputLabel>
                        <Select
                          name="Allied"
                          value={formData.Allied}
                          onChange={handleChange}
                          required
                          sx={{
                            color: '#fff',
                            '& .MuiOutlinedInput-notchedOutline': { borderColor: '#444' },
                            '&:hover .MuiOutlinedInput-notchedOutline': { borderColor: '#764ACB' },
                          }}
                        >
                          <MenuItem value={0}>Verbündet</MenuItem>
                          <MenuItem value={1}>Neutral</MenuItem>
                          <MenuItem value={2}>Feindlich</MenuItem>
                        </Select>
                      </FormControl>
                    </Grid2>
                  </Grid2>

                  <Grid2 container spacing={2} sx={{ mt: 1 }}>
                    <Grid2 item xs={6}>
                      <TextField
                        fullWidth
                        label="Beruf/Klasse"
                        name="Job"
                        value={formData.Job}
                        onChange={handleChange}
                        required
                        sx={{ ...inputStyles, width: '165px' }}
                      />
                    </Grid2>
                    <Grid2 item xs={6}>
                      <TextField
                        fullWidth
                        label="Level"
                        name="Level"
                        type="number"
                        value={formData.Level}
                        onChange={handleChange}
                        required
                        sx={{ ...inputStyles, width: '165px' }}
                      />
                    </Grid2>
                  </Grid2>
                </CardContent>
              </Card>
            </Box>
          </Grid2>

          {/* Right Column - Stats and Description */}
          <Grid2 item xs={12} md={8}>
            {/* Health/Mana Bars */}
            <Box sx={{ display: 'flex', gap: 2, mb: 4, width: '810px' }}>
              <Box sx={{ flex: 1, backgroundColor: '#2e2e3f', borderRadius: '8px', p: 2, border: '1px solid #444' }}>
                <Typography variant="body1" sx={{ display: 'flex', justifyContent: 'space-between', color: '#fff' }}>
                  <HeartIcon sx={{ color: "red" }} />
                  <span>Maximale Gesundheit</span>
                </Typography>
                <TextField
                  fullWidth
                  name="MaxHealth"
                  type="number"
                  value={formData.MaxHealth}
                  onChange={handleChange}
                  required
                  sx={inputStyles}
                />
              </Box>
              <Box sx={{ flex: 1, backgroundColor: '#2e2e3f', borderRadius: '8px', p: 2, border: '1px solid #444' }}>
                <Typography variant="body1" sx={{ display: 'flex', justifyContent: 'space-between', color: '#fff' }}>
                  <WaterDropIcon sx={{ color: 'blue' }} />
                  <span>Maximales Mana</span>
                </Typography>
                <TextField
                  fullWidth
                  name="MaxMana"
                  type="number"
                  value={formData.MaxMana}
                  onChange={handleChange}
                  required
                  sx={inputStyles}
                />
              </Box>
            </Box>

            {/* Description */}
            <Box sx={{ mb: 4, width: '810px' }}>
              <Typography variant="h5" sx={{ color: '#fff', mb: 2 }}>Beschreibung</Typography>
              <Box sx={{ backgroundColor: '#2e2e3f', p: 2, borderRadius: '8px', border: '1px solid #444' }}>
                <TextField
                  fullWidth
                  multiline
                  rows={4}
                  name="Description"
                  value={formData.Description}
                  onChange={handleChange}
                  sx={inputStyles}
                />
              </Box>
            </Box>

            {/* Stats */}
            <Box sx={{ mb: 4, width: '810px' }}>
              <Typography variant="h5" sx={{ color: '#fff', mb: 2 }}>Attribute</Typography>
              <Box sx={{
                backgroundColor: '#2e2e3f',
                p: 2,
                borderRadius: '8px',
                border: '1px solid #444'
              }}>
                <Grid2 container spacing={2} justifyContent="space-between">
                  <Grid2 item>
                    <TextField
                      label="Stärke"
                      name="Strength"
                      type="number"
                      value={formData.Strength}
                      onChange={handleChange}
                      sx={{ ...inputStyles, width: '180px' }}
                    />
                  </Grid2>
                  <Grid2 item>
                    <TextField
                      label="Geschicklichkeit"
                      name="Dexterity"
                      type="number"
                      value={formData.Dexterity}
                      onChange={handleChange}
                      sx={{ ...inputStyles, width: '180px' }}
                    />
                  </Grid2>
                  <Grid2 item>
                    <TextField
                      label="Beweglichkeit"
                      name="Agility"
                      type="number"
                      value={formData.Agility}
                      onChange={handleChange}
                      sx={{ ...inputStyles, width: '180px' }}
                    />
                  </Grid2>
                  <Grid2 item>
                    <TextField
                      label="Ausdauer"
                      name="Endurance"
                      type="number"
                      value={formData.Endurance}
                      onChange={handleChange}
                      sx={{ ...inputStyles, width: '180px' }}
                    />
                  </Grid2>
                </Grid2>
              </Box>
            </Box>

            {/* Button Container */}
            <Box sx={{ 
              display: 'flex', 
              justifyContent: 'space-between', 
              gap: 2, 
              width: '800px' 
            }}>
              <Button
                onClick={() => navigate(`/games/${gameId}/master`)}
                variant="contained"
                sx={{
                  backgroundColor: '#764ACB',
                  '&:hover': { backgroundColor: '#9865f7' },
                  width: '200px'
                }}
              >
                Zurück ohne Speichern
              </Button>
              <Button
                type="submit"
                variant="contained"
                sx={{
                  backgroundColor: '#764ACB',
                  '&:hover': { backgroundColor: '#9865f7' },
                  width: '580px'
                }}
              >
                NPC Erstellen
              </Button>
            </Box>
          </Grid2>
        </Grid2>
      </form>
    </Box>
  );
};

export default CreateNpc;