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';
import AddIcon from '@mui/icons-material/Add';

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

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 [seacrhOrganizations, setSearchOrganizations] = useState('');
    const [searchSpecialities, setSearchSpecialities] = useState('');
    const [searchText, setSearchText] = useState('');

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

    const handleSearchOrganizations = (event: any) => {
      const newSearchOrganizations = event.id ?? '';
      console.log(newSearchOrganizations);
      setSearchOrganizations(newSearchOrganizations);
    };

    const handleSearchSpecialities = (event: any) => {
      const newSearchSpecialities = event.id ?? '';
      setSearchSpecialities(newSearchSpecialities);
    };

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

      props.onSearch(searchText, seacrhOrganizations, searchSpecialities);
    };

    const [organization, setOrganization] = useState<any>([]);
    const [specialities, setSpecialities] = useState<any>([]);

    useEffect(() => {
      axios.get(`/search-organizations`).then((response) => {
        setOrganization(response.data);
      });

      axios.get(`/search-specialities`).then((response) => {
        setSpecialities(response.data);
      });

      // Trigger First Search
      setSearchText(searchParams.get('search') ?? '');
      setSearchOrganizations(searchParamsOrganizations.get('organization_id') ?? '');
      setSearchSpecialities(searchParamsSpecialities.get('speciality_id') ?? '');
    }, []);

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

    //item search
    const dataOrganizations = item.concat(organization);
    const dataSpecialities = item.concat(specialities);

    return (
      <form style={{ width: '100%' }}>
        <Grid container spacing={2} sx={{ justifyContent: 'space-between', alignItems: 'center' }}>
          <Grid item xs={12} sm={12} md={8} lg={8}>
            <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 item xs={12} sm={4} md={2} lg={2}>
            <Autocomplete
              id="organizations"
              options={dataOrganizations}
              value={dataOrganizations.find((v) => v.id == seacrhOrganizations)}
              getOptionLabel={(option) => option.name}
              onChange={(event, value) => {
                handleSearchOrganizations(value);
              }}
              onKeyDown={(event) => {
                if (event.key === 'Enter') {
                  handleSearchSubmit(event);
                }
              }}
              renderInput={(params) => (
                <TextField {...params} label="Rumah Sakit" variant="outlined" fullWidth />
              )}
            />
          </Grid>
          <Grid item xs={12} sm={4} md={2} lg={2}>
            <Autocomplete
              id="specialities"
              options={dataSpecialities}
              getOptionLabel={(option) => option.name}
              value={dataSpecialities.find((v) => v.id == searchSpecialities)}
              onChange={(event, value) => handleSearchSpecialities(value)}
              onKeyDown={(event) => {
                if (event.key === 'Enter') {
                  handleSearchSubmit(event);
                }
              }}
              renderInput={(params) => (
                <TextField {...params} label="Spesialis" variant="outlined" fullWidth />
              )}
            />
          </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={10} lg={10}>
          <Filter onSearch={applyItems} />
        </Grid>
        <Grid item xs={12} md={2} lg={2} sx={{ textAlign: 'right' }}>
          <Link to="/master/doctors/create" style={{ textDecoration: 'none' }}>
            <Button variant="outlined" startIcon={<AddIcon />} sx={{ p: 1.8 }}>
              Create
            </Button>
          </Link>
        </Grid>
      </Grid>
    );
  }

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

  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 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.name ? row.name : '-'}</TableCell>

          <TableCell align="left">
            {row.organizations?.map((org) => org.organization_name).join(', ') ?? '-'}
          </TableCell>
          <TableCell align="left">
            {row.specialties ? row.specialties.map((spec) => spec.specialty_name).join(', ') : '-'}
          </TableCell>
          <TableCell align="left">{row.address ? row.address : '-'}</TableCell>
          {/* <TableCell align="left">
            <CheckStatus row={row} />
          </TableCell> */}

          <TableCell align="center">
            <ButtonGroup variant="text" aria-label="text button group">
              <Link to={'/master/doctors/' + 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>
          </TableCell>
        </TableRow>
        {/* COLLAPSIBLE ROW */}
        <TableRow>
          <TableCell
            style={{ paddingBottom: 0, paddingTop: 0, backgroundColor: 'rgba(244, 246, 248, 0.5)' }}
            colSpan={9999}
          >
            <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}>
                        Pendidikan
                      </Grid>
                      <Grid item xs={6}>
                        : {row.education ? row.education : '-'}
                      </Grid>

                      <Grid item xs={6}>
                        Pengalaman Kerja
                      </Grid>
                      <Grid item xs={6}>
                        : {row.experience ? row.experience : '-'}
                      </Grid>

                      <Grid item xs={6}>
                        Jenis Kelamin
                      </Grid>
                      <Grid item xs={6}>
                        :{' '}
                        {row.gender == 'male'
                          ? 'Laki-Laki'
                          : row.gender == 'female'
                          ? 'Perempuan'
                          : '-'}
                      </Grid>
                    </Grid>
                  </Grid>
                  <Grid item xs={6} sx={{ padding: 2 }}>
                    <Grid container>
                      <Grid item xs={6}>
                        Email
                      </Grid>
                      <Grid item xs={6}>
                        : {row.email ? row.email : '-'}
                      </Grid>

                      <Grid item xs={6}>
                        No. Telp
                      </Grid>
                      <Grid item xs={6}>
                        : {row.phone ? row.phone : '-'}
                      </Grid>

                      <Grid item xs={6}>
                        Penghargaan
                      </Grid>
                      <Grid item xs={6}>
                        : {row.award ? row.award : '-'}
                      </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"
        >
          <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('/doctors', {
      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">
                  Nama Dokter
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Rumah Sakit
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Spesialis
                </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>
  );
}
