// @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,
  Dialog,
} from '@mui/material';
import * as Yup from 'yup';


// icon
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';
import HistoryIcon from '@mui/icons-material/History';
import MoreVertIcon from '@mui/icons-material/MoreVert';
import FindInPageOutlinedIcon from '@mui/icons-material/FindInPageOutlined';
import EditOutlinedIcon from '@mui/icons-material/EditOutlined';
import SettingsOutlinedIcon from '@mui/icons-material/SettingsOutlined';
import CachedOutlinedIcon from '@mui/icons-material/CachedOutlined';

// hooks
import useSettings from '../../hooks/useSettings';
// components
import Page from '../../components/Page';
import DialogUpdateStatus from '../../components/DialogUpdateStatus';
import axios from '../../utils/axios';
import useAuth from '../../hooks/useAuth';
import { useForm } from 'react-hook-form'
import { Link, NavLink as RouterLink, useNavigate, useSearchParams } from 'react-router-dom';
import React, { ChangeEvent, ReactElement, useEffect, useRef, useState } from 'react';
import { Theme, useTheme } from '@mui/material/styles';
import { Corporate } from '../../@types/corporates';
import { LaravelPaginatedData } from '../../@types/paginated-data';
import HeaderBreadcrumbs from '../../components/HeaderBreadcrumbs';
import BasePagination from '../../components/BasePagination';
import { fCurrency } from '../../utils/formatNumber';
import { enqueueSnackbar } from 'notistack';
import { fDate } from '@/utils/formatTime';
import Popover from '@mui/material/Popover';

import ButtonStyles from '../../theme/overrides/Button';
import TableMoreMenu from '@/components/table/TableMoreMenu';
import Iconify from '@/components/Iconify';
import Label from '@/components/Label';
import { FormProvider, RHFSelect } from '@/components/hook-form';
import { LoadingButton } from '@mui/lab';
import { yupResolver } from '@hookform/resolvers/yup';


export default function Corporates() {
  const { themeStretch } = useSettings();
  const [searchParams, setSearchParams] = useSearchParams();
  const navigate = useNavigate()

  // Type 
  type DataContent = {
    code: string;
    name: string;
    id: string;
    status: string|number;
  };
  
  type MuiDialogProps = {
    title?: {
      name?: string;
      icon?: string;
    };
    openDialog: boolean;
    setOpenDialog: Function;
    content?: ReactElement;
    data?: DataContent[];
  };

  type FormValuesProps = {
    value: string;
    active: boolean;
  };

  // Called on every row to map the data to the columns
  function createData(corporate: Corporate): Corporate {
    return {
      ...corporate,
    };
  }
  

  // Dummy Default Data
  const [dataTableIsLoading, setDataTableLoading] = React.useState(true);
  const [dataTableData, setDataTableData] = React.useState<LaravelPaginatedData>({
    current_page: 1,
    data: [],
    path: '',
    first_page_url: '',
    last_page: 1,
    last_page_url: '',
    next_page_url: '',
    prev_page_url: '',
    per_page: 10,
    from: 0,
    to: 0,
    total: 0,
  });

  const loadDataTableData = async (appliedFilter: any | null = null) => {
    setDataTableLoading(true);
    const filter = appliedFilter ? appliedFilter : Object.fromEntries([...searchParams.entries()]);
    const response = await axios.get('/corporates', { params: filter });
    console.log(response.data);
    setDataTableLoading(false);

    setDataTableData(response.data);
  };

  const applyFilter = async (searchFilter: any) => {
    await loadDataTableData({ search: searchFilter });
    setSearchParams({ search: searchFilter });
  };

  const handlePageChange = (event: ChangeEvent, value: number) => {
    const filter = Object.fromEntries([...searchParams.entries(), ['page', value]]);
    loadDataTableData(filter);
    setSearchParams(filter);
  };

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

  const headStyle = {
    fontWeight: 'bold',
  };

  // FILTER SELECT
  const ITEM_HEIGHT = 48;
  const ITEM_PADDING_TOP = 8;
  const MenuProps = {
    PaperProps: {
      style: {
        maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
        width: 250,
      },
    },
  };

  const names = ['PLAN001', 'PLAN002', 'PLAN003', 'PLAN004', 'PLAN005'];
  function getStyles(name: string, personName: string[], theme: Theme) {
    return {
      fontWeight:
        personName.indexOf(name) === -1
          ? theme.typography.fontWeightRegular
          : theme.typography.fontWeightMedium,
    };
  }

  const theme = useTheme();
  const [planIdFilter, setPlanIdFilter] = React.useState<string[]>([]);

  const handleChangePlanID = (event: SelectChangeEvent<typeof planIdFilter>) => {
    const {
      target: { value },
    } = event;
    setPlanIdFilter(
      // On autofill we get a stringified value.
      typeof value === 'string' ? value.split(',') : value
    );
  };

  const [statusFilter, setStatusFilter] = React.useState<string[]>([]);
  const handleChangeStatus = (event: SelectChangeEvent<typeof statusFilter>) => {
    const {
      target: { value },
    } = event;
    setStatusFilter(
      // On autofill we get a stringified value.
      typeof value === 'string' ? value.split(',') : value
    );
  };


  // END FILTER SELECT

  // Component Search Input
  function SearchInput(props: any) {
    // SEARCH
    const searchInput = useRef<HTMLInputElement>(null);
    const [searchText, setSearchText] = useState('');

    const handleSearchChange = (event: any) => {
      const newSearchText = event.target.value ?? '';
      setSearchText(newSearchText);
    };

    const handleSubmit = (event: any) => {
      event.preventDefault();
      props.onSearch(searchText); // Trigger to Parent
    };

    useEffect(() => {
      // console.log('Search Input: useEffect')
      setSearchText(searchParams.get('search') ?? '');
    }, [searchParams]);

    return (
      <form onSubmit={handleSubmit} style={{ width: '100%' }}>
        <Stack direction={'row'} spacing={2} sx={{ mb: 2 }}>
          <TextField
            id="search-input"
            ref={searchInput}
            label="Search"
            variant="outlined"
            // fullWidth
            style={{ width: '85%' }}
            onChange={handleSearchChange}
            value={searchText}
          />

          {/* <Grid item>
            <TextField id="outlined-basic" label="Search" variant="outlined" sx={{ width: 400 }}/>
          </Grid>

          <Grid item>
            <FormControl sx={{ width: 200 }}>
              <InputLabel id="plan-id-label">PlanID</InputLabel>
              <Select
                labelId="plan-id-label"
                id="plan-id"
                multiple
                value={planIdFilter}
                onChange={handleChangePlanID}
                input={<OutlinedInput label="PlanID" />}
                MenuProps={MenuProps}
              >
                {names.map((name) => (
                  <MenuItem
                    key={name}
                    value={name}
                    style={getStyles(name, planIdFilter, theme)}
                  >
                    {name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Grid>

          <Grid item>
            <FormControl sx={{ width: 200 }}>
              <InputLabel id="status-filter-label">Status</InputLabel>
              <Select
                labelId="status-filter-label"
                id="status-filter"
                multiple
                value={statusFilter}
                onChange={handleChangeStatus}
                input={<OutlinedInput label="Status" />}
                MenuProps={MenuProps}
              >
                {['Active', 'Suspended'].map((name) => (
                  <MenuItem
                    key={name}
                    value={name}
                    style={getStyles(name, statusFilter, theme)}
                  >
                    {name}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Grid> */}

          {/* <Grid item> */}
          {/* <input id="importMember" ref={importMember} style={{ display: 'none' }} type="file" accept='.csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, text/plain' />
            <Button variant="outlined" startIcon={<PublishIcon />} sx={{ p: 1.8 }} onClick={handleImportButton}>
              Import
            </Button> */}
          <Link to={'/corporates/create'}>
            <Button variant="contained" startIcon={<AddIcon sx={{}} />} sx={{ p: 1.8, typography: 'subtitle2' }}> 
              New Corporate
            </Button>
          </Link>
          {/* </Grid> */}
        </Stack>

        <Button type="submit" sx={{ display: 'none' }}>
          Search
        </Button>
      </form>
    );
  }

  // Component Row
  // Generate the every row of the table
  const [isDialogOpen, setDialogOpen] = useState(false)
  let titles = {
    name: 'Update Status',
    icon: '-'
  }
  const [dataValue, setDataValue] = useState();
  const [dataDescription, setDescriptionValue] = useState('');

  
  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 {
      console.log(dataValue)
      handleUpdate(dataValue.id, dataValue.status, row.reason) 
    } catch (error: any) {
      console.log('data gagal');
    }

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

  const handleUpdate = (id: string, active: number, reason: string) => {
      axios
        .put(`/corporates/${id}/activation`, {
          active: active, 
          reason: reason
        })
        .then((res) => {
          window.location.reload();
        });
  }


  const getContent = () => (
    <>
       <Stack paddingX={2} paddingY={2}>
                <Typography variant='subtitle1'>Are you sure to {dataValue?.status == 1 ? 'inactive' : 'active'} this service ?</Typography>
            </Stack>
            <Card>
                <Grid container paddingX={2} paddingY={2}>
                    <Grid item xs={4} md={4}>
                        <Typography variant='inherit'>Code</Typography>
                    </Grid>
                    <Grid item xs={8}>
                        <Typography variant='subtitle1'>{dataValue?.code}</Typography>
                    </Grid>
                    <Grid item xs={4} md={4} marginTop={2}>
                        <Typography variant='inherit'>Corporate Name</Typography>
                    </Grid>
                    <Grid item xs={8} marginTop={2}>
                        <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="Worng Setting">Worng 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?.status == 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>
    </>
  );

  function Row(props: { row: ReturnType<typeof createData> }) {
    const { row } = props;
    const [open, setOpen] = React.useState(false);
    const navigate = useNavigate()

    
    const handleActivate = (isOpen: boolean, dataValue: DataContent) => {
      setDialogOpen(isOpen)
      setDataValue(dataValue)
      setDescriptionValue('Are you sure to inactive this coporate ?')
    };

    return (
      <React.Fragment>
        <TableRow >
          <TableCell>
            {/* <IconButton aria-label="expand row" size="small" onClick={() => setOpen(!open)}>
              {open ? <KeyboardArrowDownIcon /> : <KeyboardArrowRightIcon />}
            </IconButton> */}
          </TableCell>
          <TableCell align="left">{row.code}</TableCell>
          <TableCell align="left">{row.name}</TableCell>
          <TableCell align="left">
            {row.active == 1 && (
              <Label color='success'>
                Active
              </Label>
              // <Button
              //   variant="outlined"
              //   color="success"
              //   size="small"
              //   onClick={() => {
              //     handleActivate(row, 'inactive');
              //   }}
              // >
              //   Active
              // </Button>
            )}
            {row.active != 1 && (
              <Label color='error'>
                Inactive
              </Label>
              // <Button
              //   variant="outlined"
              //   color="error"
              //   size="small"
              //   onClick={() => {
              //     handleActivate(row, 'active');
              //   }}
              // >
              //   Inactive
              // </Button>
            )}
          </TableCell>
          <TableCell align="right" sx={{borderBottom: 'unset'}}>
            {/* <Stack direction="row" justifyContent="flex-end" spacing={1}>
              <Link to={`/corporates/${row.id}/edit`}>
                <Button variant="outlined" color="primary" size="small">
                  Edit
                </Button>
              </Link>
              <Link to={`/corporate/${row.id}`}>
                <Button variant="outlined" color="primary" size="small">
                  Config
                </Button>
              </Link>
              <Link to={`/corporate/${row.id}/corporate-history`}>
                <HistoryIcon />
              </Link>
            </Stack> */}
           <TableMoreMenu actions={
            <>
              <MenuItem onClick={() => setOpen(!open)}>
                <FindInPageOutlinedIcon />
                Detail
              </MenuItem>
              <MenuItem onClick={() => navigate(`/corporates/${row.id}/edit`)}>
                <EditOutlinedIcon />
                Edit
              </MenuItem>
              <MenuItem onClick={() => navigate(`/corporates/${row.id}`)}>
                <SettingsOutlinedIcon />
                Config
              </MenuItem>
              <MenuItem onClick={() => navigate(`/corporates/${row.id}/corporate-history`)}>
                <HistoryIcon />
                History
              </MenuItem>
              <MenuItem onClick={() => handleActivate(true, {code: row.code, name: row.name, id:row.id, status: row.active})}>
                <CachedOutlinedIcon />
                Update Status
              </MenuItem>
            </>
           } />
          </TableCell>
        </TableRow>

        

        {/* COLLAPSIBLE Detail ROW */}
        <TableRow>
          <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={9999}>
            <Collapse in={open} timeout="auto" unmountOnExit>
              <Card sx={{paddingX: 2, paddingY: 2, marginBottom:3}}>
                <Box sx={{ margin: 1, pb: 2 }}>
                  <Grid container>
                    <Grid item xs={6}>
                      <Typography sx={{ fontWeight: '600', mb: 1 }}>Current Policy Detail</Typography>
                      <Grid container>
                        <Grid item xs={4}>
                          Policy Code :
                        </Grid>
                        <Grid item xs={6}>
                          {row.current_policy?.code}
                        </Grid>

                        <Grid item xs={4}>
                          Number of Plan :
                        </Grid>
                        <Grid item xs={6}>
                          {row.corporate_plans_count}
                        </Grid>

                        <Grid item xs={4}>
                          Number of Benefit :
                        </Grid>
                        <Grid item xs={6}>
                          {row.corporate_benefits_count}
                        </Grid>

                        <Grid item xs={4}>
                          Period :
                        </Grid>
                        <Grid item xs={6}>
                          <Box sx={{ display: 'flex', placeContent: 'space-between' }}>
                            {/* <span>: {fDate(row.current_policy?.start)}</span>- */}
                            {/* <span>{fDate(row.current_policy?.end)}</span> */}
                          </Box>
                        </Grid>

                        <Grid item xs={4}>
                          Total Premi :
                        </Grid>
                        <Grid item xs={6}>
                          {row.current_policy ? (
                            <Box sx={{ display: 'flex', placeContent: 'space-between' }}>
                              <span>
                                {fCurrency(row.current_policy?.total_premi).split(' ')[0]}
                              </span>
                              <span>{fCurrency(row.current_policy?.total_premi).split(' ')[1]}</span>
                            </Box>
                          ) : (
                            '-'
                          )}
                        </Grid>

                        <Grid item xs={4}>
                          Minimal Deposit :
                        </Grid>
                        <Grid item xs={6}>
                          {row.current_policy ? (
                            <Box sx={{ display: 'flex', placeContent: 'space-between' }}>
                              <span>
                                {fCurrency(row.current_policy?.minimal_deposit_net).split(' ')[0]}
                              </span>
                              <span>
                                {fCurrency(row.current_policy?.minimal_deposit_net).split(' ')[1]}
                              </span>
                            </Box>
                          ) : (
                            '-'
                          )}
                        </Grid>
                        <Grid item xs={4}>
                          Corporate Limit :
                        </Grid>
                        <Grid item xs={6}>
                          {row.current_policy ? (
                            <Box sx={{ display: 'flex', placeContent: 'space-between' }}>
                              <span>
                                {fCurrency(row.current_policy?.limit_balance).split(' ')[0]}
                              </span>
                              <span>
                                {fCurrency(row.current_policy?.limit_balance).split(' ')[1]}
                              </span>
                            </Box>
                          ) : (
                            '-'
                          )}
                        </Grid>
                      </Grid>
                    </Grid>

                    <Grid item xs={6}>
                      <Typography sx={{ fontWeight: '600', mb: 1 }}>Member Detail</Typography>
                      <Grid container>
                        <Grid item xs={6}>
                          Total Member :
                        </Grid>
                        <Grid item xs={6}>
                          {row.employees_count}
                        </Grid>
                        <Grid item xs={6}>
                          Total Claim This Month  : 
                        </Grid>
                        <Grid item xs={6}>
                          0
                        </Grid>
                      </Grid>
                    </Grid>

                  </Grid>
                </Box>
              </Card>
            </Collapse>
          </TableCell>
        </TableRow>
      </React.Fragment>
    );
  }

  return (
    <Page title="Membership : Corporate List">
      <Container maxWidth={themeStretch ? false : 'xl'}>
        <HeaderBreadcrumbs
          heading={'Coporate List'}
          links={[
            { name: 'Dashboard', href: '/dashboard' },
            {
              name: 'Station Benefit & Membership',
              href: '/corporates',
            },
            {
              name: 'Corporates',
              href: '/corporates',
            },
          ]}
        />

        <SearchInput onSearch={applyFilter} />

        {/* <Card> */}
          {/* The Main Table */}
          <TableContainer component={Paper}>
            <Table aria-label="collapsible table">
              <TableHead>
                <TableRow>
                  <TableCell align="left" width={50} />
                  <TableCell align="left">
                    Code
                  </TableCell>
                  <TableCell align="left">
                    Name
                  </TableCell>
                  <TableCell align="left" width={100}>
                    Status
                  </TableCell>
                  <TableCell align="center" width={100}>
                    {/* Action */}
                  </TableCell>
                </TableRow>
              </TableHead>
              {dataTableIsLoading ? (
                <TableBody>
                  <TableRow>
                    <TableCell colSpan={8} align="center">
                      Loading
                    </TableCell>
                  </TableRow>
                </TableBody>
              ) : dataTableData.data.length == 0 ? (
                <TableBody>
                  <TableRow>
                    <TableCell colSpan={8} align="center">
                      No Data
                    </TableCell>
                  </TableRow>
                </TableBody>
              ) : (
                <TableBody>
                  {dataTableData.data.map((row) => (
                    <Row key={row.code} row={row} />
                  ))}
                </TableBody>
              )}
            </Table>
          </TableContainer>
          <BasePagination paginationData={dataTableData} onPageChange={handlePageChange} />
        {/* </Card> */}
      </Container>
      <DialogUpdateStatus 
        openDialog={isDialogOpen}
        setOpenDialog={setDialogOpen} 
        title={titles}
        data={dataValue}
        description={dataDescription}
        content={getContent()}
      />
    </Page>

  );
}
