import { Button, Card, Grid, Stack, Typography, FormControl, InputLabel, Select, FormHelperText, MenuItem } from "@mui/material";
import { useEffect, useMemo, useState } from 'react';
import { useSnackbar } from 'notistack';
import { useNavigate, useParams } from 'react-router-dom';
import axios from '../../../utils/axios';

type Props = {
  isEdit: boolean;
};

export default function CorporateHospitalForm({ isEdit }: Props) {

  const { enqueueSnackbar } = useSnackbar();
  const navigate = useNavigate();
  const { corporate_id, id, organization_id } = useParams();
  const [dataHospital, setDataHospital] = useState(null);
  let idHospital = organization_id && isEdit ? organization_id : 0;
  const [indexData, setIndexData] = useState(idHospital);
  const [updateData, setUpdateData] = useState(null);
  const [dataDefault, setDataDefault] = useState(null);

  useEffect(() => {
    axios.get('/corporates/' + corporate_id + '/hospitals/data')
    .then((res) => {
      setDataHospital(res.data);
      const data = {
        corporate_id : corporate_id ? corporate_id : null,
        organization_id : res.data[0] ? res.data[0].id : null,
        code : res.data[0] ? res.data[0].code : null,
        name : res.data[0] ? res.data[0].name : null,
      }
      setDataDefault(data);
    })
    
  }, [isEdit]);

  const [addData, setAddData] = useState(dataDefault);

  const handlePageChange = (index:any) => {
    setIndexData(index);
    const data = {
      corporate_id : corporate_id ? corporate_id : null,
      organization_id : dataHospital ? dataHospital[index].id : null,
      code : dataHospital ? dataHospital[index].code : null,
      name : dataHospital ? dataHospital[index].name : null,
    }
    setAddData(data);
    
  }
  const handleSaveData = () => {
    //Save data
    axios
    .post('/corporates/'+corporate_id+'/hospitals/save', (addData ? addData : dataDefault))
    .then((response) => {
      if(response.data)
      {
        enqueueSnackbar('Data saved successfully', { variant: 'success' });
      }
    })
    .catch((error) => {
      enqueueSnackbar('Failed to add data', { variant: 'error' });
    });
  }  
  
  const handlePageChangeUpdate = (id: any) => {
    setIndexData(id);
    const foundData = dataHospital?.find(item => item.id === id);
    const dataUpdate = {
      corporate_id : corporate_id ? corporate_id : null,
      organization_id : dataHospital ? foundData.id : null,
      code : dataHospital ? foundData.code : null,
      name : dataHospital ? foundData.name : null,
    }
    setUpdateData(dataUpdate);
  }

  const handleUpdateData = () => {
    //Update data
    if(updateData)
    {
      axios
      .put('/corporates/'+corporate_id+'/hospitals/'+id+'/edit', updateData)
      .then((response) => {
        if(response.data)
        {
          enqueueSnackbar('Data updated successfully', { variant: 'success' });
          navigate(-1);
          window.history.replaceState(null, '', '/corporates/'+corporate_id+'/hospitals');
        }
      })
      .catch((error) => {
        enqueueSnackbar('Failed to update data', { variant: 'error' });
      });
    }
    else
    {
      enqueueSnackbar('Data has not changed.', { variant: 'error' });
    }
    
  } 

  return (
    <Stack>
      <Card sx={{ p: 2 }}>
        <Stack spacing={2} direction='column'>
          <Typography variant='subtitle1'>Hospital *</Typography>
          {dataHospital && dataHospital.length > 0 ? (
            isEdit ? (
              <FormControl>
                <InputLabel htmlFor="id_hospital" required>
                  Hospital
                </InputLabel>
                <Select
                  id="id_hospital"
                  value={dataHospital && dataHospital.length > 0 ? indexData : ''}
                  fullWidth
                  label="Hospital"
                  onChange={(e) => {
                    handlePageChangeUpdate(e.target.value);
                  }}
                  
                >
                  {dataHospital?.map((data, index) => (
                    <MenuItem key={index} value={data.id}>{data.name}</MenuItem>
                  ))}
                </Select>
                <FormHelperText style={{ color: 'red' }}></FormHelperText>
              </FormControl>
            ) : (
              <FormControl>
                <InputLabel htmlFor="id_hospital" required>
                  Hospital
                </InputLabel>
                <Select
                  id="id_hospital"
                  value={dataHospital && dataHospital.length > 0 ? indexData : ''}
                  fullWidth
                  label="Hospital"
                  onChange={(e) => {
                    handlePageChange(e.target.value);
                  }}
                  
                >
                  {dataHospital?.map((data, index) => (
                    <MenuItem key={index} value={index}>{data.name}</MenuItem>
                  ))}
                </Select>
                <FormHelperText style={{ color: 'red' }}></FormHelperText>
              </FormControl>
            )
          ) : (
            <Typography variant='body2' style={{ position: 'relative', margin: 'auto', width: 'fit-content' }}>
              Loading
            </Typography>

          )}
          
          <Stack direction='row' spacing={2} justifyContent='flex-end'>
            <Button variant="outlined" sx={{color: '#212B36'}} onClick={() => navigate(-1)}>Cancel</Button>
            {isEdit ? (
              <Button sx={{backgroundColor: '#19BBBB'}} variant="contained" onClick={() => handleUpdateData()}>Save</Button>
            ):(
              <Button sx={{backgroundColor: '#19BBBB'}} variant="contained" onClick={() => handleSaveData()}>Save</Button>
            )}
            
          </Stack>
        </Stack>
    </Card>
    </Stack>
  );
}
