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

export default function AddOrEditProviderForm({ onAdd, initialData, onCancel }) {
  const [provider, setProvider] = useState({
    name: '',
    email: '',
    phone: '',
    location: '',
    category: '',
  });

  useEffect(() => {
    if (initialData) {
      setProvider(initialData);
    } else {
      setProvider({
        name: '',
        email: '',
        phone: '',
        location: '',
        category: '',
      });
    }
  }, [initialData]);

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

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

  return (
    <Box sx={{ px: 2, py: 3 }}>
      <Box display="flex" flexDirection={{ xs: 'column', md: 'row' }} gap={4}>
        <Box flex={1}>
          <TextField
            fullWidth
            label="Name"
            name="name"
            value={provider.name}
            onChange={handleChange}
            margin="normal"
          />
          <TextField
            fullWidth
            label="Email"
            name="email"
            type="email"
            value={provider.email}
            onChange={handleChange}
            margin="normal"
          />
          <TextField
            fullWidth
            label="Phone"
            name="phone"
            value={provider.phone}
            onChange={handleChange}
            margin="normal"
          />
          <TextField
            fullWidth
            label="Location"
            name="location"
            value={provider.location}
            onChange={handleChange}
            margin="normal"
          />
          <TextField
            fullWidth
            label="Category"
            name="category"
            value={provider.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>
  );
}
