use axios instead : import React, { useState, useEffect } from 'react';
import {
  Box,
  TextField,
  Button,
  Typography,
  Grid,
  IconButton,
  Stack,
  Alert,
} from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete';
import AddIcon from '@mui/icons-material/Add';

const SpecialiteForm = () => {
  const [formData, setFormData] = useState({
    title: '',
    buttons: [''],
    description: '',
    image: null,
    image_path: '',
    section_title: '',
    section_description: '',
    cta_button: '',
  });
  const [preview, setPreview] = useState('');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  useEffect(() => {
    const timer = setTimeout(() => {
      setError('');
      setSuccess('');
    }, 5000);
    return () => clearTimeout(timer);
  }, [error, success]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('http://127.0.0.1:8000/specialite-page');
        const result = await response.json();
        if (result.status === 'success') {
          const data = result.data;
          setFormData({
            ...data,
            buttons: JSON.parse(data.buttons),
            image: null,
          });
          if (data.image_path) {
            setPreview(`http://127.0.0.1:8000/storage/${data.image_path}`);
          }
        }
      } catch (err) {
        setError('Failed to load existing data');
      }
    };
    fetchData();
  }, []);

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

  const handleImageChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      if (file.size > 2048000) {
        setError('Image size should be less than 2MB');
        return;
      }
      if (!['image/jpeg', 'image/png', 'image/jpg', 'image/gif', 'image/svg+xml'].includes(file.type)) {
        setError('Invalid file type. Please upload an image (JPEG, PNG, JPG, GIF, SVG)');
        return;
      }
      setFormData((prev) => ({ 
        ...prev, 
        image: file,
      }));
      setPreview(URL.createObjectURL(file));
    }
  };

  const handleButtonAdd = () => {
    setFormData((prev) => ({
      ...prev,
      buttons: [...prev.buttons, ''],
    }));
  };

  const handleButtonRemove = (index) => {
    setFormData((prev) => ({
      ...prev,
      buttons: prev.buttons.filter((_, i) => i !== index),
    }));
  };

  const handleButtonChange = (index, value) => {
    setFormData((prev) => ({
      ...prev,
      buttons: prev.buttons.map((button, i) => (i === index ? value : button)),
    }));
  };

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

    Object.keys(formData).forEach(key => {
      if (key === 'buttons') {
        formDataToSend.append(key, JSON.stringify(formData[key]));
      } else if (key === 'image' && formData[key]) {
        formDataToSend.append(key, formData[key]);
      } else if (key !== 'image_path' && key !== 'image') {
        formDataToSend.append(key, formData[key]);
      }
    });

    try {
      const response = await fetch('http://127.0.0.1:8000/specialite-page', {
        method: 'POST',
        body: formDataToSend,
      });
      const result = await response.json();
      
      if (result.status === 'success') {
        setSuccess('Specialite page updated successfully');
        if (result.data.image_path) {
          setPreview(`http://127.0.0.1:8000/storage/${result.data.image_path}`);
          setFormData(prev => ({
            ...prev,
            image_path: result.data.image_path,
            image: null
          }));
        }
      } else {
        setError('Failed to update specialite page');
      }
    } catch (err) {
      setError('An error occurred while submitting the form');
    }
  };

  return (
    <Box>
      <Typography variant="h4" gutterBottom>
        Specialite Page Settings
      </Typography>

      {error && <Alert severity="error" sx={{ mb: 2 }}>{error}</Alert>}
      {success && <Alert severity="success" sx={{ mb: 2 }}>{success}</Alert>}

      <form onSubmit={handleSubmit}>
        <Grid container spacing={3}>
          <Grid item xs={12}>
            <TextField
              fullWidth
              label="Title"
              name="title"
              value={formData.title}
              onChange={handleInputChange}
              required
            />
          </Grid>

          <Grid item xs={12}>
            <TextField
              fullWidth
              multiline
              rows={4}
              label="Description"
              name="description"
              value={formData.description}
              onChange={handleInputChange}
              required
            />
          </Grid>

          <Grid item xs={12}>
            <Typography variant="subtitle1" gutterBottom>
              Buttons
            </Typography>
            {formData.buttons.map((button, index) => (
              <Stack
                key={index}
                direction="row"
                spacing={2}
                sx={{ mb: 2 }}
                alignItems="center"
              >
                <TextField
                  fullWidth
                  label={`Button ${index + 1}`}
                  value={button}
                  onChange={(e) => handleButtonChange(index, e.target.value)}
                  required
                />
                <IconButton
                  onClick={() => handleButtonRemove(index)}
                  disabled={formData.buttons.length === 1}
                >
                  <DeleteIcon />
                </IconButton>
              </Stack>
            ))}
            <Button
              startIcon={<AddIcon />}
              onClick={handleButtonAdd}
              variant="outlined"
              sx={{ mb: 2 }}
            >
              Add Button
            </Button>
          </Grid>

          <Grid item xs={12}>
            <Button
              variant="contained"
              component="label"
              fullWidth
              sx={{ mb: 2 }}
            >
              Upload Image
              <input
                type="file"
                hidden
                accept="image/*"
                onChange={handleImageChange}
              />
            </Button>
            {preview && (
              <Box sx={{ mt: 2, mb: 2 }}>
                <Typography variant="subtitle2" gutterBottom>
                  {formData.image ? 'New Image Preview:' : 'Current Image:'}
                </Typography>
                <img
                  src={preview}
                  alt="Preview"
                  style={{ 
                    maxWidth: '100%', 
                    maxHeight: '200px',
                    border: '1px solid #ddd',
                    borderRadius: '4px',
                    padding: '4px'
                  }}
                />
              </Box>
            )}
          </Grid>

          <Grid item xs={12}>
            <TextField
              fullWidth
              label="Section Title"
              name="section_title"
              value={formData.section_title}
              onChange={handleInputChange}
              required
            />
          </Grid>

          <Grid item xs={12}>
            <TextField
              fullWidth
              multiline
              rows={4}
              label="Section Description"
              name="section_description"
              value={formData.section_description}
              onChange={handleInputChange}
              required
            />
          </Grid>

          <Grid item xs={12}>
            <TextField
              fullWidth
              label="CTA Button"
              name="cta_button"
              value={formData.cta_button}
              onChange={handleInputChange}
              required
            />
          </Grid>

          <Grid item xs={12}>
            <Button
              type="submit"
              variant="contained"
              color="primary"
              size="large"
              fullWidth
            >
              Save Changes
            </Button>
          </Grid>
        </Grid>
      </form>
    </Box>
  );
};

export default SpecialiteForm;