// @mui
import {
  Button,
  Card,
  IconButton,
  MenuItem,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography,
  Stack,
  Collapse,
  Box,
  FormControl,
  InputLabel,
  Select,
  FormHelperText,
  Menu,
  ButtonGroup
} from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
// hooks
import React, { ChangeEvent, useEffect, useRef, useState } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
// components
import axios from '../../../utils/axios';
import { Hospital } from '../../../@types/corporates';
import { LaravelPaginatedData } from '../../../@types/paginated-data';
import BasePagination from '../../../components/BasePagination';
import TableMoreMenu from '@/components/table/TableMoreMenu';
import EditOutlinedIcon from '@mui/icons-material/EditOutlined';
import HistoryIcon from '@mui/icons-material/History';
import FindInPageOutlinedIcon from '@mui/icons-material/FindInPageOutlined';
import CachedOutlinedIcon from '@mui/icons-material/CachedOutlined';
import { Dialog, DialogTitle, DialogContent, DialogActions } from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import { enqueueSnackbar } from 'notistack';
import Label from '../../../components/Label';
import DownloadIcon from '@mui/icons-material/Download';
import { LoadingButton } from '@mui/lab';
import CancelIcon from '@mui/icons-material/Cancel';
import UploadIcon from '@mui/icons-material/Upload';

export default function HospitalList() {
  const { corporate_id } = useParams();
  const [searchParams, setSearchParams] = useSearchParams();
  const navigate = useNavigate();

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

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

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

    return (
      <React.Fragment>
        <TableRow sx={{ '& > *': open ? {borderBottom: 'unset'} : {}, cursor: open ? 'pointer' : '' }} onClick={() => {if(open==true) setOpen(!open)}}>
          <TableCell align="left">{row.code ? row.code : '-'}</TableCell>
          <TableCell align="left">{row.name ? row.name : '-'}</TableCell>
          <TableCell align="left">
            {row.active === 1 ? (
              <Label color='success' >
                Active
              </Label>
            ) : ( 
              <Label color='error'>
                Inactive
              </Label>
            )}
            </TableCell>
          <TableCell align="left">
            <TableMoreMenu actions={
              <>
                <MenuItem onClick={() => setOpen(!open)}>
                  <FindInPageOutlinedIcon />
                  Details
                </MenuItem>
                <MenuItem onClick={() => handleEditData(row)}>
                  <EditOutlinedIcon />
                  Edit
                </MenuItem>
                <MenuItem onClick={() => handleEditDataStatus(row)}>
                  <CachedOutlinedIcon />
                  Update Status
                </MenuItem>
                <MenuItem onClick={() => navigate ('/corporates/'+corporate_id+'/hospitals/'+row.id+'/history')}>
                  <HistoryIcon />
                  History
                </MenuItem>
              </>
              }
            />
          </TableCell>
        </TableRow>
        {/* COLLAPSIBLE ROW */}
        <TableRow sx={{display: open ? '' : 'none', cursor: open ? 'pointer' : ''}} onClick={() => {if(open==true) setOpen(!open)}}>
          <TableCell colSpan={4}>
            <Collapse in={open} timeout="auto" unmountOnExit>
              <Card sx={{padding:2}}>
                <Box sx={{ pb: 2 }}>
                  <Typography variant='subtitle1'>Detail</Typography>
                  <Stack marginTop={2}>
                    <Stack direction='row' spacing={1}>
                      <Typography variant='body2' sx={{color: style1.color, width: '50%'}}>Code:</Typography>
                      <Typography variant='body2' sx={{width: '50%'}}>{row.code ? row.code : '-'}</Typography>
                    </Stack>
                    <Stack direction='row' spacing={1}>
                      <Typography variant='body2' sx={{color: style1.color, width: '50%'}}>Hospital Name:</Typography>
                      <Typography variant='body2' sx={{width: '50%'}}>{row.name ? row.name : '-'}</Typography>
                    </Stack>
                  </Stack>
                </Box>
              </Card>
            </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: any | null = null) => {
    setDataTableLoading(true);
    const filter = appliedFilter ? appliedFilter : Object.fromEntries([...searchParams.entries()]);
    // Get Data Hospitals
    const response = await axios.get('/corporates/' + corporate_id + '/hospitals', {
      params: filter,
    });
    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();
  }, []);

  //validation dialog
  const [nameField, setNameField] = useState('');
  const [codeField, setCodeField] = useState('');
  // ID for edit data
  const [idField, setIdField] = useState('');

  const handleAddData = () => {
    navigate('/corporates/'+corporate_id+'/hospitals/create');
  }
  //Edit data
  const handleEditData = (data : any) => {
    navigate('/corporates/'+corporate_id+'/hospitals/edit/'+data.id+'/'+data.organization_id);  
  }
  // End dialog for hospitals

  // Dialog for update status hospitals
  const [openDialogStatus, setOpenDialogStatus] = useState(false);
  const [activeField, setActiveField] = useState(0);
  const [reasonUpdate,setReasonUpdate] = useState('Agreement changed');

  const handleCloseDialogUpdate = () => {
    setOpenDialogStatus(false);
    setNameField('');
    setCodeField('');
    setIdField('');
    setActiveField(activeField);
  }

  const handleSaveUpdateData = () => {
    let activeValue = 0;
    if(activeField === 1)
    {
      activeValue = 0;
    }
    else
    {
      activeValue = 1;
    }
    const updateData = {
      reason: reasonUpdate,
      active : activeValue,
      id: idField,
    };
    axios
      .put('/hospitals/'+idField+'/activation', updateData)
      .then((response) => {
        enqueueSnackbar('Data updated successfully', { variant: 'success' });
        loadDataTableData();
        handleCloseDialogUpdate();
      })
      .catch((error) => {
        enqueueSnackbar('Failed to add data', { variant: 'error' });
      });
  }

  const handleEditDataStatus = (data: any) => {
    setIdField(data.id);
    setNameField(data.name);
    setCodeField(data.code);
    setActiveField(data.active);
    setOpenDialogStatus(true);    
  }
  // End dialog for update status devisions

  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
  const createMenu = Boolean(anchorEl);
  const importHospital = useRef<HTMLInputElement>(null);
  const [currentImportFileName, setCurrentImportFileName] = useState(null);
  const [importLoading, setImportLoading] = useState(false);
  const [importResult, setImportResult] = useState(null);
  const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
      setAnchorEl(event.currentTarget);
  };
  const handleClose = () => {
      setAnchorEl(null);
  };
  const handleImportButton = () => {
      if (importHospital?.current) {
        handleClose();
      importHospital.current ? importHospital.current.click() : console.log('No File selected');
      } else {
        alert('No file selected');
      }
  };
  const handleCancelImportButton = () => {
    if(importHospital.current)
    {
        importHospital.current.value = '';
        importHospital.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(importHospital.current && importHospital.current.files)
    {
        if (importHospital.current?.files.length) {
            const formData = new FormData();
            formData.append('file', importHospital.current?.files[0]);
            setImportLoading(true);
            axios
                .post('corporates/'+corporate_id+'/hospitals/import', formData)
                .then((response) => {
                handleCancelImportButton();
                loadDataTableData();
                setImportResult(response.data);
                setImportLoading(false);
                enqueueSnackbar('Success Import Hospitals', { variant: 'success' });
                })
                .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 = () => {
    axios.get('corporates/hospitals/download-template').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 (
    <Stack>
      <input
          type="file"
          id="file"
          ref={importHospital}
          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"
              startIcon={<DownloadIcon />}
              sx={{ p: 1.8, color: '#FFFFFF', backgroundColor: '#19BBBB', width: '125px', height: '48px' }}
              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={handleAddData}>
                <Typography variant='body2'>Create</Typography>
              </MenuItem>
              <MenuItem onClick={handleImportButton}>
                  <Typography variant='body2'>Import</Typography>
              </MenuItem>
              <MenuItem
                  onClick={() => {
                      handleGetTemplate();
                  }}
              >
              <Typography variant='body2'> Download Template</Typography>
              </MenuItem>
              {/* <MenuItem onClick={handleICDList}>
              <Typography variant='body2'>Download ICD</Typography>
              </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.data.total_success_row ?? 0}
                  </Box>{' '}
                  Row Processed,{' '}
                  <Box sx={{ color: 'error.main', display: 'inline' }}>
                  {importResult.data.total_failed_row}
                  </Box>{' '}
                  Failed
                  {importResult.data.failed_rows.map((row, index) => (
                      <Typography variant='body' key={index} color="error"> [Code={row.code ? row.code : 'Required'},Name={row.name ? row.name : 'Required'}]</Typography>
                  ))}
              </Box>
              </Stack>
          )}
      <Card>
        {/* The Main Table */}
        <TableContainer component={Paper}>
          <Table aria-label="collapsible table">
            {/* Table Head */}
            <TableHead>
              <TableRow>
                <TableCell sx={{width: '20%'}} align="left">
                  <Typography variant='subtitle2'>Code</Typography>
                </TableCell>
                <TableCell sx={{width: '50%'}} align="left">
                  <Typography variant='subtitle2'>Hospital</Typography>
                </TableCell>
                <TableCell sx={{width: '20%'}} align="left">
                  <Typography variant='subtitle2'>Status</Typography>
                </TableCell>
                <TableCell sx={{width: '10%'}} align="left">
                </TableCell>
              </TableRow>
            </TableHead>
            {/* Condition Table Body */}
            {dataTableIsLoading ? (
              <TableBody>
                <TableRow>
                  <TableCell colSpan={4} align="center">
                    Loading
                  </TableCell>
                </TableRow>
              </TableBody>
            ) : dataTableData.data.length == 0 ? (
              <TableBody>
                <TableRow>
                  <TableCell colSpan={4} align="center">
                    No Data
                  </TableCell>
                </TableRow>
              </TableBody>
            ) : (
              <TableBody>
                {dataTableData.data.map((row) => (
                  <Row key={row.id} row={row} />
                ))}
              </TableBody>
            )}
          </Table>
        </TableContainer>
        {/* Paginations */}
        <BasePagination paginationData={dataTableData} onPageChange={handlePageChange} />
      </Card>
      {/* Dialog Update Status */}
      <Dialog open={openDialogStatus} onClose={handleCloseDialogUpdate} fullWidth={true}>
        <DialogTitle sx={{ backgroundColor: '#19BBBB', color: '#FFF', padding: 2 }}>
          <Stack direction="row" alignItems="center" justifyContent="space-between">
              <Stack direction="row" alignItems='center' spacing={1}>
                <Typography variant="h6">Update Status</Typography>
              </Stack>
              <IconButton sx={{ color: '#FFF' }} onClick={handleCloseDialogUpdate}>
                <CloseIcon />
              </IconButton>
          </Stack>
        </DialogTitle>
        <DialogContent>
          <Stack spacing={2} padding={2}>
            <Typography variant='body1'>Are you sure to {activeField == 1 ? 'Inactive' : 'Active'} this hospital ?</Typography>
            <Card sx={{padding:2}}  >
              <Stack direction='row' spacing={2}>
                <Typography variant='subtitle2' sx={{color: '#919EAB', width: '30%'}}>Code</Typography>
                <Typography variant='subtitle2' sx={{width: '70%'}}>{codeField}</Typography>
              </Stack>
              <Stack direction='row' spacing={2}>
                <Typography variant='subtitle2' sx={{color: '#919EAB', width: '30%'}}>Hospital Name</Typography>
                <Typography variant='subtitle2' sx={{width: '70%'}}>{nameField}</Typography>
              </Stack>
            </Card>
          </Stack>
          <Stack spacing={2} padding={2}>
            <Typography variant='subtitle1'>Reason for update*</Typography>
            <FormControl>
              <InputLabel htmlFor="reason" required>
                Reason for update
              </InputLabel>
              <Select
                id="reason"
                value={reasonUpdate}
                fullWidth
                label="Reason for update"
                onChange={(e) => {
                  setReasonUpdate(e.target.value);
                }}
                
              >
                <MenuItem value="Agreement changed">Agreement changed</MenuItem>
                <MenuItem value="Endorsement">Endorsement</MenuItem>
                <MenuItem value="Renewal">Renewal</MenuItem>
                <MenuItem value="Worng Setting">Worng Setting</MenuItem>
              </Select>
              <FormHelperText style={{ color: 'red' }}></FormHelperText>
            </FormControl>
          </Stack>
        </DialogContent>
        <DialogActions>
          <Button variant="outlined" sx={{color: '#212B36'}} onClick={handleCloseDialogUpdate}>Cancel</Button>
          <Button sx={{backgroundColor: activeField == 0 ? '#19BBBB' : '#FF4842'}} onClick={handleSaveUpdateData} variant="contained">{activeField == 1 ? 'Inactive' : 'Active'}</Button>
        </DialogActions>
      </Dialog>

    </Stack>
  );
}