// @mui
import {
  Box,
  Button,
  Card,
  Collapse,
  IconButton,
  InputLabel,
  MenuItem,
  OutlinedInput,
  Paper,
  Select,
  SelectChangeEvent,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography,
  Badge,
  Tab,
  Tabs,
  CardHeader,
  Stack,
  Menu,
  ButtonGroup,
  Grid,
} from '@mui/material';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight';
import AddIcon from '@mui/icons-material/Add';
import UploadIcon from '@mui/icons-material/Upload';
import CancelIcon from '@mui/icons-material/Cancel';
import InsertDriveFileIcon from '@mui/icons-material/InsertDriveFile';
// hooks
import React, { ChangeEvent, Component, useEffect, useRef, useState } from 'react';
import useSettings from '../../../hooks/useSettings';
import { useParams, useSearchParams } from 'react-router-dom';
// components
import axios from '../../../utils/axios';
import { Plan } from '../../../@types/corporates';
import { LaravelPaginatedData } from '../../../@types/paginated-data';
import { Member } from '../../../@types/member';
import BasePagination from '../../../components/BasePagination';
import { enqueueSnackbar } from 'notistack';
import { LoadingButton } from '@mui/lab';
import DialogLog from './sections/DialogLog';

export default function CorporatePlanList() {
  const { themeStretch } = useSettings();
  const { corporate_id } = useParams();
  const [searchParams, setSearchParams] = useSearchParams();
  const [importResult, setImportResult] = useState(null);

  // 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 = null) => {
    setDataTableLoading(true);
    const filter = appliedFilter ? appliedFilter : Object.fromEntries([...searchParams.entries()]);
    const response = await axios
      .get('/corporates/' + corporate_id + '/members', { params: filter })
      .catch((response) => {
        enqueueSnackbar('Failed getting data. ' + response.message, { variant: 'error' });
      });
    // console.log(response.data);
    setDataTableLoading(false);

    setDataTableData(response.data);
  };

  const applyFilter = async (searchFilter: string) => {
    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();
  }, []);

  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%' }}>
        <TextField
          id="search-input"
          ref={searchInput}
          label="Search"
          variant="outlined"
          fullWidth
          onChange={handleSearchChange}
          value={searchText}
        />
      </form>
    );
  }

  function ImportForm(props: any) {
    // IMPORT
    // Create Button Menu
    const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
    const createMenu = Boolean(anchorEl);
    const importPlan = useRef<HTMLInputElement>(null);
    const [currentImportFileName, setCurrentImportFileName] = useState(null);
    const [importLoading, setImportLoading] = useState(false);

    const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
      setAnchorEl(event.currentTarget);
    };

    const handleClose = () => {
      setAnchorEl(null);
    };

    const handleImportButton = () => {
      if (importPlan?.current) {
        handleClose();
        importPlan.current ? importPlan.current.click() : console.log('No File selected');
      } else {
        alert('No file selected');
      }
    };

    const handleCancelImportButton = () => {
      importPlan.current.value = '';
      importPlan.current.dispatchEvent(new Event('change', { bubbles: true }));
    };

    const handleImportChange = (event: any) => {
      if (event.target.files[0]) {
        setCurrentImportFileName(event.target.files[0].name);
      } else {
        setCurrentImportFileName(null);
      }
    };

    const handleUpload = () => {
      if (importPlan.current?.files.length) {
        const formData = new FormData();
        formData.append('file', importPlan.current?.files[0]);
        setImportLoading(true);
        axios
          .post(`corporates/${corporate_id}/members/import`, formData)
          .then((response) => {
            handleCancelImportButton();
            loadDataTableData();
            setImportResult(response.data);
            setImportLoading(false);
          })
          .catch((response) => {
            enqueueSnackbar(
              'Looks like something went wrong. Please check your data and try again. ' +
                response.message,
              { variant: 'error' }
            );
            setImportLoading(false);
          });
      } else {
        enqueueSnackbar('No File Selected', { variant: 'warning' });
      }
    };

    const handleGetTemplate = (type: string) => {
      axios.get('corporates/import-document-example/' + type).then((response) => {
        const link = document.createElement('a');
        link.href = response.data.data.file_url;
        link.setAttribute('download', response.data.data.file_name);
        document.body.appendChild(link);
        link.click();
        handleClose();
      });
    };

    return (
      <div>
        <input
          type="file"
          id="file"
          ref={importPlan}
          style={{ display: 'none' }}
          onChange={handleImportChange}
          accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, text/plain"
        />
        {!currentImportFileName && (
          <Stack direction={'row'} spacing={2} sx={{ p: 2 }}>
            <SearchInput onSearch={applyFilter} />
            {/* <h1>kjasndkjandskjasndkjansdkjansd</h1> */}
            <Button
              id="import-button"
              variant="outlined"
              startIcon={<AddIcon />}
              sx={{ p: 1.8 }}
              aria-controls={createMenu ? 'basic-menu' : undefined}
              aria-haspopup="true"
              aria-expanded={createMenu ? 'true' : undefined}
              onClick={handleClick}
            >
              Import
            </Button>
            <Menu
              id="import-button"
              anchorEl={anchorEl}
              open={createMenu}
              onClose={handleClose}
              MenuListProps={{
                'aria-labelledby': 'basic-button',
              }}
            >
              <MenuItem onClick={handleImportButton}>Import</MenuItem>
              <MenuItem
                onClick={() => {
                  handleGetTemplate('member');
                }}
              >
                Download Template
              </MenuItem>
            </Menu>
          </Stack>
        )}

        {currentImportFileName && (
          <Stack direction={'row'} spacing={2} sx={{ p: 2 }}>
            <ButtonGroup variant="outlined" aria-label="outlined button group" fullWidth>
              <Button onClick={handleImportButton} fullWidth>
                {currentImportFileName ?? 'No File Selected'}
              </Button>
              <Button
                onClick={handleCancelImportButton}
                size="small"
                fullWidth={false}
                sx={{ p: 1.8 }}
              >
                <CancelIcon color="error" />
              </Button>
            </ButtonGroup>

            <LoadingButton
              id="upload-button"
              variant="outlined"
              startIcon={<UploadIcon />}
              sx={{ p: 1.8 }}
              onClick={handleUpload}
              loading={importLoading}
            >
              Upload
            </LoadingButton>
          </Stack>
        )}
        {importResult && (
          <Stack direction={'row'} sx={{ px: 2, pb: 2 }}>
            <Box sx={{ color: 'text.secondary' }}>
              Last Import Result :{' '}
              <Box sx={{ color: 'success.main', display: 'inline' }}>
                {importResult.total_success_row ?? 0}
              </Box>{' '}
              Row Processed,{' '}
              <Box sx={{ color: 'error.main', display: 'inline' }}>
                {importResult.total_failed_row}
              </Box>{' '}
              Failed, Report :{' '}
              <a href={importResult.result_file?.url ?? '#'}>
                {importResult.result_file?.name ?? '-'}
              </a>
            </Box>
          </Stack>
        )}
      </div>
    );
  }

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

  const [columns, setColumns] = React.useState([
    { id: 'member_id', label: 'MemberID', minWidth: 100, align: 'left' },
    // { id: 'principal_id', label: 'Mapping ID', minWidth: 100, align: 'left' },
    // { id: 'nik', label: 'NIK', minWidth: 100, align: 'left' },
    // { id: 'current_policy.policy_number', label: 'Policy Number', minWidth: 100, align: 'left' },
    { id: 'effective_date', label: 'Effective Date', minWidth: 100, align: 'left' },
    { id: 'name', label: 'Name', minWidth: 100, align: 'left' },
    // { id: 'nric', label: 'NRIC', minWidth: 100, align: 'left' },
    // { id: 'email', label: 'E-mail', minWidth: 100, align: 'left' },
    { id: 'plan_id', label: 'PlanID', minWidth: 100, align: 'left' },
    { id: 'activation_date', label: 'Activation Date', minWidth: 100, align: 'left' },
    { id: 'termination_date', label: 'Termination Date', minWidth: 100, align: 'left' },
  ]);

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

    // useEffect(function () {
    //   if (row.full_name == 'Pajri') {
    //     setDialogLogOpen(true);
    //     console.log('fuck');
    //   }
    // }, []);

    const handleActivate = (model: any, status: string) => {
      axios
        .put(`/members/${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.member.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.member_id}</TableCell>
          <TableCell align="left">{row.current_policy?.start}</TableCell>
          <TableCell align="left">{row.name}</TableCell>
          <TableCell align="left">{row.current_plan?.code}</TableCell>
          <TableCell align="left">{row.current_policy?.start}</TableCell>
          <TableCell align="left">{row.current_policy?.end}</TableCell>
          <TableCell align="center">
            {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"><Button variant="outlined" color="success" size="small">Edit</Button></TableCell> */}
        </TableRow>
        {/* COLLAPSIBLE ROW */}
        <TableRow>
          <TableCell />
          <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={15}>
            <Collapse in={open} timeout="auto" unmountOnExit>
              <Box sx={{ pb: 2 }}>
                <Typography sx={{ fontWeight: '600', mb: 1 }}>Detail</Typography>
                <Grid container sx={{ pb: 2, mb: 2, borderBottom: 1 }}>
                  <Grid item xs={6}>
                    <Grid container>
                      <Grid item xs={6}>
                        Mapping ID
                      </Grid>
                      <Grid item xs={6}>
                        : {row.principal_id ?? '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Policy Number
                      </Grid>
                      <Grid item xs={6}>
                        : {row.current_policy?.code ?? '-'}
                      </Grid>
                      <Grid item xs={6}>
                        NRIC
                      </Grid>
                      <Grid item xs={6}>
                        : {row.nric ?? '-'}
                      </Grid>

                      <Grid item xs={6}>
                        NIK
                      </Grid>
                      <Grid item xs={6}>
                        : {row.employeds[0]?.nik ?? '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Email
                      </Grid>
                      <Grid item xs={6}>
                        : {row.email ?? '-'}
                      </Grid>
                    </Grid>
                  </Grid>
                  <Grid item xs={6}>
                    <Grid container>
                      <Grid item xs={6}>
                        Birth Date
                      </Grid>
                      <Grid item xs={6}>
                        : {row.birth_date ?? '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Gender
                      </Grid>
                      <Grid item xs={6}>
                        : {row.gender ?? '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Martial Status
                      </Grid>
                      <Grid item xs={6}>
                        : {row.marital_status ?? '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Language
                      </Grid>
                      <Grid item xs={6}>
                        : {row.language ?? '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Race
                      </Grid>
                      <Grid item xs={6}>
                        : {row.race ?? '-'}
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
                <Typography sx={{ fontWeight: '600', mb: 1 }}>Claim History</Typography>
                <Grid container sx={{ pb: 2, mb: 2, borderBottom: 1 }}>
                  <Grid item xs={6}>
                    <Grid container>
                      <Grid item xs={6}>
                        Requested
                      </Grid>
                      <Grid item xs={6}>
                        : {row.total_claims?.requested}
                      </Grid>

                      <Grid item xs={6}>
                        Pending
                      </Grid>
                      <Grid item xs={6}>
                        : {row.total_claims?.received}
                      </Grid>

                      <Grid item xs={6}>
                        Approved
                      </Grid>
                      <Grid item xs={6}>
                        : {row.total_claims?.approved}
                      </Grid>

                      <Grid item xs={6}>
                        Declined
                      </Grid>
                      <Grid item xs={6}>
                        : {row.total_claims?.declined}
                      </Grid>

                      <Grid item xs={6}>
                        Paid
                      </Grid>
                      <Grid item xs={6}>
                        : {row.total_claims?.paid}
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>

                <Grid>
                  <LoadingButton
                    id="upload-button"
                    variant="outlined"
                    startIcon={<InsertDriveFileIcon />}
                    // sx={{ p: 1.8 }}
                    // onClick={() => {handleDownloadLog(row)}}
                    onClick={() => {
                      setDialogLogOpen(true);
                    }}
                    loading={loadingLog}
                  >
                    Download LOG
                  </LoadingButton>
                </Grid>

                <DialogLog
                  title={{
                    name: `Generate LOG - ${row.full_name}`,
                  }}
                  openDialog={dialogLogOpen}
                  setOpenDialog={setDialogLogOpen}
                  data={{ member: row }}
                ></DialogLog>
              </Box>
            </Collapse>
          </TableCell>
        </TableRow>
      </React.Fragment>
    );
  }

  const headStyle = {
    fontWeight: 'bold',
  };
  return (
    <Stack>
      <ImportForm />

      <Card>
        {/* The Main Table */}
        <TableContainer component={Paper}>
          <Table aria-label="collapsible table">
            <TableBody>
              <TableRow>
                <TableCell style={headStyle} align="left" />
                {columns.map((column, index) => (
                  <TableCell style={headStyle} key={index} align={column.align}>
                    {column.label}
                  </TableCell>
                ))}
                <TableCell style={headStyle} align="center">
                  Status
                </TableCell>
                {/* <TableCell style={headStyle} align="center">
                  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, index) => (
                  <Row key={index} row={row} />
                ))}
              </TableBody>
            )}
          </Table>
        </TableContainer>

        <BasePagination paginationData={dataTableData} onPageChange={handlePageChange} />
      </Card>
    </Stack>
  );
}
