import * as Yup from 'yup';
import { useForm } from "react-hook-form";
import { FormProvider, RHFSelect } from "../../../../components/hook-form";
import { Button, Card, Grid, Typography } from "@mui/material";
import { Stack, fontWeight } from "@mui/system";
import { useNavigate, useParams } from "react-router";
import React, { useEffect, useMemo } from "react";
import { DetailCorpFormularium } from "./Types";
import axios from "@/utils/axios";
import { LoadingButton } from "@mui/lab";
import { enqueueSnackbar } from "notistack";
import { yupResolver } from '@hookform/resolvers/yup';


export default function CorporateFormulariumCreateForm() {
  const navigate = useNavigate();
  const { corporate_id } = useParams();

  const NewCorporaeFormulariumSchema = Yup.object().shape({
    id: Yup.string().required('required'),
  });

  const methods = useForm({
    resolver: yupResolver(NewCorporaeFormulariumSchema),
  });

  const onSubmit = async (data: any) => {
    await axios
      .post(`/corporates/${corporate_id}/formulariums`, data)
      .then((res) => {
        console.log(res.data.message)
        enqueueSnackbar('Formularium created successfully', { variant: 'success'})
      })
      .then((res) => {
        navigate(`/corporates/${corporate_id}/formulariums/`, { replace: true })
      })
      .catch(({ response }) => {
        if (response.status === 422) {
          for (const [key, value] of Object.entries(response.data.errors)) {
            setError(key, {message: value[0]});
            enqueueSnackbar(value[0] ?? 'Failed Processing Request', { variant: 'error' });
          }
        }
        else {
          enqueueSnackbar('Create Failed: '+ response.data.message, { variant: "error"})
        }
      });
  };

  const {
    setError,
    handleSubmit,
    formState: { isSubmitting }
  } = methods;

  // Data Dummy
  const options = ["Dummy 1", "Dummy 2", "Dummy 3"];

  const [dataDropdownIsLoading, setDataDropdownLoading] = React.useState(true);
  const [dataDropdownData, setDataDropdownData] = React.useState<DetailCorpFormularium[] | null>(null)
  const loadDataDropdown = async () => {
    setDataDropdownLoading(true);
    const resp = await axios.get(`corporates/${corporate_id}/formulariums-create`);
    console.log(resp.data);
    setDataDropdownLoading(false);

    setDataDropdownData(resp.data.data)
  };

  useEffect(() => {
    loadDataDropdown();
  }, [])

  return (
    <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
      <Grid item xs={12}>
        <Card sx={{p:2}}>
          <Stack spacing={3}>
            <Typography variant="h6">Formularium Name*</Typography>
            <RHFSelect name="id" label="Category" placeholder="Category" fullWidth={true}>
              <option value=""/>
              {dataDropdownData?.map((item, index) => (
                <option key={index} value={item.id}>
                  {item.name}
                </option>
              ))}
            </RHFSelect>
          </Stack>
        </Card>
        <Stack direction="row" spacing={4} sx={{marginTop: '40px'}}>
          <Grid container item xs={12} md={12} justifyContent="flex-end" sx={{p:2}}>
            <Button
              variant="outlined"
              onClick={() => navigate(`/corporates/${corporate_id}/formulariums/`)}
              sx={{
                p: 1,
                fontWeight: 'bold',
                color: 'black',
                outlineColor: 'black',
                marginRight: '20px',
                width: 100
              }}
            >
              Cancel
            </Button>
            
            <LoadingButton
              loading={isSubmitting}
              type='submit'
              variant="contained"
              sx={{
                p: 1,
                fontWeight: 'bold',
                backgroundColor: '#19BBBB', 
                color: '#FFF',
                "&:hover":{
                  backgroundColor: '#19BBBB', color: '#FFF',
                },
                width: 100
              }}
            >
              Create
            </LoadingButton>
          </Grid>
        </Stack>
      </Grid>

    </FormProvider>
  )
}