import * as Yup from 'yup';
// @mui
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,
  Checkbox,
  FormControlLabel,
} 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';
// hooks
import React, { ChangeEvent, Component, useEffect, useMemo, useRef, useState } from 'react';
import useSettings from '../../../hooks/useSettings';
import { Link, useParams, useSearchParams } from 'react-router-dom';
// components
import axios from '../../../utils/axios';
import { LaravelPaginatedData } from '../../../@types/paginated-data';
import { Icd } from '../../../@types/diagnosis';
import BasePagination from '../../../components/BasePagination';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { RHFCheckbox } from '../../../components/hook-form';
import { CheckBox } from '@mui/icons-material';
import { CorporateService } from '../../../@types/corporates';

export default function List() {
  const { themeStretch } = useSettings();
  const { corporate_id } = useParams();
  const [searchParams, setSearchParams] = useSearchParams();
  const [importResult, setImportResult] = useState(null);

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

  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}
          label="Search"
          variant="outlined"
          fullWidth
          onChange={handleSearchChange}
          value={searchText}
        />
      </form>
    );
  }

  function SearchForm(props: any) {
    // Create Button Menu
    const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);

    const handleClose = () => {
      setAnchorEl(null);
    };

    return (
      <Stack direction={'row'} spacing={2} sx={{ p: 2 }}>
        <SearchInput onSearch={applyFilter} />
      </Stack>
    );
  }

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

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

    const handleConfigChange = (event: ChangeEvent<HTMLInputElement>, service: any) => {
      console.log(event.target.name, event.target.checked, service);

      axios.put(`/corporates/${corporate_id}/services`, {
        service_code: service.service_code,
        config_name: event.target.name,
        config_value: event.target.checked,
      });
    };

    const handleActivate = (service: any, status: string) => {
      axios
        .put(`/corporates/${corporate_id}/services/${service.service_code}`, {
          service_code: service.service_code,
          status,
        })
        .then((res) => {
          setDataTableData({
            ...dataTableData,
            data: dataTableData.data.map((service) => {
              let updatedService = service;
              if (row.id == service.id) {
                updatedService.status = res.data.status;
              }
              return updatedService;
            }),
          });
        });
    };

    return (
      <React.Fragment>
        <TableRow sx={{ '& > *': { borderBottom: 'unset' } }}>
          {/* <TableCell>
            <IconButton
              aria-label="expand row"
              size="small"
              onClick={() => setOpen(!open)}
            >
              {open ? <KeyboardArrowDownIcon /> : <KeyboardArrowRightIcon />}
            </IconButton>
          </TableCell> */}
          <TableCell align="left">{row.service_code}</TableCell>
          <TableCell align="left">{row.name}</TableCell>

          <TableCell align="right">
            {row.status == 'active' && (
              <Button
                variant="outlined"
                color="success"
                size="small"
                onClick={() => {
                  handleActivate(row, 'inactive');
                }}
              >
                Active
              </Button>
            )}
            {row.status == 'inactive' && (
              <Button
                variant="outlined"
                color="error"
                size="small"
                onClick={() => {
                  handleActivate(row, 'active');
                }}
              >
                Inactive
              </Button>
            )}
          </TableCell>
          <TableCell align="right">
            <Link to={`/corporate/${corporate_id}/services/${row.service_code}`}>
              <Button variant="outlined" color="primary" size="small">
                Config
              </Button>
            </Link>
          </TableCell>
        </TableRow>
        {/* COLLAPSIBLE ROW */}
        {false && (
          <TableRow>
            <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={99}>
              <Collapse in={open} timeout="auto" unmountOnExit>
                <Box sx={{ borderBottom: 1 }}>
                  <Stack>
                    <TableContainer>
                      <Table sx={{ minWidth: 650 }} size="small">
                        <TableHead>
                          <TableRow>
                            <TableCell colSpan={4} sx={{ py: 1 }}>
                              General Practitioner
                            </TableCell>
                          </TableRow>
                        </TableHead>
                        <TableBody>
                          <TableRow>
                            <TableCell colSpan={2}>External Doctor</TableCell>
                            <TableCell colSpan={2}>Internal Doctor</TableCell>
                          </TableRow>
                          <TableRow>
                            <TableCell>
                              <FormControlLabel
                                control={
                                  <Checkbox
                                    defaultChecked={
                                      row.configurations.gp_external_doctor_online == '1'
                                    }
                                    onChange={(event) => {
                                      handleConfigChange(event, row);
                                    }}
                                    name="gp_external_doctor_online"
                                  />
                                }
                                label="Online"
                              />
                            </TableCell>
                            <TableCell>
                              <FormControlLabel
                                control={
                                  <Checkbox
                                    defaultChecked={
                                      row.configurations.gp_external_doctor_offline == '1'
                                    }
                                    onChange={(event) => {
                                      handleConfigChange(event, row);
                                    }}
                                    name="gp_external_doctor_offline"
                                  />
                                }
                                label="Offline"
                              />
                            </TableCell>
                            <TableCell>
                              <FormControlLabel
                                control={
                                  <Checkbox
                                    defaultChecked={
                                      row.configurations.gp_internal_doctor_online == '1'
                                    }
                                    onChange={(event) => {
                                      handleConfigChange(event, row);
                                    }}
                                    name="gp_internal_doctor_online"
                                  />
                                }
                                label="Online"
                              />
                            </TableCell>
                            <TableCell>
                              <FormControlLabel
                                control={
                                  <Checkbox
                                    defaultChecked={
                                      row.configurations.gp_internal_doctor_offline == '1'
                                    }
                                    onChange={(event) => {
                                      handleConfigChange(event, row);
                                    }}
                                    name="gp_internal_doctor_offline"
                                  />
                                }
                                label="Offline"
                              />
                            </TableCell>
                          </TableRow>
                        </TableBody>
                      </Table>
                    </TableContainer>

                    <TableContainer>
                      <Table sx={{ minWidth: 650 }} size="small">
                        <TableHead>
                          <TableRow>
                            <TableCell colSpan={4} sx={{ py: 1 }}>
                              Specialist Practitioner
                            </TableCell>
                          </TableRow>
                        </TableHead>
                        <TableBody>
                          <TableRow>
                            <TableCell colSpan={2}>External Doctor</TableCell>
                            <TableCell colSpan={2}>Internal Doctor</TableCell>
                          </TableRow>
                          <TableRow>
                            <TableCell>
                              <FormControlLabel
                                control={
                                  <Checkbox
                                    defaultChecked={
                                      row.configurations.sp_external_doctor_online == '1'
                                    }
                                    onChange={(event) => {
                                      handleConfigChange(event, row);
                                    }}
                                    name="sp_external_doctor_online"
                                  />
                                }
                                label="Online"
                              />
                            </TableCell>
                            <TableCell>
                              <FormControlLabel
                                control={
                                  <Checkbox
                                    defaultChecked={
                                      row.configurations.sp_external_doctor_offline == '1'
                                    }
                                    onChange={(event) => {
                                      handleConfigChange(event, row);
                                    }}
                                    name="sp_external_doctor_offline"
                                  />
                                }
                                label="Offline"
                              />
                            </TableCell>
                            <TableCell>
                              <FormControlLabel
                                control={
                                  <Checkbox
                                    defaultChecked={
                                      row.configurations.sp_internal_doctor_online == '1'
                                    }
                                    onChange={(event) => {
                                      handleConfigChange(event, row);
                                    }}
                                    name="sp_internal_doctor_online"
                                  />
                                }
                                label="Online"
                              />
                            </TableCell>
                            <TableCell>
                              <FormControlLabel
                                control={
                                  <Checkbox
                                    defaultChecked={
                                      row.configurations.sp_internal_doctor_offline == '1'
                                    }
                                    onChange={(event) => {
                                      handleConfigChange(event, row);
                                    }}
                                    name="sp_internal_doctor_offline"
                                  />
                                }
                                label="Offline"
                              />
                            </TableCell>
                          </TableRow>
                        </TableBody>
                      </Table>
                    </TableContainer>

                    <TableContainer>
                      <Table sx={{ minWidth: 650 }} size="small">
                        <TableHead>
                          <TableRow>
                            <TableCell colSpan={4} sx={{ py: 1 }}>
                              Medicine
                            </TableCell>
                          </TableRow>
                        </TableHead>
                        <TableBody>
                          <TableRow>
                            <TableCell width={'25%'}>
                              <FormControlLabel
                                control={
                                  <Checkbox
                                    defaultChecked={row.configurations.vitamins == '1'}
                                    onChange={(event) => {
                                      handleConfigChange(event, row);
                                    }}
                                    name="vitamins"
                                  />
                                }
                                label="Vitamins"
                              />
                            </TableCell>
                            <TableCell width={'25%'}>
                              <FormControlLabel
                                control={
                                  <Checkbox
                                    defaultChecked={row.configurations.delivery_fee == '1'}
                                    onChange={(event) => {
                                      handleConfigChange(event, row);
                                    }}
                                    name="delivery_fee"
                                  />
                                }
                                label="Delivery Fee"
                              />
                            </TableCell>
                            <TableCell width={'25%'} />
                            <TableCell width={'25%'} />
                          </TableRow>
                        </TableBody>
                      </Table>
                    </TableContainer>

                    <TableContainer>
                      <Table sx={{ minWidth: 650 }} size="small">
                        <TableHead>
                          <TableRow>
                            <TableCell colSpan={4} sx={{ py: 1 }}>
                              Free Admin Fee
                            </TableCell>
                          </TableRow>
                        </TableHead>
                        <TableBody>
                          <TableRow>
                            <TableCell width={'25%'}>
                              <FormControlLabel
                                control={
                                  <Checkbox
                                    defaultChecked={
                                      row.configurations.general_practitioner_fee == '1'
                                    }
                                    onChange={(event) => {
                                      handleConfigChange(event, row);
                                    }}
                                    name="general_practitioner_fee"
                                  />
                                }
                                label="General Practitioner"
                              />
                            </TableCell>
                            <TableCell width={'25%'}>
                              <FormControlLabel
                                control={
                                  <Checkbox
                                    defaultChecked={
                                      row.configurations.specialist_practitioner_fee == '1'
                                    }
                                    onChange={(event) => {
                                      handleConfigChange(event, row);
                                    }}
                                    name="specialist_practitioner_fee"
                                  />
                                }
                                label="Specialist Practitioner"
                              />
                            </TableCell>
                            <TableCell width={'25%'} />
                            <TableCell width={'25%'} />
                          </TableRow>
                        </TableBody>
                      </Table>
                    </TableContainer>
                  </Stack>
                </Box>
              </Collapse>
            </TableCell>
          </TableRow>
        )}
      </React.Fragment>
    );
  }

  const loadDataTableData = async (appliedFilter: any | null = null) => {
    setDataTableLoading(true);
    const filter = appliedFilter ? appliedFilter : Object.fromEntries([...searchParams.entries()]);
    const response = await axios.get('/corporates/' + corporate_id + '/services', {
      params: filter,
    });
    setDataTableLoading(false);

    // const service = [
    //   {
    //     'id' : 1,
    //     'code' : 'OP',
    //     'name' : 'Out Patient',
    //     'description' : 'Out Patient',
    //     'configurations' : [
    //       {
    //         'gp_external_doctor_online' : false,
    //         'gp_external_doctor_offline' : false,
    //         'gp_internal_doctor_online' : false,
    //         'gp_internal_doctor_offline' : false,
    //         'sp_external_doctor_online' : false,
    //         'sp_external_doctor_offline' : false,
    //         'sp_internal_doctor_online' : false,
    //         'sp_internal_doctor_offline' : false,
    //         'vitamins': false,
    //         'delivery_fee': false,
    //         'general_practitioner_fee': false,
    //         'specialist_practitioner_fee': false,
    //       },
    //     ]
    //   },
    //   {
    //     'id' : 2,
    //     'code' : 'IP',
    //     'name' : 'In Patient',
    //     'description' : 'In Patient',
    //     'configurations' : [
    //       {
    //         'gp_external_doctor_online' : false,
    //         'gp_external_doctor_offline' : false,
    //         'gp_internal_doctor_online' : false,
    //         'gp_internal_doctor_offline' : false,
    //         'sp_external_doctor_online' : false,
    //         'sp_external_doctor_offline' : false,
    //         'sp_internal_doctor_online' : false,
    //         'sp_internal_doctor_offline' : false,
    //         'vitamins': false,
    //         'delivery_fee': false,
    //         'general_practitioner_fee': false,
    //         'specialist_practitioner_fee': false,
    //       },
    //     ]
    //   },
    //   {
    //     'id' : 3,
    //     'code' : 'DE',
    //     'name' : 'Dental',
    //     'description' : 'Dental',
    //     'configurations' : [
    //       {
    //         'gp_external_doctor_online' : false,
    //         'gp_external_doctor_offline' : false,
    //         'gp_internal_doctor_online' : false,
    //         'gp_internal_doctor_offline' : false,
    //         'sp_external_doctor_online' : false,
    //         'sp_external_doctor_offline' : false,
    //         'sp_internal_doctor_online' : false,
    //         'sp_internal_doctor_offline' : false,
    //         'vitamins': false,
    //         'delivery_fee': false,
    //         'general_practitioner_fee': false,
    //         'specialist_practitioner_fee': false,
    //       },
    //     ]
    //   },
    //   {
    //     'id' : 4,
    //     'code' : 'Optical',
    //     'name' : 'Optical',
    //     'description' : 'Optical',
    //     'configurations' : [
    //       {
    //         'gp_external_doctor_online' : false,
    //         'gp_external_doctor_offline' : false,
    //         'gp_internal_doctor_online' : false,
    //         'gp_internal_doctor_offline' : false,
    //         'sp_external_doctor_online' : false,
    //         'sp_external_doctor_offline' : false,
    //         'sp_internal_doctor_online' : false,
    //         'sp_internal_doctor_offline' : false,
    //         'vitamins': false,
    //         'delivery_fee': false,
    //         'general_practitioner_fee': false,
    //         'specialist_practitioner_fee': false,
    //       },
    //     ]
    //   },
    //   {
    //     'id' : 5,
    //     'code' : 'MA',
    //     'name' : 'Matternity',
    //     'description' : 'Matternity',
    //     'configurations' : [
    //       {
    //         'gp_external_doctor_online' : false,
    //         'gp_external_doctor_offline' : false,
    //         'gp_internal_doctor_online' : false,
    //         'gp_internal_doctor_offline' : false,
    //         'sp_external_doctor_online' : false,
    //         'sp_external_doctor_offline' : false,
    //         'sp_internal_doctor_online' : false,
    //         'sp_internal_doctor_offline' : false,
    //         'vitamins': false,
    //         'delivery_fee': false,
    //         'general_practitioner_fee': false,
    //         'specialist_practitioner_fee': false,
    //       },
    //     ]
    //   },
    //   {
    //     'id' : 6,
    //     'code' : 'SP',
    //     'name' : 'Special Benefit',
    //     'description' : 'Special Benefit',
    //     'configurations' : [
    //       {
    //         'gp_external_doctor_online' : false,
    //         'gp_external_doctor_offline' : false,
    //         'gp_internal_doctor_online' : false,
    //         'gp_internal_doctor_offline' : false,
    //         'sp_external_doctor_online' : false,
    //         'sp_external_doctor_offline' : false,
    //         'sp_internal_doctor_online' : false,
    //         'sp_internal_doctor_offline' : false,
    //         'vitamins': false,
    //         'delivery_fee': false,
    //         'general_practitioner_fee': false,
    //         'specialist_practitioner_fee': false,
    //       },
    //     ]
    //   }
    // ];

    // console.log('asdasd', service);
    // let x = response.data;
    // x.data = service;

    setDataTableData(response.data);
  };

  const headStyle = {
    fontWeight: 'bold',
  };

  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();
  }, []);

  return (
    <Stack>
      <SearchForm />

      <Card>
        {/* The Main Table */}
        <TableContainer component={Paper}>
          <Table aria-label="collapsible table">
            <TableBody>
              <TableRow>
                {/* <TableCell style={headStyle} align="left" width={10}/> */}
                <TableCell style={headStyle} align="left">
                  Code
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Service
                </TableCell>

                <TableCell style={headStyle} align="right" width={30}>
                  Status
                </TableCell>
                <TableCell style={headStyle} align="right" width={30}>
                  Action
                </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>
  );
}
