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,
  Pagination,
  Grid,
  Chip,
  styled,
  DialogTitle,
  Dialog,
  DialogContent,
  DialogContentText,
  DialogActions,
  InputAdornment,
} 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 EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';

import {
  Link,
  NavLink as RouterLink,
  useSearchParams,
  useNavigate,
  useParams,
} from 'react-router-dom';
// hooks
import React, { ChangeEvent, Component, useEffect, useRef, useState } from 'react';
import useSettings from '../../../hooks/useSettings';
// components
import axios from '../../../utils/axios';
import { LaravelPaginatedData } from '../../../@types/paginated-data';
import { Icd } from '../../../@types/diagnosis';
import BasePagination from '../../../components/BasePagination';
import { Organizations } from '../../../@types/organization';
import CreateIcon from '@mui/icons-material/Create';
import { Props } from '../../../components/editor/index';
import { red } from '@mui/material/colors';
import { margin, padding } from '@mui/system';
import { enqueueSnackbar } from 'notistack';
import SvgIconStyle from '../../../components/SvgIconStyle';
// import ButtonCreate from '../../../components/ButtonCreate';
import { Search } from '@mui/icons-material';
import { Icon } from '@iconify/react';

// ----------------------------------------------------------------------

const getIcon = (name: string) => (
  <SvgIconStyle src={`/icons/${name}.svg`} sx={{ width: 1, height: 1 }} />
);

const ICONS = {
  show: getIcon('ic_show'),
  edit: getIcon('ic_edit'),
  delete: getIcon('ic_delete'),
};

export default function List() {
  // Generate the every row of the table

  const navigate = useNavigate();
  const { organization_id } = useParams();
  const [searchParams, setSearchParams] = useSearchParams();
  const [importResult, setImportResult] = useState(null);
  const Item = styled(Paper)(({ theme }) => ({
    textAlign: 'left',
  }));

  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 handleSearchSubmit = (event: any) => {
      event.preventDefault();
      props.onSearch(searchText); // Trigger to Parent
    };

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

    return (
      <form onSubmit={handleSearchSubmit} style={{ width: '100%' }}>
        <TextField
          id="search-input"
          ref={searchInput}
          variant="outlined"
          fullWidth
          onChange={handleSearchChange}
          value={searchText}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <Search />
              </InputAdornment>
            ),
            placeholder: 'Search',
          }}
        />
      </form>
    );
  }

  function ImportForm(props: any) {
    // IMPORT
    // Create Button Menu

    return (
      <Stack
        direction={'row'}
        spacing={2}
        sx={{ p: 2, justifyContent: 'flex-end', alignItems: 'center' }}
      >
        <SearchInput onSearch={applyFilter} />

        <Link to="/master/hospitals/create" style={{ textDecoration: 'none' }}>
          <Button variant="outlined" startIcon={<AddIcon />} sx={{ p: 1.8 }}>
            Create
          </Button>
        </Link>
      </Stack>
    );
  }

  function createData(organization: Organizations): Organizations {
    return {
      ...organization,
    };
  }

  function CheckStatus(props: { row: ReturnType<typeof createData> }) {
    const { row } = props;
    if (row.active === 1) {
      return (
        <Chip
          label="Aktif"
          size="small"
          sx={{
            backgroundColor: 'rgba(84, 214, 44, 0.16)',
            color: '#229A16',
            padding: '1 8 1 8 px',
            borderRadius: '4px',
            fontSize: '12px',
            fontWeight: 'bold',
          }}
        />
      );
    } else {
      return (
        <Chip
          label="Tidak Aktif"
          size="small"
          sx={{
            backgroundColor: 'rgba(255, 72, 66, 0.16)',
            color: '#B72136',
            padding: '1 8 1 8 px',
            borderRadius: '4px',
            fontSize: '12px',
            fontWeight: 'bold',
          }}
        />
      );
    }
  }

  function Row(props: { row: ReturnType<typeof createData> }) {
    const { row } = props;
    const [open, setOpen] = React.useState(false);
    const [openDialog, setOpenDialog] = React.useState(false);

    const handleActivate = (model: any, status: string) => {
      axios
        .put(`/organizations/${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.data.active;
              }
              return updatedModel;
            }),
          });
        })
        .catch((error) => {
          enqueueSnackbar(
            error.response.data.message ?? error.message ?? 'Failed Processing Request',
            { variant: 'error' }
          );
        });
    };

    const handleDelete = (model: any) => {
      axios
        .delete(`/organizations/${row.id}`)
        .then((res) => {
          setDataTableData({
            ...dataTableData,
            data: dataTableData.data.filter((model) => model.id != row.id),
          });
          enqueueSnackbar('Data berhasil dihapus', { variant: 'success' });
        })
        .catch((error) => {
          enqueueSnackbar(
            error.response.data.message ?? error.message ?? 'Failed Processing Request',
            { variant: 'error' }
          );
        });
    };

    return (
      <React.Fragment>
        <TableRow
          sx={{
            backgroundColor: open ? 'rgba(244, 246, 248, 0.5)' : '#fff',
            '& > *': { borderBottom: 'unset' },
          }}
        >
          <TableCell>
            <IconButton aria-label="expand row" size="small" onClick={() => setOpen(!open)}>
              {open ? <KeyboardArrowDownIcon /> : <KeyboardArrowRightIcon />}
            </IconButton>
          </TableCell>
          <TableCell align="left">{row.name}</TableCell>
          <TableCell align="left">{row.phone}</TableCell>
          <TableCell align="left">{row.address}</TableCell>

          <TableCell align="right">
            {/* <Stack direction="row"> */}
            <ButtonGroup variant="text" aria-label="text button group">
              <Link to={'/master/hospitals/' + row.id + '/edit'}>
                <Button>
                  <Icon icon="ph:pencil-simple-fill" style={{ width: '24px', height: '24px' }} />
                </Button>
              </Link>
              <Button
                onClick={() => {
                  setOpenDialog(true);
                }}
              >
                <Icon icon="eva:trash-2-outline" style={{ width: '24px', height: '24px' }} />
              </Button>
            </ButtonGroup>
            {/* </Stack> */}
          </TableCell>
        </TableRow>

        {/* COLLAPSIBLE ROW */}
        <TableRow>
          <TableCell
            style={{ paddingBottom: 0, paddingTop: 0, backgroundColor: 'rgba(244, 246, 248, 0.5)' }}
            colSpan={6}
          >
            <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}>
                        Kode Rumah Sakit
                      </Grid>
                      <Grid item xs={6}>
                        : {row.code ? row.code : '-'}
                      </Grid>

                      <Grid item xs={6}>
                        Longitude
                      </Grid>
                      <Grid item xs={6}>
                        : {row.lng ? row.lng : '-'}
                      </Grid>

                      <Grid item xs={6}>
                        Latittude
                      </Grid>
                      <Grid item xs={6}>
                        : {row.lat ? row.lat : '-'}
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </Box>
            </Collapse>
          </TableCell>
        </TableRow>

        {/* END COLLAPSIBLE ROW */}

        <Dialog
          open={openDialog}
          onClose={() => {
            setOpenDialog(false);
          }}
          aria-labelledby="alert-dialog-title"
          aria-describedby="alert-dialog-description"
        >
          {/* <DialogTitle id="alert-dialog-title">{'Hapus Dokter'}</DialogTitle> */}
          <DialogContent sx={{ p: 5 }}>
            <Icon
              icon="eva:trash-2-outline"
              style={{
                width: '100px',
                height: '100px',
                color: '#FF0000',
                margin: 'auto',
                display: 'block',
                marginBottom: '20px',
                alignContent: 'center',
              }}
            />
            <DialogContentText sx={{ fontWeight: 'bold', pb: 1 }} id="alert-dialog-title">
              Apakah anda yakin ingin menghapus
            </DialogContentText>
            <Typography sx={{ fontWeight: 'bold' }} id="alert-dialog-title">
              {row.name}?
            </Typography>
          </DialogContent>
          <DialogActions>
            <Button
              onClick={() => {
                setOpenDialog(false);
              }}
              color="primary"
              variant="outlined"
            >
              Batal
            </Button>
            <Button
              onClick={() => {
                handleDelete(row.id);
              }}
              color="primary"
              variant="contained"
              autoFocus
            >
              Hapus
            </Button>
          </DialogActions>
        </Dialog>
      </React.Fragment>
    );
  }
  const headStyle = {
    fontWeight: 'bold',
  };
  // Dummy Default Data
  const [dataTableIsLoading, setDataTableLoading] = useState(true);
  const [dataTableLastRequest, setDataTableLastRequest] = useState(0);
  const [dataTableResponseState, setDataTableResponseState] = useState('idle');
  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 [dataTablePage, setDataTablePage] = useState(5);

  const loadDataTableData = async (appliedFilter: any | null = null) => {
    setDataTableLoading(true);
    const filter = appliedFilter ? appliedFilter : Object.fromEntries([...searchParams.entries()]);
    const response = await axios.get('/organizations', {
      params: filter,
    });
    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();
  }, []);

  return (
    <Stack>
      {/* <Ambulace /> */}

      <Card sx={{ marginTop: '30px' }}>
        <ImportForm sx={{ marginTop: '100px' }} />

        {/* The Main Table */}
        <TableContainer component={Paper}>
          <Table aria-label="collapsible table">
            <TableBody>
              <TableRow>
                <TableCell style={headStyle} align="left" />
                <TableCell style={headStyle} align="left">
                  Rumah Sakit
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Nomor IGD
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Alamat
                </TableCell>
                {/* <TableCell style={headStyle} align="center">
                  Aksi
                </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>
  );
}
