import {
  Box,
  Button,
  Card,
  Collapse,
  Paper,
  Select,
  SelectChangeEvent,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography,
  Stack,
  ButtonGroup,
  Grid,
  Chip,
  Dialog,
  DialogContent,
  DialogContentText,
  DialogActions,
  FormControl,
  Autocomplete,
  InputAdornment,
  IconButton,
} from '@mui/material';

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 { Practitioner } from '../../../@types/doctor';
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 { Controller } from 'react-hook-form';

import SvgIconStyle from '../../../components/SvgIconStyle';
import { GridSearchIcon } from '@mui/x-data-grid';
import { Search } from '@mui/icons-material';
import { Icon } from '@iconify/react';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight';

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

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

  const navigate = useNavigate();
  const { organization_id } = useParams();
  const [searchParams, setSearchParams] = useSearchParams();
  const [searchParamsOrganizations, setSearchParamsOrganizations] = useSearchParams();
  const [searchParamsSpecialities, setSearchParamsSpecialities] = useSearchParams();
  const [searchParamsFilter, setSearchParamsFilter] = useSearchParams();

  function Filter(props: any) {
    // SEARCH
    const searchInput = useRef<HTMLInputElement>(null);
    const [searchText, setSearchText] = useState('');

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

    const handleSearchSubmit = (event: any) => {
      event.preventDefault();

      props.onSearch(searchText);
    };

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

    const item = [
      {
        id: '',
        value: '',
        name: 'Semua',
      },
    ];

    return (
      <form style={{ width: '100%' }}>
        <Grid container spacing={2} sx={{ justifyContent: 'space-between', alignItems: 'center' }}>
          <Grid item xs={12} sm={12} md={12} lg={12}>
            <TextField
              id="search-input"
              ref={searchInput}
              variant="outlined"
              fullWidth
              onChange={handleSearchChange}
              onKeyDown={(event) => {
                if (event.key === 'Enter') {
                  handleSearchSubmit(event);
                }
              }}
              value={searchText}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <Search />
                  </InputAdornment>
                ),
                placeholder: 'Search',
              }}
            />
          </Grid>
        </Grid>
      </form>
    );
  }

  function FilterForm(props: any) {
    // IMPORT
    return (
      <Grid
        container
        spacing={2}
        sx={{ p: 2, justifyContent: 'space-between', alignItems: 'center' }}
      >
        <Grid item xs={12} md={12} lg={12}>
          <Filter onSearch={applyItems} />
        </Grid>
      </Grid>
    );
  }

  function createData(doctor: Practitioner): Practitioner {
    return {
      ...doctor,
    };
  }

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

    const handleDelete = (model: any) => {
      axios
        .delete(`/doctors/${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>
          <TableCell>
            <IconButton aria-label="expand row" size="small" onClick={() => setOpen(!open)}>
              {open ? <KeyboardArrowDownIcon /> : <KeyboardArrowRightIcon />}
            </IconButton>
          </TableCell>
          <TableCell align="left">{row.date_created ? row.date_created : '-'}</TableCell>
          <TableCell align="left">{row.date_appointment ? row.date_appointment : '-'}</TableCell>
          <TableCell align="left">{row.booking_code ?? '-'}</TableCell>
          <TableCell align="left">{row.patient_name ? row.patient_name : '-'}</TableCell>
          <TableCell align="left">{row.health_care ? row.health_care : '-'}</TableCell>
          <TableCell align="left">{row.doctor_name ? row.doctor_name : '-'}</TableCell>
          <TableCell align="left">{row.type ? row.type : '-'}</TableCell>

          <TableCell align="left">{row.status ? row.status : '-'}</TableCell>
          <TableCell align="center">
            <ButtonGroup variant="text" aria-label="text button group">
              <Link to={'/report/appointments/' + row.id + '/show'}>
                <Button>
                  <Icon icon="ph:eye-bold" style={{ width: '24px', height: '24px' }} />
                </Button>
              </Link>
            </ButtonGroup>
          </TableCell>
        </TableRow>
        <TableRow>
          <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={15}>
            <Collapse in={open} timeout="auto" unmountOnExit>
              <Stack>
                <Grid container>
                  <Grid item xs={2}>Spesialisasi</Grid><Grid item xs="10">: {row.speciality}</Grid>
                  <Grid item xs={2}>Via</Grid><Grid item xs="10">: {row.appointment_media}</Grid>
                  <Grid item xs={2}>Metode Pembayaran</Grid><Grid item xs="10">: {row.payment_method}</Grid>
                  <Grid item xs={2}>HIS RegID</Grid><Grid item xs="10">: {row.his_detail?.sRegID}</Grid>
                  <Grid item xs={2}>HIS Medrec</Grid><Grid item xs="10">: {row.his_detail?.Medrec}</Grid>
                  <Grid item xs={2}>No HP</Grid><Grid item xs="10">: {row.patient?.sPhone ?? ''}</Grid>
                  <Grid item xs={2}>E-mail</Grid><Grid item xs="10">: {row.patient?.sEmail ?? ''}</Grid>
                  <Grid item xs={2}>Alamat</Grid><Grid item xs="10">: {row.patient?.detail?.sAlamat ?? ''}</Grid>
                  <Grid item xs={2}>KTP</Grid><Grid item xs="10">: {row.patient?.detail?.sKTP ?? ''}</Grid>
                </Grid>
              </Stack>  
            </Collapse>
          </TableCell>
        </TableRow>

        <Dialog
          open={openDialog}
          onClose={() => {
            setOpenDialog(false);
          }}
          aria-labelledby="alert-dialog-title"
          aria-describedby="alert-dialog-description"
        >
          <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"
            >
              Batal
            </Button>
            <Button
              onClick={() => {
                handleDelete(row.id);
              }}
              color="primary"
              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('/appointments', {
      params: filter,
    });
    setDataTableLoading(false);
    setDataTableData(response.data);
  };

  // const applyFilter = async (searchFilter: string) => {
  //   await loadDataTableData({ search: searchFilter });
  //   setSearchParams({ search: searchFilter });
  // };

  const applyItems = async (
    searchFilter: string,
    searchFilterOrganization: string,
    searchFilterSpecialities: string
  ) => {
    await loadDataTableData({
      search: searchFilter,
      organization_id: searchFilterOrganization,
      speciality_id: searchFilterSpecialities,
    });
    setSearchParamsFilter({
      search: searchFilter,
      organization_id: searchFilterOrganization,
      speciality_id: searchFilterSpecialities,
    });
  };

  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' }}>
        <FilterForm sx={{ marginTop: '100px' }} />

        {/* The Main Table */}
        <TableContainer component={Paper}>
          <Table>
            <TableBody>
              <TableRow>
                <TableCell style={headStyle} align="left" />
                <TableCell style={headStyle} align="left">
                  Tanggal Pemesanan
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Tanggal Appointment
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Kode Booking
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Pasien
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Faskes
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Dokter
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Jenis
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Status Appointment
                </TableCell>
                <TableCell style={headStyle} align="left" />

                {/* <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>
  );
}
