// @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, useSearchParams } from 'react-router-dom';
import React, { ChangeEvent, 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';

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

  // 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
            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="outlined" startIcon={<AddIcon />} sx={{ p: 1.8 }}>
              Create
            </Button>
          </Link>
          {/* </Grid> */}
        </Stack>

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

  // Component Row
  // Generate the every row of the table
  function Row(props: { row: ReturnType<typeof createData> }) {
    const { row } = props;
    const [open, setOpen] = React.useState(false);

    const handleActivate = (model: any, status: string) => {
      axios
        .put(`/corporates/${row.id}/activation`, {
          // service_code: service.service_code,
          active: status == 'active',
        })
        .then((res) => {
          setDataTableData({
            ...dataTableData,
            data: dataTableData.data.map((model) => {
              let updatedModel = model;
              if (row.id == model.id) {
                updatedModel.active = res.data.corporate.active;
              }
              return updatedModel;
            }),
          });
        })
        .catch((error) => {
          // console.log('asdasd', error.response.data.message)
          enqueueSnackbar(
            error.response.data.message ?? error.message ?? 'Failed Processing Request',
            { variant: 'error' }
          );
        });
    };

    return (
      <React.Fragment>
        <TableRow sx={{ '& > *': { borderBottom: 'unset' } }}>
          <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 && (
              <Button
                variant="outlined"
                color="success"
                size="small"
                onClick={() => {
                  handleActivate(row, 'inactive');
                }}
              >
                Active
              </Button>
            )}
            {row.active != 1 && (
              <Button
                variant="outlined"
                color="error"
                size="small"
                onClick={() => {
                  handleActivate(row, 'active');
                }}
              >
                Inactive
              </Button>
            )}
          </TableCell>
          <TableCell align="right">
            <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={'/corporates/' + row.id + ''}>
                <Button variant="outlined" color="primary" size="small">
                  Config
                </Button>
              </Link>
            </Stack>
          </TableCell>
        </TableRow>
        {/* COLLAPSIBLE ROW */}
        <TableRow>
          <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={9999}>
            <Collapse in={open} timeout="auto" unmountOnExit>
              <Box sx={{ margin: 1, borderBottom: 1, pb: 2 }}>
                <Typography sx={{ fontWeight: '600', mb: 1 }}>Current Policy Detail</Typography>
                <Grid container>
                  <Grid item xs={6}>
                    <Grid container>
                      <Grid item xs={6}>
                        Policy Code
                      </Grid>
                      <Grid item xs={6}>
                        : {row.current_policy?.code}
                      </Grid>

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

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

                  <Grid item xs={6}>
                    <Grid Grid container>
                      <Grid item xs={6}>
                        Period
                      </Grid>
                      <Grid item xs={6}>
                        : {row.current_policy?.start} - {row.current_policy?.end}
                      </Grid>

                      <Grid item xs={6}>
                        Total Premi
                      </Grid>
                      <Grid item xs={6}>
                        : {row.current_policy ? fCurrency(row.current_policy?.total_premi) : '-'}
                      </Grid>

                      <Grid item xs={6}>
                        Minimal Deposit
                      </Grid>
                      <Grid item xs={6}>
                        :{' '}
                        {row.current_policy
                          ? fCurrency(row.current_policy?.minimal_deposit_net)
                          : '-'}
                      </Grid>

                      <Grid item xs={6}>
                        Corporate Limit
                      </Grid>
                      <Grid item xs={6}>
                        : {row.current_policy ? fCurrency(row.current_policy?.limit_balance) : '-'}
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>

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

                  <Grid item xs={6}>
                    <Grid Grid container>
                      <Grid item xs={6}>
                        Total Claim This Month
                      </Grid>
                      <Grid item xs={6}>
                        : 0
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>

                {/* <Typography sx={{ fontWeight: '600', mb: 1, mt: 2 }}>Sub Corporate</Typography>
                <Grid container>
                  <Grid item xs={12}>
                    <Grid container>
                      <Grid item xs={6}>
                        Sub Corporates ({row.sub_corporates.length})
                      </Grid>
                      <Grid item xs={6}>
                        : {row.sub_corporates?.map((corp) => corp.name).join(', ')}
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid> */}
              </Box>
            </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: 'Corporates',
              href: '/corporates',
            },
          ]}
        />

        <SearchInput onSearch={applyFilter} />

        <Card>
          {/* The Main Table */}
          <TableContainer component={Paper}>
            <Table aria-label="collapsible table">
              <TableBody>
                <TableRow>
                  <TableCell style={headStyle} align="left" width={50} />
                  <TableCell style={headStyle} align="left">
                    Code
                  </TableCell>
                  <TableCell style={headStyle} align="left">
                    Name
                  </TableCell>
                  <TableCell style={headStyle} align="left" width={100}>
                    Status
                  </TableCell>
                  <TableCell style={headStyle} align="right" width={100}>
                    Action
                  </TableCell>
                </TableRow>
              </TableBody>
              {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>
    </Page>
  );
}
