import { Button, FormLabel } from '@mui/material';
import FormControl from '@mui/material/FormControl';
import TextField from '@mui/material/TextField';
import { ChangeEvent, FormEvent, useState } from 'react';
import { getEmptyManufacturer } from '../../utils/DrugUtils';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import Manufacturer from '../../interfaces/Manufacturer';

export default function DrugFrom(props: { updateDrug?: Manufacturer }) {
  const [drug, setDrug] = useState(props.updateDrug ?? getEmptyManufacturer());
  const navigate = useNavigate();

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    setDrug({
      ...drug,
      [e.target.name]: e.target.value
    });
  };

  const handleSubmit = (e: FormEvent<HTMLElement>) => {
    e.preventDefault();
    if (drug.id === undefined || drug.id === -1) {
      addDrug(drug);
    } else {
      updateDrug(drug);
    }
  };

  const addDrug = async (drug: Manufacturer) => {
    try {
      drug.id = 0;
      axios.post(
        'https://silkroadapi.azurewebsites.net/Manufacturer/add-manufacturer',
        drug,
        { withCredentials: true }
      );
      navigate('/');
    } catch (error) {
      console.error(error);
    }
  };

  const updateDrug = async (drug: Manufacturer) => {
    try {
      axios.put(
        'https://silkroadapi.azurewebsites.net/Manufacturer/update-manufacturer',
        drug,
        { withCredentials: true }
      );
      navigate('/');
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <FormControl
        sx={{
          width: '70%',
          marginLeft: '15%',
          marginRight: '15%',
          marginBottom: '30px',
          marginTop: '30px'
        }}
      >
        <FormLabel>Name</FormLabel>
        <TextField
          type='text'
          required
          onChange={handleChange}
          name='name'
          title='Name'
          value={drug.name}
        />
        <FormLabel>Address</FormLabel>
        <TextField
          type='text'
          required
          onChange={handleChange}
          name='address'
          title='Address'
          value={drug.address}
        />
        <FormLabel>Contact</FormLabel>
        <TextField
          type='text'
          required
          onChange={handleChange}
          name='contact'
          title='Contact'
          value={drug.contact}
        />
        <Button variant='outlined' color='secondary' type='submit'>
          Submit
        </Button>
      </FormControl>
    </form>
  );
}
