// @mui
import {
  Autocomplete,
  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,
  TablePagination,
  Grid,
} 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, useRef, useState } from 'react';
import useSettings from '@/hooks/useSettings';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
// components
import axios from '@/utils/axios';
import { LaravelPaginatedData } from '@/@types/paginated-data';
import { Member } from '@/@types/member';
import Iconify from '@/components/Iconify';

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

  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={{ flex: '1' }}>
        <TextField
          id="search-input"
          ref={searchInput}
          label="Search"
          variant="outlined"
          fullWidth
          onChange={handleSearchChange}
          value={searchText}
        />
      </form>
    );
  }

  function ImportForm(props: any) {
    // IMPORT
    // Create Button Menu
    const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
    const createMenu = Boolean(anchorEl);
    const importForm = useRef<HTMLInputElement>(null);
    const [currentImportFileName, setCurrentImportFileName] = useState(null);

    const handleImportChange = (event: any) => {
      if (event.target.files[0]) {
        setCurrentImportFileName(event.target.files[0].name);
      } else {
        setCurrentImportFileName(null);
      }
    };

    const options = ['All', 'Option 2'];
    const [value, setValue] = React.useState<string | null>(options[0]);
    const [inputValue, setInputValue] = React.useState('');

    return (
      <div>
        <Stack direction={'row'} justifyContent="space-between" spacing={2} sx={{ p: 2 }}>
          {/* Filter Division */}
          {/* <Autocomplete
            value={value}
            onChange={(event: any, newValue: string | null) => {
              setValue(newValue);
            }}
            inputValue={inputValue}
            onInputChange={(event, newInputValue) => {
              setInputValue(newInputValue);
            }}
            id="controllable-states-demo"
            options={options}
            sx={{ minWidth: 240 }}
            renderInput={(params) => <TextField {...params} label="Division" />}
          /> */}
          {/* Search */}
          <SearchInput onSearch={applyFilter} />

          {/* Button Import */}
          <Button
            id="import-button"
            variant="outlined"
            startIcon={<Iconify icon="eva:download-fill" />}
            sx={{ p: 1.8, minWidth: '104px' }}
            // onClick={() => {}}
          >
            Import
          </Button>
          {/* <input
            type="file"
            id="file"
            ref={importForm}
            style={{ display: 'none' }}
            onChange={handleImportChange}
            accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, text/plain"
          /> */}
          {/* Button Add Task */}
          <Button variant="contained" startIcon={<AddIcon />} sx={{ p: 1.8, minWidth: '142px' }}>
            Add Data
          </Button>
        </Stack>
      </div>
    );
  }

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

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

  //   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.member_id}</TableCell>
  //         <TableCell align="left">{row.payor_id}</TableCell>
  //         <TableCell align="left">{row.name}</TableCell>
  //         <TableCell align="left">{row.nik}</TableCell>
  //         <TableCell align="left">{row.nric}</TableCell>

  //         <TableCell align="right">
  //           <Button variant="outlined" color="success" size="small">
  //             Active
  //           </Button>
  //         </TableCell>
  //         {/* <TableCell align="right"><Button variant="outlined" color="error" size="small">Disable</Button></TableCell> */}
  //       </TableRow>
  //       {/* COLLAPSIBLE ROW */}
  //       <TableRow>
  //         <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={99}>
  //           <Collapse in={open} timeout="auto" unmountOnExit>
  //             <Box sx={{ borderBottom: 1 }}>
  //               <Typography variant="body2" gutterBottom component="div">
  //                 <Grid></Grid>
  //               </Typography>
  //             </Box>
  //           </Collapse>
  //         </TableCell>
  //       </TableRow>
  //     </React.Fragment>
  //   );
  // }

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

    setDataTableData(response.data.members);
    setDataTableLoading(false);
  };

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

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

  useEffect(() => {
    loadDataTableData();
  }, []);

  return (
    <Card>
      <ImportForm />
      <Stack>
        {/* The Main Table */}
        <TableContainer component={Paper}>
          <Table aria-label="collapsible table">
            <TableBody>
              <TableRow>
                <TableCell style={headStyle} align="left">
                  MemberID
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Name
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Divisi
                </TableCell>
                <TableCell style={headStyle} align="left">
                  Limit
                </TableCell>
                <TableCell style={headStyle} align="right" width={100}>
                  Status
                </TableCell>
                <TableCell style={headStyle} align="right" width={100}>
                  Action
                </TableCell>
              </TableRow>
            </TableBody>
            {dataTableIsLoading ? (
              <TableBody>
                <TableRow>
                  <TableCell colSpan={8} align="center">
                    No Data Found
                  </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} />
                ))} */}
                Testing
              </TableBody>
            )}
          </Table>
        </TableContainer>

        {/* <TablePagination
          rowsPerPageOptions={[5, 10, 25]}
          component="div"
          count={rows.length}
          rowsPerPage={rowsPerPage}
          page={page}
          onPageChange={handleChangePage}
          onRowsPerPageChange={handleChangeRowsPerPage}
        /> */}
      </Stack>
    </Card>
  );
}
