// @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';
// 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 BasePagination from '../../../components/BasePagination';
import { enqueueSnackbar } from 'notistack';

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

  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 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]);
        axios
          .post(`corporates/${corporate_id}/import-plan-benefit`, formData)
          .then((response) => {
            handleCancelImportButton();
            loadDataTableData();
            setImportResult(response.data);
            // alert('Succesfully read '+ response.data.total_successed_row + ' with ' + response.data.total_failed_row + ' failed rows');
          })
          .catch((response) => {
            enqueueSnackbar(
              'Looks like something went wrong. Please check your data and try again. ' +
                response.message,
              { variant: 'error' }
            );
          });
      } else {
        enqueueSnackbar('No File Selected', { variant: 'warning' });
      }
    };

    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={handleClose}>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>

            <Button
              id="upload-button"
              variant="outlined"
              startIcon={<UploadIcon />}
              sx={{ p: 1.8 }}
              onClick={handleUpload}
            >
              Upload
            </Button>
          </Stack>
        )}
        {importResult && (
          <Stack direction={'row'} sx={{ px: 2, pb: 2 }}>
            <Box sx={{ color: 'text.secondary' }}>
              Last Import Result 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(plan: Plan): Plan {
    return {
      ...plan,
    };
  }

  // 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(`/plans/${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.plan.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.service_code}</TableCell>
          <TableCell align="left">{row.corporate_plan_id}</TableCell>
          <TableCell align="left">{row.code}</TableCell>
          <TableCell align="left">{row.type}</TableCell>

          <TableCell align="left">{row.limit_rules}</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="center">
            <Button variant="outlined" color="success" size="small">
              Edit
            </Button>
          </TableCell>
        </TableRow>
        {/* COLLAPSIBLE ROW */}
        <TableRow>
          <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={15}>
            <Collapse in={open} timeout="auto" unmountOnExit>
              <Box sx={{ margin: 1, pb: 2, pl: 4 }}>
                <Grid container>
                  <Grid item xs={6} sx={{ padding: 2 }}>
                    <Grid container>
                      <Grid item xs={6}>
                        Start
                      </Grid>
                      <Grid item xs={6}>
                        : {row.start ? row.start : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        End
                      </Grid>
                      <Grid item xs={6}>
                        : {row.end ? row.end : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Referal
                      </Grid>
                      <Grid item xs={6}>
                        : {row.require_referral ? row.require_referral : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Referral Source
                      </Grid>
                      <Grid item xs={6}>
                        : {row.referral_source ? row.referral_source : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Referral Duration
                      </Grid>
                      <Grid item xs={6}>
                        : {row.referral_duration ? row.referral_duration : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Family Plan
                      </Grid>
                      <Grid item xs={6}>
                        : {row.family_plan ? row.family_plan : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Family Sharing Overflow
                      </Grid>
                      <Grid item xs={6}>
                        : {row.family_plan_share_rules ? row.family_plan_share_rules : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Max/Claim
                      </Grid>
                      <Grid item xs={6}>
                        : {row.max_claim_limit ? row.max_claim_limit : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Max Count of Claim
                      </Grid>
                      <Grid item xs={6}>
                        : {row.max_claim_count ? row.max_claim_count : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Area
                      </Grid>
                      <Grid item xs={6}>
                        : {row.area_limit ? row.area_limit : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Shared Plan
                      </Grid>
                      <Grid item xs={6}>
                        : {row.limit_shared_plans ? row.limit_shared_plans : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Limit Shared Type
                      </Grid>
                      <Grid item xs={6}>
                        : {row.limit_shared_plan_type ? row.limit_shared_plan_type : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Cashless(%)
                      </Grid>
                      <Grid item xs={6}>
                        : {row.cashless_percentage ? row.cashless_percentage : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Reimbursement(%)
                      </Grid>
                      <Grid item xs={6}>
                        : {row.reimbursement_percentage ? row.reimbursement_percentage : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Digital(%)
                      </Grid>
                      <Grid item xs={6}>
                        : {row.digital_deductible ? row.digital_deductible : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        CoShare M(%)
                      </Grid>
                      <Grid item xs={6}>
                        : {row.co_share_m_percentage ? row.co_share_m_percentage : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        CoShare S(%)
                      </Grid>
                      <Grid item xs={6}>
                        : {row.co_share_s_percentage ? row.co_share_s_percentage : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        CoShare C(%)
                      </Grid>
                      <Grid item xs={6}>
                        : {row.co_share_c_percentage ? row.co_share_c_percentage : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Cashless Deductible
                      </Grid>
                      <Grid item xs={6}>
                        : {row.cashless_deductible ? row.cashless_deductible : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Reimbursement Deductible
                      </Grid>
                      <Grid item xs={6}>
                        : {row.reimbursement_deductible ? row.reimbursement_deductible : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Digital Deductible
                      </Grid>
                      <Grid item xs={6}>
                        : {row.digital_deductible ? row.digital_deductible : '-'}
                      </Grid>
                    </Grid>
                  </Grid>
                  <Grid item xs={6} sx={{ padding: 2 }}>
                    <Grid container>
                      <Grid item xs={6}>
                        Layer ID
                      </Grid>
                      <Grid item xs={6}>
                        : {row.layer ? row.layer : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Layer Condition
                      </Grid>
                      <Grid item xs={6}>
                        : {row.layer_conditions ? row.layer_conditions : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Budget Type
                      </Grid>
                      <Grid item xs={6}>
                        : {row.budget_type ? row.budget_type : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Budget Code
                      </Grid>
                      <Grid item xs={6}>
                        : {row.budget_code ? row.budget_code : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Budget Condition
                      </Grid>
                      <Grid item xs={6}>
                        : {row.budget_conditions ? row.budget_conditions : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Surgery
                      </Grid>
                      <Grid item xs={6}>
                        : {row.surgery_limit ? row.surgery_limit : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Non Surgery
                      </Grid>
                      <Grid item xs={6}>
                        : {row.non_surgery_limit ? row.non_surgery_limit : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        DeductibleM
                      </Grid>
                      <Grid item xs={6}>
                        : {row.co_share_m_deductible ? row.co_share_m_deductible : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        DeductibleS
                      </Grid>
                      <Grid item xs={6}>
                        : {row.co_share_s_deductible ? row.co_share_s_deductible : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        DeductibleC
                      </Grid>
                      <Grid item xs={6}>
                        : {row.co_share_c_deductible ? row.co_share_c_deductible : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        CoShare & Deductible Condition
                      </Grid>
                      <Grid item xs={6}>
                        :
                        {row.co_share_deductible_condition
                          ? row.co_share_deductible_condition
                          : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        MSC
                      </Grid>
                      <Grid item xs={6}>
                        : {row.msc ? row.msc : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Gender
                      </Grid>
                      <Grid item xs={6}>
                        : {row.genders ? row.genders : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Min Age
                      </Grid>
                      <Grid item xs={6}>
                        : {row.min_age ? row.min_age : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Max Age
                      </Grid>
                      <Grid item xs={6}>
                        : {row.max_age ? row.max_age : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Rule of Excess
                      </Grid>
                      <Grid item xs={6}>
                        : {row.rule_of_excess ? row.rule_of_excess : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Max Excess Covered
                      </Grid>
                      <Grid item xs={6}>
                        : {row.max_excess_covered ? row.max_excess_covered : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Prorate Type
                      </Grid>
                      <Grid item xs={6}>
                        : {row.prorate_type ? row.prorate_type : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Prorate Lookup
                      </Grid>
                      <Grid item xs={6}>
                        : {row.prorate_lookup ? row.prorate_lookup : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Currency
                      </Grid>
                      <Grid item xs={6}>
                        : {row.currency ? row.currency : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Reinstatement Surgery
                      </Grid>
                      <Grid item xs={6}>
                        :
                        {row.max_surgery_reinstatement_days
                          ? row.max_surgery_reinstatement_days
                          : '-'}
                      </Grid>
                      <Grid item xs={6}>
                        Period of Surgery
                      </Grid>
                      <Grid item xs={6}>
                        : {row.max_surgery_periode_days ? row.max_surgery_periode_days : '-'}
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </Box>
            </Collapse>
          </TableCell>
        </TableRow>
      </React.Fragment>
    );
  }

  // 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 + '/plans', { params: filter });
    // console.log(response.data);
    setDataTableLoading(false);

    setDataTableData(response.data);
  };

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

  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();
  }, []);

  return (
    <Stack>
      <ImportForm />

      <Card>
        {/* The Main Table */}
        <TableContainer component={Paper}>
          <Table aria-label="collapsible table">
            <TableBody>
              <TableRow>
                <TableCell style={headStyle} align="left" />
                <TableCell style={headStyle} align="left">
                  Service
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Plan
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Code
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Type
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Plan Limit
                </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) => (
                  <Row key={row.id} row={row} />
                ))}
              </TableBody>
            )}
          </Table>
        </TableContainer>

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