// @mui
import { Box, Button, Card, Collapse, IconButton, InputLabel, MenuItem, OutlinedInput, Paper, Grid, Select, SelectChangeEvent, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, Typography, Badge, Tab, Tabs, CardHeader, Stack, Menu, ButtonGroup, Pagination } from '@mui/material';
import { LoadingButton } from "@mui/lab";
import { CachedOutlined, FindInPageOutlined } from '@mui/icons-material';
// hooks
import React, { ChangeEvent, Component, useEffect, useRef, useState } from 'react';
import useSettings from '../../../../hooks/useSettings';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
// components
import axios from '../../../../utils/axios';
import Label from '@/components/Label';
import TableMoreMenu from '@/components/table/TableMoreMenu';
import InfoDetail from "./InfoDetail";
import { DetailCorpFormularium } from "./Types";
import DialogUpdateStatus from '@/components/DialogUpdateStatus'
import { RHFSelect, FormProvider } from '@/components/hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { useForm } from 'react-hook-form';
import * as Yup from 'yup';
import { CorporateFormulariumList } from "./Types";

type ParamsDetail = {
  props: DetailCorpFormularium,
  formularium: CorporateFormulariumList,
}

export default function CategoryDetail({props, formularium} : ParamsDetail) {
  
  type FormValuesProps = {
    value: string;
    active: boolean;
  };
  const { corporate_id } = useParams();
  const [open, setOpen] = React.useState(false);
  const [isDialogOpen, setDialogOpen] = useState(false)
  let titles = {
    name: 'Update Status',
    icon: '-'
  }
  const [dataValue, setDataValue] = useState<CorporateFormulariumList | null>(null);
  const [dataDescription, setDescriptionValue] = useState('');
  const [url, setUrl] = useState('');

  const handleActivate = (isOpen: boolean, dataValue: CorporateFormulariumList) => {
    console.log(dataValue)
    setDialogOpen(isOpen)
    setDataValue(dataValue)
    setDescriptionValue('Are you sure to inactive this formularium ?')
    setUrl(url)
  };

  const NewCorporateSchema = Yup.object().shape({
    reason: Yup.string().required('Reason Edit is required'),
  });

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

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

  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: string, id: number, reason: string) => {
    if (active == "Active") {
      active = "0"
    } else {
      active = "1"
    }
    axios
      .put(`/corporates/${corporate_id}/formulariums-update-status/${id}`, {
        active: active,
      })
      .then((res) => {
        console.log(res.data.message)
        window.location.reload();
      });
  }
  
  const getContent = () => (
    <>
      <Stack paddingX={2} paddingY={2}>
        <Typography variant='subtitle1'>Are you sure to {dataValue?.active === "Active" ? 'inactive' : 'active'} 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?.category}</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 == "Active" ?
                  <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 (
    <React.Fragment>
        <TableBody>
          <TableRow>
            <TableCell align='left' width={50}/>
            <TableCell align='left'>{props.code}</TableCell>
            <TableCell align='left'>{props.name}</TableCell>
            <TableCell align='left' width={100}>
              {formularium.active == "Active" ? (
                <Label color='success'>Active</Label>
              ): (
                <Label color='error'>Inactive</Label>
              )}
            </TableCell>
            <TableCell align='center' width={100}>
              <TableMoreMenu actions={
                <>
                  <MenuItem onClick={() => setOpen(!open)}>
                    <FindInPageOutlined />
                    Detail
                  </MenuItem>
                  <MenuItem onClick={() => handleActivate(true, {
                    id: formularium.id,
                    formulaurium_category_id: formularium.formulaurium_category_id,
                    category: formularium.category,
                    description: formularium.description,
                    active: formularium.active
                  })
                  }>
                    <CachedOutlined />
                    Update Status
                  </MenuItem>
                </>
              } />
            </TableCell>
          </TableRow>
        </TableBody>
        <TableBody>
          <TableRow>
            <TableCell colSpan={5} style={{paddingBottom:0, paddingTop:0}}>
              <Collapse in={open} timeout='auto' unmountOnExit>
                <InfoDetail {...props}/>
              </Collapse>
            </TableCell>
          </TableRow>
        </TableBody>

        <DialogUpdateStatus 
          openDialog={isDialogOpen} 
          setOpenDialog={setDialogOpen} 
          description={dataDescription}
          title={titles}
          data={dataValue}
          content={getContent()}
        />
    </React.Fragment>
  )
}