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 defaultItemImage from '../assets/default-item.png';

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

  const [formData, setFormData] = useState({
    ItemName: '',        // Match DB column names exactly
    Type: '',
    Art: '',
    Rarity: 1,
    MaxDurability: 100,
    CurrentDurability: 100,
    GoldValue: 0,
    Abilities: '',
    AP: 0,
    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();

    // Add all form fields with exact column names
    Object.keys(formData).forEach(key => {
        // Convert null values to empty strings to prevent SQL issues
        formDataToSend.append(key, formData[key] === null ? '' : formData[key]);
    });

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

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

        if (response.status === 201) {
            navigate(`/games/${gameId}/master`);
        }
    } catch (error) {
        console.error('Error creating item:', 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' }}>
      <Button
        onClick={() => navigate(`/games/${gameId}/master`)}
        variant="contained"
        sx={{
          backgroundColor: '#764ACB',
          '&:hover': { backgroundColor: '#9865f7' },
          mb: 3
        }}
      >
        Back to Game
      </Button>

      <form onSubmit={handleSubmit}>
        <Grid2 container spacing={3}>
          {/* Left Column - Image and Basic Info */}
          <Grid2 item xs={12} md={4}>
            <Box sx={{ border: '1px solid #444', borderRadius: '3px', p: 2, backgroundColor: '#2e2e3f', width: '330px' }}>
              <Card sx={{ backgroundColor: '#1e1e2f', color: '#fff' }}>
                {/* Image Upload Section */}
                {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="Item 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' }
                      }}
                    >
                      Upload Item Image
                    </Button>
                  </Box>
                )}

                {/* Basic Item Info */}
                <CardContent sx={{ p: 3 }}>
                  <TextField
                    fullWidth
                    label="Item Name"
                    name="ItemName"  // Changed from itemName
                    value={formData.ItemName}
                    onChange={handleChange}
                    required
                    sx={{ ...inputStyles, mb: 2 }}
                  />

                  <Grid2 container spacing={2}>
                    <Grid2 item xs={6}>
                      <FormControl fullWidth sx={{ mb: 2, width: '140px' }}>  {/* Width for "Consumable" + padding */}
                        <InputLabel sx={{ color: '#fff' }}>Type</InputLabel>
                        <Select
                          name="Type"
                          value={formData.Type}
                          onChange={handleChange}
                          required
                          sx={{ ...inputStyles }}
                        >
                          <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>
                    </Grid2>
                    <Grid2 item xs={6}>
                      <FormControl fullWidth sx={{ mb: 2, width: '120px' }}>  {/* Width for "Potion" + padding */}
                        <InputLabel sx={{ color: '#fff' }}>Art</InputLabel>
                        <Select
                          name="Art"
                          value={formData.Art}
                          onChange={handleChange}
                          required
                          sx={{ ...inputStyles }}
                        >
                          <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>
                    </Grid2>
                  </Grid2>

                  <TextField
                    fullWidth
                    label="Gold Value"
                    name="GoldValue"
                    type="number"
                    value={formData.GoldValue}
                    onChange={handleChange}
                    required
                    sx={{ ...inputStyles, mb: 2 }}
                  />
                </CardContent>
              </Card>
            </Box>
          </Grid2>

          {/* Right Column - Details */}
          <Grid2 item xs={12} md={8}>
            {/* Item Properties */}
            <Box sx={{ mb: 4 }}>
              <Typography variant="h5" sx={{ color: '#fff', mb: 2 }}>Item Properties</Typography>
              <Box sx={{ backgroundColor: '#2e2e3f', p: 2, borderRadius: '8px', border: '1px solid #444', width: '800px', justifyItems: 'center' }}>  
                <Grid2 container spacing={2}>
                  <Grid2 item xs={12} md={4}>
                    <FormControl fullWidth sx={{ mb: 2, width: '160px' }}>  {/* Width for "Legendary" + padding */}
                      <InputLabel sx={{ color: '#fff' }}>Rarity</InputLabel>
                      <Select
                        name="Rarity"
                        value={formData.Rarity}
                        onChange={handleChange}
                        required
                        sx={{ ...inputStyles }}
                      >
                        <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>
                  </Grid2>
                  <Grid2 item xs={12} md={4}>
                    <TextField
                      fullWidth
                      label="Attack Power"
                      name="AP"
                      type="number"
                      value={formData.AP}
                      onChange={handleChange}
                      sx={{ ...inputStyles }}
                    />
                  </Grid2>
                  <Grid2 item xs={12} md={4}>
                    <TextField
                      fullWidth
                      label="Max Durability"
                      name="MaxDurability"
                      type="number"
                      value={formData.MaxDurability}
                      onChange={handleChange}
                      required
                      sx={{ ...inputStyles }}
                    />
                  </Grid2>
                </Grid2>
              </Box>
            </Box>

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

            {/* Submit Button */}
            <Button
              type="submit"
              variant="contained"
              fullWidth
              sx={{
                backgroundColor: '#764ACB',
                '&:hover': { backgroundColor: '#9865f7' },
                mt: 3
              }}
            >
              Create Item
            </Button>
          </Grid2>
        </Grid2>
      </form>
    </Box>
  );
};

export default CreateItem;