import { useState, useEffect } from 'react';
import { Box, Button, TextField, Grid, Avatar, Typography, Paper } from '@mui/material';
import { handleDecimalInputKeyDown } from '../../utils/validation';

export default function AddOrEditProductForm({ onAdd, initialData, onCancel }) {
  const [product, setProduct] = useState({
    name: '',
    price: '',
    provider: '',
    stock: '',
    category: '',
    representation: ''
  });

  useEffect(() => {
    if (initialData) {
      setProduct(initialData);
    } else {
      setProduct({
        name: '',
        price: '',
        provider: '',
        stock: '',
        category: '',
        representation: ''
      });
    }
  }, [initialData]);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setProduct((prev) => ({
      ...prev,
      [name]: name === 'price' || name === 'stock' ? Number(value) : value
    }));
  };

  const handleImageChange = (e) => {
    const file = e.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onloadend = () => {
      setProduct((prev) => ({ ...prev, representation: reader.result }));
    };
    reader.readAsDataURL(file);
  };

  const handleSubmit = () => {
    if (onAdd) {
      onAdd(product);
    }
  };

  return (
    <Box sx={{ px: 2, py: 3 }}>
      <Box display="flex" flexDirection={{ xs: 'column', md: 'row' }} gap={4}>
        {/* Left visual panel */}
        <Paper
          elevation={0}
          sx={{
            bgcolor: '#f9f9f9',
            p: 2,
            borderRadius: 2,
            flex: 1,
            minWidth: '400px',
          }}
        >
          <Typography variant="subtitle1" fontWeight={600} gutterBottom>
            {product.name || 'N/A'}
          </Typography>
          <Typography variant="body2" gutterBottom>
            {product.provider || 'N/A'}
          </Typography>
          <Typography variant="body2" gutterBottom>
            {product.price ? `$${product.price.toFixed(2)}` : '$0.00'}
          </Typography>
          {product.representation ? (
            <Avatar
              variant="rounded"
              src={product.representation}
              sx={{ width: '100%', height: 280, borderRadius: 2 }}
              imgProps={{ style: { objectFit: 'cover', width: '100%', height: '100%' } }}
            />
          ) : (
            <Box
              sx={{
                width: '100%',
                height: 240,
                bgcolor: '#e0e0e0',
                borderRadius: 2,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center'
              }}
            >
              <Typography variant="body2" color="text.secondary">Image Preview</Typography>
            </Box>
          )}
          <Box mt={2}>
            <Button component="label" className="button-transparent" fullWidth >
              Upload Image
              <input type="file" hidden accept="image/*" onChange={handleImageChange} />
            </Button>
          </Box>
        </Paper>

        {/* Right input panel */}
        <Box flex={1}>
          <TextField
            fullWidth
            label="Product Name"
            name="name"
            value={product.name}
            onChange={handleChange}
            margin="normal"
          />
          <TextField
            fullWidth
            label="Price"
            name="price"
            type="number"
            value={product.price}
            onChange={handleChange}
            margin="normal"
            onKeyDown={handleDecimalInputKeyDown}
          />
          <TextField
            fullWidth
            label="Provider"
            name="provider"
            value={product.provider}
            onChange={handleChange}
            margin="normal"
          />
          <TextField
            fullWidth
            label="Stock"
            name="stock"
            type="number"
            value={product.stock}
            onChange={handleChange}
            margin="normal"
            onKeyDown={handleDecimalInputKeyDown}
          />
          <TextField
            fullWidth
            label="Category"
            name="category"
            value={product.category}
            onChange={handleChange}
            margin="normal"
          />

          <Box display="flex" justifyContent="flex-end" gap={1} mt={3}>
            <Button onClick={onCancel} className='button-transparent'>Cancel</Button>
            <Button variant="contained" onClick={handleSubmit} className="button-gold">Save</Button>
          </Box>
        </Box>
      </Box>
    </Box>
  );
}