// @mui
import { Box, Button, Card, Collapse, IconButton, InputLabel, MenuItem, OutlinedInput, Paper, Grid, Select, SelectChangeEvent, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, Typography, Badge, Tab, Tabs, CardHeader, Stack, Menu, ButtonGroup, Pagination } 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 { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
// components
import axios from '../../../../utils/axios';
import { LaravelPaginatedData } from '../../../../@types/paginated-data';
import { Icd } from '../../../../@types/diagnosis';
import BasePagination from '../../../../components/BasePagination';
import { enqueueSnackbar } from 'notistack';
import DetailFormularium from "./DetailFormularium";
import { FormulariumData } from '../Type';


export default function List() {
  const navigate = useNavigate();
  const { id: formularium_template_id } = useParams();
  const [searchParams, setSearchParams] = useSearchParams();
  const [importResult, setImportResult] = useState(null);
  const { isActive } = useLocation().state as { isActive: number }

  function SearchInput(props: any) {
    const searchInput = useRef<HTMLInputElement>(null);
    const [searchText, setSearchText] = useState("");

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

    const handleSearchSubmit = (event: any) => {
      event.preventDefault();
      props.onSearch(searchText);
    }

    useEffect(() => {
      setSearchText(searchParams.get('search') ?? '');
    }, [searchParams])

    return (
      <form onSubmit={handleSearchSubmit} style={{width: '100%'}}>
        <TextField
          id='search-input'
          ref={searchInput}
          label='search'
          variant='outlined'
          fullWidth
          onChange={handleSearchChange}
          value={searchText} 
        />
      </form>
    );
  }

  function ImportForm( props: any ) {
    const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
    const createMenu = Boolean(anchorEl);
    const importForm = useRef<HTMLInputElement>(null) 
    const [currentImportFileName, setCurrentImportFileName] = useState(null)

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

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

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

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

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

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

    const handleFormulariumList = async (appliedFilter = null) => {
      axios.get(`master/formulariums/${formularium_template_id}/list`)
        .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();
          enqueueSnackbar('Download Success', { variant: 'success' })
        })
        .catch(response => {
          enqueueSnackbar('Looks like something went wrong. Please check your data and try again. ' + response.message, { variant: 'error' })
        });
    }

    const handleUpload = () => {
      if (importForm.current?.files?.length) {
        const formData = new FormData();
        formData.append('file', importForm.current?.files[0])
        axios.post(`master/formulariums/${formularium_template_id}/import`, formData )
          .then(response => {
            handleCancelImportButton();
            loadDataTableData();
            setImportResult(response.data);
          })
          .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={importForm} 
          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}/>
              <Button 
                id='import-button'
                variant='outlined'
                startIcon={<AddIcon />}
                sx={{ 
                  p: 1.8,
                  width: '200px',
                  backgroundColor: '#19BBBB', color: '#FFF',
                  "&:hover":{
                    backgroundColor: "#19BBBB", color: '#FFF'
                  },
                }}
                aria-controls={createMenu ? 'basic-menu' : undefined}
                aria-haspopup="true"
                aria-expanded={createMenu ? 'true' : undefined}
                onClick={handleClick}
              >
                Create
              </Button>
              <Menu
                id='import-button'
                anchorEl={anchorEl}
                open={createMenu}
                onClose={handleClose}
                MenuListProps={{
                  'aria-labelledby': 'basic-button',
                }}
              >
                <MenuItem onClick={handleImportButton}>Import</MenuItem>
                <MenuItem onClick={() => handleGetTemplate('master-formularium')}>Download Template</MenuItem>
                <MenuItem onClick={() => handleFormulariumList()}>Download Formularium</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>
    );
  }

  // Default data
  const [dataTableRow, setDataTableRow] = useState<FormulariumData[] | null>(null)
  const [dataTableIsLoading, setDataTableLoading] = useState(true);
  const [dataTableData, setDataTableData] = 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(`/master/formulariums/${formularium_template_id}`, { params: filter });
    setDataTableLoading(false);

    console.log(formularium_template_id)
    console.log(response)
    setDataTableData(response.data)
    setDataTableRow(response.data.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();
  }, [])

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

  return (
    <Stack>
      <ImportForm />
      <Card>
        <TableContainer component={Paper}>
          <Table aria-label='collapsible table'>
            <TableHead>
              <TableRow>
                <TableCell style={headStyle} align='left' width={50}/>
                <TableCell style={headStyle} align='left'>Code</TableCell>
                <TableCell style={headStyle} align='left'>ATC Code</TableCell>
                <TableCell style={headStyle} align='left'>Name</TableCell>
                <TableCell style={headStyle} align='left'>Category Name</TableCell>
                <TableCell style={headStyle} align='left'>UOM</TableCell>
                <TableCell style={headStyle} align='left'>Status</TableCell>
                <TableCell style={headStyle} align='center' width={100}></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>
            ) : (
              dataTableRow?.map(item => (
                <DetailFormularium props={item} isActive={1}/>
              ))
            )}
          </Table>
        </TableContainer>

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