import * as Yup from 'yup';
import TableMoreMenu from "@/components/table/TableMoreMenu"
import EditOutlinedIcon from '@mui/icons-material/EditOutlined';
import CachedOutlinedIcon from '@mui/icons-material/CachedOutlined';
import HistoryIcon from '@mui/icons-material/History';
import FindInPageOutlinedIcon from '@mui/icons-material/FindInPageOutlined';
import { Button, Card, Collapse, Grid, MenuItem, Paper, Stack, Table, TableCell, TableContainer, TableHead, TableRow, Typography } from "@mui/material"
import React, { Fragment, useEffect, useState } from "react";
import axios from "@/utils/axios";
import { useNavigate, useParams } from "react-router-dom";
import { RHFSelect, FormProvider } from '@/components/hook-form';
import DialogUpdateStatus from '@/components/DialogUpdateStatus'
import { MasterFormularium } from "./Type";
import { LoadingButton } from "@mui/lab";
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';

type Props = {
  props: MasterFormularium
}

export default function FormulariumRow({props} : Props) {
  const navigate = useNavigate();

  const [isDialogOpen, setDialogOpen] = useState(false);
  const [dataValue, setDataValue] = useState<MasterFormularium | null>(null);
  const [dataDescription, setDescriptionValue] = useState('');
  const [url, setUrl] = useState('');
  let titles = {
    name: 'Update Status',
    icon: '-'
  }
  type FormValuesProps = {
    value: string;
    active: boolean;
  };

  const handleActivate = (isOpen: boolean, dataValue: MasterFormularium) => {
    setDialogOpen(isOpen);
    setDataValue(dataValue);
    setDescriptionValue("Are you sure to inactive this formularium ? ");
    setUrl(url);
  };

  const NewMasterFormSchema = Yup.object().shape({
    reason: Yup.string().required('Reason edit is required')
  });

  const methods = useForm<FormValuesProps>({
    resolver: yupResolver(NewMasterFormSchema)
  });

  const onSubmit = async (row: any) => {
    try {
      handleUpdate(dataValue?.active, dataValue?.id, row.reason)
    } catch (error: any) {
      console.log('data gagal');
    }

    const ascent = document?.querySelector('ascent');
    if (ascent != null) {
      ascent.innerHTML = '';
    }
  };

  const handleUpdate = (active: number, id: number, reason: string) => {
    
    if (active == 1) {
      active = 0
    } else {
      active = 1
    }

    axios
    .put(`/master/formularium-template/${id}/activation`, {
      active: active,
    })
    .then((res) => {
      window.location.reload();
    })
  }

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

  const getContent = () => (
    <>
      <Stack paddingX={2} paddingY={2}>
        <Typography variant='subtitle1'>Are you sure to Change this Formularium</Typography>
        <Stack>
          <Card>
            <Grid container paddingX={2} paddingY={2}>
              <Grid item xs={5} md={5}>
                <Typography variant="inherit">Formularium name</Typography>
              </Grid>
              <Grid item xs={7}>
                <Typography variant="subtitle1">{dataValue?.name}</Typography>
              </Grid>
            </Grid>
          </Card>

          <Typography marginTop={5} marginBottom={3} variant="subtitle1">Reason for update</Typography>
          <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
            <RHFSelect 
              name="reason"
              label="Reason for update"
            >
              <option value=""></option>
              <option value="Agreement changed">Agreement changed</option>
              <option value="Endorsement">Endorsement</option>
              <option value="Renewal">Renewal</option>
              <option value="Wrong Setting">Wrong Setting</option>
            </RHFSelect>
            <Stack
              alignItems='center'
              justifyContent='flex-end'
              direction={{xs: 'column', md: 'row'}}
              spacing={2}
              marginTop={5}
            >
              <Stack direction='row' spacing={1}>
                <Button
                  sx={{boxShadow: 'none'}}
                  variant='outlined'
                  size='medium'
                  fullWidth={true}
                  onClick={() => setDialogOpen(false)}
                >
                  Cancel
                </Button>
                {dataValue?.active == 1 ?
                  <LoadingButton
                    sx={{boxShadow: '0px 2px 4px rgba(0,0,0,0.1)'}}
                    type='submit'
                    variant='contained'
                    size='medium'
                    fullWidth={true}
                    loading={isSubmitting}
                    color='error'
                  >
                    Inactive
                  </LoadingButton> :
                  <LoadingButton
                    sx={{boxShadow: '0px 2px 4px rgba(0,0,0,0.1)'}}
                    type='submit'
                    variant='contained'
                    size='medium'
                    fullWidth={true}
                    loading={isSubmitting}
                    color='success'
                  >
                    Active
                  </LoadingButton>
                }
              </Stack>
            </Stack>
          </FormProvider>
        </Stack>
      </Stack>
    </>
  )

  return (
    <Fragment>
      <TableRow>
        <TableCell align="left" width={50}></TableCell>
        <TableCell align="left">{props.name}</TableCell>
        <TableCell align="left">{props.description}</TableCell>
        <TableCell align="center" width={100}>
          <TableMoreMenu actions = {
            <>
              <MenuItem onClick={() => navigate(`/master/formularium-template-v2/${props.id}/detail`, {state: { isActive: props.active }})}>
                <FindInPageOutlinedIcon />
                Detail
              </MenuItem>
              <MenuItem onClick={() => navigate(`/master/formularium-template-v2/${props.id}/edit`)}>
                <EditOutlinedIcon />
                Edit
              </MenuItem>
              <MenuItem onClick={() => handleActivate(true, {
                id: props.id,
                name: props.name,
                description: props.description,
                active: props.active
              })
              }>
                <CachedOutlinedIcon />
                Update Status
              </MenuItem>
              <MenuItem onClick={() => navigate(`/master/formularium-template-v2/${props.id}/history`)}>
                <HistoryIcon />
                History
              </MenuItem>
            </>
          } />
        </TableCell>
      </TableRow>
      <DialogUpdateStatus 
        openDialog={isDialogOpen} 
        setOpenDialog={setDialogOpen} 
        description={dataDescription}
        title={titles}
        data={dataValue}
        content={getContent()}     
      />
    </Fragment>
  )
}