// @mui
import { Box, Button, Card, Collapse, Container, FormControl, Grid, IconButton, InputLabel, MenuItem, OutlinedInput, Paper, Select, SelectChangeEvent, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, Typography, Badge, Stack } from '@mui/material';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight';
import PublishIcon from '@mui/icons-material/Publish';
import AddIcon from '@mui/icons-material/Add';
// hooks
import useSettings from '../../hooks/useSettings';
// components
import Page from '../../components/Page';
import axios from '../../utils/axios';
import useAuth from '../../hooks/useAuth';
import { Link , NavLink as RouterLink, useParams } from 'react-router-dom';
import React, { useContext, useEffect, useRef, useState } from 'react';
import { Theme, useTheme } from '@mui/material/styles';
import { Corporate } from '../../@types/corporates';
import { LaravelPaginatedData, LaravelPaginatedDataDefault } from '../../@types/paginated-data';
import HeaderBreadcrumbs from '../../components/HeaderBreadcrumbs';
import CorporateTabNavigations from './CorporateTabNavigations';
import { fCurrency } from '../../utils/formatNumber';
import { ConfiguredCorporateContext } from '@/contexts/ConfiguredCorporateContext';
import Iconify from '@/components/Iconify';
import { LoadingButton } from '@mui/lab';
import { makeFormData } from '@/utils/jsonToFormData';
import { enqueueSnackbar } from 'notistack';

export default function Corporates() {
  const { themeStretch } = useSettings();
  const { corporate_id } = useParams();
  const [corporate, setCorporate] = useState<Corporate|null>();

  const configuredCorporateContext = useContext(ConfiguredCorporateContext);

  useEffect(() => {
    setCorporate(configuredCorporateContext.currentCorporate);
    getFilesDoc(corporate_id);
  }, [configuredCorporateContext, corporate_id])

  const headStyle = {
    fontWeight: 'bold',
  };
  // Upload Docs
  const fileDocsInput = useRef<HTMLInputElement>(null);
  const [fileDocs, setFileDocs] = useState([]);
  const [showAll, setShowAll] = useState(false);
  const [isActive, setIsActive] = useState(false);
  const handleDocsInputChange = (corporate_id) => (event) => {
    if(event.target.files[0] && corporate_id)
    {
      const updatedFiles = Array.from(event.target.files).map((file) => ({
        file
      }));
      submitUploadDocs(corporate_id, updatedFiles);
    }
  };
  function submitUploadDocs(corporate_id, files)
  {
    if(files.length > 0)
    {
      files.map((file, index) => {
        const formData = makeFormData(
        {
          corporate_id : corporate_id,
          result_files : file['file']
        }
        );
        axios
        .post('/add-files-doc', formData)
        .then((response) => {
          getFilesDoc(corporate_id);
          enqueueSnackbar(response.data.message,  { variant: 'success' });
        })
        .catch((error) => {
          enqueueSnackbar(error.response.data.errors[0],  { variant: 'error' });
        });
      });
    }
  }
  function getFilesDoc(corporate_id)
  {
    axios
    .post('/get-files-doc',{corporate_id:corporate_id})
    .then((response) => {
      setFileDocs(response.data.data);
      if(response.data.data[0]['status_download'] == 1)
      {
        setIsActive(!isActive);
      }
      else
      {
        setIsActive(isActive);
      }
    })
    .catch((error) => {
      enqueueSnackbar(error.response.data.errors[0],  { variant: 'error' });
    });
  }

  const toggleButton = () => {
    setIsActive(!isActive);
    let statusDownload = 0;
    if(!isActive)
    {
      statusDownload = 1;
    }
    else
    {
      statusDownload = 0;
    }
    axios
    .post('/update-status-files-doc', {status_download : statusDownload, corporate_id :  corporate_id})
    .then((response) => {
      enqueueSnackbar(response.data.message,  { variant: 'success' });
    })
    .catch((error) => {
      enqueueSnackbar(error.response.data.errors[0],  { variant: 'error' });
    });
  };
  // End Upload Docs

  const style1 = {px:4, marginTop: 2};
  const style2 = {color: '#919EAB', width: '50%'};
  const style3 = {color: '#212B36', width: '50%'};

  return (
    <Page title="Dashboard">

      <HeaderBreadcrumbs
        heading={'Corporate Dashboard'}
        links={[
          {
            name: 'Corporates',
            href: '/corporates',
          },
          {
            name: corporate?.name ?? '-',
            href: '/corporates/'+corporate_id,
          },
        ]}
      />

      {/* <Container maxWidth={themeStretch ? false : 'xl'}> */}
        <Card>
          <Stack spacing="2">
            <CorporateTabNavigations position=""/>
            <Grid>
              <Grid sx={{ p:2 }}>
                <Typography variant='subtitle1' sx={{...headStyle, px:4, marginTop: 2}}>Current Policy </Typography>
                <Stack spacing={2} direction='row' sx={{...style1}}>
                  <Typography variant='body2' sx={{...style2}}>Policy Name</Typography>
                  <Typography variant='body2' sx={{...style3}}>{corporate?.current_policy?.code}</Typography>
                </Stack>
                <Stack spacing={2} direction='row' sx={{...style1}}>
                  <Typography variant='body2' sx={{...style2}}>Total Premi</Typography>
                  <Typography variant='body2' sx={{...style3}}>{fCurrency(corporate?.current_policy?.total_premi)}</Typography>
                </Stack>
                <Stack spacing={2} direction='row' sx={{...style1}}>
                  <Typography variant='body2' sx={{...style2}}>Stop Service</Typography>
                  <Typography variant='body2' sx={{...style3}}>{fCurrency(corporate?.current_policy?.minimal_stop_service_net)}</Typography>
                </Stack>
                <Stack spacing={2} direction='row' sx={{...style1}}>
                  <Typography variant='body2' sx={{...style2}}>Balance</Typography>
                  <Typography variant='body2' sx={{...style3}}>{fCurrency(corporate?.current_policy?.limit_balance)}</Typography>
                </Stack>
              </Grid>

              <Grid sx={{ p:2 }}>
                <Typography variant='subtitle1' sx={{...headStyle, px:4, marginTop: 2}}>Claims</Typography>
                <Stack spacing={2} direction='row' sx={{...style1}}>
                  <Typography variant='body2' sx={{...style2}}>Number Of Claim</Typography>
                  <Typography variant='body2' sx={{...style3}}>{corporate?.current_policy?.code}</Typography>
                </Stack>
                <Stack spacing={2} direction='row' sx={{...style1}}>
                  <Typography variant='body2' sx={{...style2}}>Total Usage This Year</Typography>
                  <Typography variant='body2' sx={{...style3}}>{fCurrency((corporate?.current_policy?.total_premi ?? 0) - (corporate?.current_policy?.limit_balance ?? 0))}</Typography>
                </Stack>

              </Grid>
              <Grid sx={{ p:2 }}>
                <Typography variant='subtitle1' sx={{...headStyle, px:4, marginTop: 2}}>Docs (Terms & Conditions)</Typography>
                {fileDocs.length > 0 && (
                  <Stack spacing={2} direction='row' sx={{...style1}} alignItems="center">
                    <Stack direction='row' sx={{width: '50%'}} alignItems="center">
                      <Typography variant='body2' sx={{color: '#919EAB', marginRight: 2}}>ASO members can download or not?</Typography>
                      <Button
                        variant="outlined"
                        color={isActive ? "success" : "error"}
                        size="small"
                        onClick={toggleButton}
                      >
                        <Typography variant='body3' sx={{fontWeight: 'bold'}}>{isActive ? 'Active' : 'Inactive'}</Typography>
                      </Button>
                    </Stack>
                    {!showAll && (
                      <Stack direction='row' sx={{width: '50%'}} alignItems="center">
                        <input
                          type="file"
                          id={`fileDocsID`}
                          ref={fileDocsInput}
                          style={{ display: 'none' }}
                          onChange={(event) => {
                            handleDocsInputChange(corporate_id)(event);
                          }}
                          accept="application/pdf"
                          multiple
                        />

                          <Button
                            variant="outlined"
                            onClick={() => {
                              fileDocsInput.current.click();
                            }}
                            sx={{ width: 'fit-content', color: '#19BBBB' }}
                          >
                            <Stack alignItems="center" direction="row" spacing={1}>
                              <Iconify icon="icon-park-outline:upload-one" fontSize="2em" sx={{color: '#19BBBB'}} />
                              <Typography variant='body3' sx={{fontWeight: 'bold', color: '#19BBBB'}}>Update File</Typography>
                            </Stack>
                          </Button>
                      </Stack>
                    )}
                  </Stack>
                )}
                {fileDocs.slice(0, showAll ? fileDocs.length : 1).map((file, index) => (
                  <Stack spacing={2} direction='row' sx={{...style1}}>
                    <a
                      href={file.path}
                      style={{ cursor: 'pointer', textDecoration: 'underline', color: '#19BBBB' }}
                      target="_blank"
                    >
                      <Typography variant='body2' sx={{color: '#19BBBB'}}>{file.original_name}</Typography>
                    </a>
                  </Stack>
                ))}
                {!showAll && fileDocs.length > 1 && (
                  <Stack spacing={2} direction='row' sx={{...style1}}>
                    <Typography variant='body2' onClick={() => setShowAll(true)} style={{ color: '#19BBBB', cursor: 'pointer' }}>Lihat Semua Data</Typography>
                  </Stack>
                )}
                {showAll && (
                  <Stack spacing={2} direction='row' sx={{...style1}}>
                    <Typography variant='body2' onClick={() => setShowAll(false)} style={{ color: '#19BBBB', cursor: 'pointer' }}>Sembunyikan Data</Typography>
                  </Stack>
                )}
                {fileDocs.length <= 0 && (
                  <Stack spacing={2} direction='row' sx={{...style1}} alignItems="center">
                    <Typography variant='body2' sx={{...style2}}>Please add a Terms & Conditions document</Typography>
                    <Stack direction='row' sx={{width: '50%'}} alignItems="center">
                      <input
                        type="file"
                        id={`fileDocsID`}
                        ref={fileDocsInput}
                        style={{ display: 'none' }}
                        onChange={(event) => {
                          handleDocsInputChange(corporate_id)(event);
                        }}
                        accept="application/pdf"
                        // multiple
                      />
                      <LoadingButton
                        variant="outlined"
                        onClick={() => {
                          fileDocsInput.current.click();
                        }}
                      >
                        <Stack alignItems="center" direction="row" spacing={1}>
                          <Iconify icon="icon-park-outline:upload-one" fontSize="2em" sx={{color: '#19BBBB'}} />
                          <Typography variant='body3' sx={{fontWeight: 'bold', color: '#19BBBB'}}>Upload File</Typography>
                        </Stack>
                      </LoadingButton>
                    </Stack>
                  </Stack>
                )}
              </Grid>
            </Grid>
          </Stack>
        </Card>
      {/* </Container> */}
    </Page>
  );
}
