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,
  InputLabel,
} 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 AutocompleteHealthcare from '@/components/autocomplete/AutocompleteHealthcare';
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 { fNumber } from '@/utils/formatNumber';
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 { DesktopDatePicker, LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { MenuItem } from '@mui/material';
import { fDateOnly } from '@/utils/formatTime';
import AutocompleteLinksehatHealthcare from '@/components/autocomplete/AutocompleteLinksehatHealthcare';

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

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

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

  useEffect(() => {
    // axios.get(`/search-organizations`).then((response) => {
    //   setOrganizationOptions(response.data);
    // });
  }, []);

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

    const handleSearchStatus = (event: any) => {
      console.log('search status', 'Yeet');
    };

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

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

    const paymentStatusOptions = {
      settlement: 'Diterima',
      expired: 'Kadaluarsa',
      capture: 'Captured',
      deny: 'Ditolak',
      pending: 'Menunggu Pembayaran',
      cancel: 'Dibatalkan',
      refund: 'Dikembalikan',
      expire: 'Kadaluarsa',
      cod: 'COD',
      FAILED: 'Gagal',
      COMPLETED: 'Complete',
    };

    const dataOrganizations = [];

    return (
      <form style={{ width: '100%' }}>
        <Grid container spacing={2} sx={{ justifyContent: 'space-between', alignItems: 'center' }}>
          <Grid item md={4}>
            <TextField
              id="search-input"
              ref={searchInput}
              variant="outlined"
              fullWidth
              onChange={handleSearchChange}
              onKeyDown={(event) => {
                if (event.key === 'Enter') {
                  // handleSearchSubmit(event);

                  const filter = Object.fromEntries([
                    ...searchParams.entries(),
                    ['search', searchText],
                  ]);
                  setSearchParams(filter);
                  loadDataTableData(filter);
                }
              }}
              label="Search"
              value={searchText}
              InputProps={{
                // startAdornment: (
                //   <InputAdornment position="start">
                //     <Search />
                //   </InputAdornment>
                // ),
                placeholder: 'Id Pemesanan, Transaction ID',
              }}
            />
          </Grid>
          <Grid item md={2}>
            <FormControl fullWidth>
              <InputLabel>Payment Status</InputLabel>
              <Select
                value={searchParams.get('payment_status') ?? 'semua'}
                label="Payment Status"
                onChange={(el) => {
                  // console.log(el.target.value)
                  const filter = Object.fromEntries([
                    ...searchParams.entries(),
                    ['payment_status', el.target.value],
                  ]);
                  setSearchParams(filter);
                  loadDataTableData(filter);
                }}
              >
                <MenuItem value={'semua'}>Semua</MenuItem>
                {Object.entries(paymentStatusOptions).map((option, index) => (
                  <MenuItem value={option[0]} key={index}>
                    {option[1]}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Grid>
          <Grid item md={2}>
            <AutocompleteLinksehatHealthcare
              onChange={(value) => {
                if (value) {
                  const filter = Object.fromEntries([
                    ...searchParams.entries(),
                    ['healthcare_id', value.nID ?? ''],
                  ]);
                  setSearchParams(filter);
                  loadDataTableData(filter);
                  setOrganizationOptions([value]);
                } else {
                  const filter = Object.fromEntries([
                    ...searchParams.entries(),
                    ['healthcare_id', ''],
                  ]);
                  setSearchParams(filter);
                  loadDataTableData(filter);
                  setOrganizationOptions([]);
                }
              }}
              currentOptions={organizationOptions}
              currentValue={organizationOptions?.find(
                (org) => org?.nID == searchParams.get('healthcare_id')
              )}
              textLabel="Rumah Sakit"
              placeholder="Nama"
            />
          </Grid>

          <Grid item md={2}>
            <LocalizationProvider dateAdapter={AdapterDateFns}>
              <DesktopDatePicker
                value={searchParams.get('appointment_start')}
                inputFormat="dd/MM/yyyy"
                onChange={(value) => {
                  try {
                    if (value && !!Date.parse(value)) {
                      const date = value ? fDateOnly(value) : '';
                      var entries = [...searchParams.entries(), ['appointment_start', date ?? '']];
                      if (!searchParams.get('appointment_end')) {
                        entries = [...entries, ['appointment_end', date ?? '']];
                      }
                      const filter = Object.fromEntries(entries);

                      setSearchParams(filter);
                      loadDataTableData(filter);
                    }
                  } catch (e) {}
                }}
                renderInput={(params) => <TextField {...params} fullWidth label="Start" />}
              />
            </LocalizationProvider>
          </Grid>

          <Grid item md={2}>
            <LocalizationProvider dateAdapter={AdapterDateFns}>
              <DesktopDatePicker
                value={searchParams.get('appointment_end')}
                inputFormat="dd/MM/yyyy"
                onChange={(value) => {
                  try {
                    if (value && !!Date.parse(value)) {
                      const date = fDateOnly(value);
                      var entries = [...searchParams.entries(), ['appointment_end', date ?? '']];
                      if (!searchParams.get('appointment_start')) {
                        entries = [...entries, ['appointment_start', date ?? '']];
                      }
                      const filter = Object.fromEntries(entries);

                      setSearchParams(filter);
                      loadDataTableData(filter);
                    }
                  } catch (e) {}
                }}
                renderInput={(params) => (
                  <TextField
                    {...params}
                    fullWidth
                    label="End"
                    // error={!!error}
                    // helperText={error?.message}
                    // {...other}
                  />
                )}
              />
            </LocalizationProvider>
          </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>
    );
  }

  //TODO Create PaymentType
  function createData(payments: any): any {
    return {
      ...payments,
    };
  }

  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.health_care?.sHealthCare ?? '-'}</TableCell>
          <TableCell align="left">{row.detail?.sPaymentDetails?.settlement_time ?? row.detail?.sPaymentDetails?.transaction_time}</TableCell>
          <TableCell align="left">{row.detail?.dTanggalAppointment == '0000-00-00' ? fDateOnly(row.detail?.dCreateOn) : row.detail?.dTanggalAppointment }</TableCell>
          <TableCell align="left">{row.nID}</TableCell>
          <TableCell align="left">{row.sBookingCode ?? ''}</TableCell>
          <TableCell align="left">{row.doctor?.user?.full_name ?? '-'}</TableCell>
          <TableCell align="left">{row.user?.full_name ?? '-'}</TableCell>
          <TableCell align="left">{row.user?.sEmail ?? '-'}</TableCell>
          <TableCell align="left">{row.type ?? '-'}</TableCell>
          <TableCell align="left">{row.payment_method ?? '-'}</TableCell>
          <TableCell align="left">{'-'}</TableCell>
          <TableCell align="left">
            {fNumber(parseInt(row.detail?.sPaymentDetails?.gross_amount ?? 0))}
          </TableCell>
          <TableCell align="left">{fNumber(parseInt(row.share_konsultasi))}</TableCell>
          <TableCell align="left">{fNumber(parseInt(row.share_komisi))}</TableCell>
          <TableCell align="left">{fNumber(parseInt(row.nAdminFee ?? 0))}</TableCell>
          <TableCell align="left">{row.payment_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 sx={{ marginLeft: 8 }}>
                <Typography variant="body1" fontWeight="bold">
                  Midtrans
                </Typography>
                <Grid container>
                  <Grid item xs={6}>
                    <Grid container>
                      <Grid item xs={3}>
                        Transaction ID
                      </Grid>
                      <Grid item xs={9}>
                        : {row.detail?.sPaymentDetails?.transaction_id}
                      </Grid>
                      <Grid item xs={3}>
                        Order ID
                      </Grid>
                      <Grid item xs={9}>
                        : {row.detail?.sPaymentDetails?.order_id}
                      </Grid>
                      <Grid item xs={3}>
                        Payment Type
                      </Grid>
                      <Grid item xs={9}>
                        : {row.detail?.sPaymentDetails?.payment_type}
                      </Grid>
                      <Grid item xs={3}>
                        Transaction Time
                      </Grid>
                      <Grid item xs={9}>
                        : {row.detail?.sPaymentDetails?.transaction_time}
                      </Grid>
                    </Grid>
                  </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('/linksehat/payments', {
      params: filter,
    });
    setDataTableLoading(false);
    setDataTableData(response.data.data);
  };

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

  const applyItems = async (
    searchFilter: string,
    searchFilterOrganization: string,
    searchFilterPaymentStatus: string,
    searchFilterAppointmentStart: string,
    searchFilterAppointmentEnd: string
  ) => {
    await loadDataTableData({
      search: searchFilter,
      organization_id: searchFilterOrganization,
      payment_status: searchFilterPaymentStatus,
      appointment_start: searchFilterAppointmentStart,
      appointment_end: searchFilterAppointmentEnd,
    });
    setSearchParamsFilter({
      search: searchFilter,
      organization_id: searchFilterOrganization,
      payment_status: searchFilterPaymentStatus,
      appointment_start: searchFilterAppointmentStart,
      appointment_end: searchFilterAppointmentEnd,
    });
  };

  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">
                  Faskes
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Tanggal Bayar
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Tanggal Konsultasi
                </TableCell>
                <TableCell style={headStyle} align="left">
                  ID Pemesanan
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Kode Pemesanan
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Dokter
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Pasien
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Email
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Tipe
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Metode Pembayaran
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Jenis Benefit
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Total Transfer (Rp)
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Konsultasi (Rp)
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Komisi (Rp)
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Biaya Administrasi (Rp)
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Status
                </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.nID} row={row} />
                ))}
              </TableBody>
            )}
          </Table>
        </TableContainer>

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