// @mui
import { styled } from '@mui/material/styles';
import {
  Typography,
  LinearProgress,
  linearProgressClasses,
  Stack,
  FormControlLabel,
  TableRow,
  TableCell,
  Table,
  TableBody,
  TextField,
  Button,
} from '@mui/material';
import { LoadingButton } from '@mui/lab';
import Checkbox from '@mui/material/Checkbox';
// components
import { FormProvider, RHFTextField } from '../../components/hook-form';
// React
import React, { ReactElement, useEffect, useState } from 'react';
import { fCurrency } from '../../utils/formatNumber';
// yup
import * as Yup from 'yup';
// form
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import MuiDialog from '../MuiDialog';
import { Member } from '../../@types/member';
import { LaravelPaginatedDataDefault } from '../../@types/paginated-data';
import DataTable from '../LaravelTable';
import axios from '../../utils/axios';

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

type DataContent = {
  info: string;
  date: string;
  time: string;
};

type MuiDialogProps = {
  title?: {
    name?: string;
    icon?: string;
  };
  openDialog: boolean;
  setOpenDialog: Function;
  content?: ReactElement;
  onSelect?: Function;
};

type FormValuesProps = {
  topup: string;
};

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

const testData = {
  companyName: 'PT. Aman Mineral',
  policyNumber: 12345678,
  totalMembers: 50,
  totalCases: 100,
  totalPersen: 75,
  myLimit: '375.000.000',
  totalLimit: 500000000,
};

const BorderLinearProgress = styled(LinearProgress)(({ theme }) => ({
  height: 10,
  borderRadius: 6,
  [`&.${linearProgressClasses.colorPrimary}`]: {
    backgroundColor: theme.palette.grey[theme.palette.mode === 'light' ? 300 : 800],
  },
  [`& .${linearProgressClasses.bar}`]: {
    borderRadius: 6,
    background: 'linear-gradient(270deg, #19BBBB 38.42%, #FF9565 76.21%, #FE7253 104.02%)',
  },
}));

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

export default function MemberSelectDialog({
  openDialog,
  setOpenDialog,
  onSelect
}: MuiDialogProps) {
  const [dataTableLoading, setDataTableLoading] = useState(false)
  const [dataTableData, setDataTableData] = useState(LaravelPaginatedDataDefault)
  const [searchFilter, setSearchFilter] = useState({
    search: ''
  })

  const handleSearchChange = (event: any) => {
    setSearchFilter({...searchFilter, ...{search: event.target.value}})
  }
  
  const loadDataTableData = async (appliedFilter : any | null = null) => {
    setDataTableLoading(true);
    const filter = appliedFilter ? appliedFilter : {};
    const response = await axios.get('/members', { params: filter });
    // console.log(response.data);
    setDataTableLoading(false);

    setDataTableData(response.data);
  }

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

  const handleFilterSubmit = (event: any) => {
    event.preventDefault();
    applyFilter(searchFilter)
  }

  useEffect(() => {
    console.log('effect openDialog');
    if (openDialog === false) {
    }
  }, [openDialog]);

  const handlePageChange = () => {
    console.log('handle change')
  }

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

  const Row = (props: { row: ReturnType<typeof createData>, onSelect }) => (
    <React.Fragment>
      <TableRow sx={{ '& > *': { borderBottom: 'unset' } }}>
        {/* <TableCell>
            <IconButton
              aria-label="expand row"
              size="small"
              onClick={() => setOpen(!open)}
            >
              {open ? <KeyboardArrowDownIcon /> : <KeyboardArrowRightIcon />}
            </IconButton>
          </TableCell> */}
        {/* { columns.map((column, index) => 
            <TableCell key={ index } align={ column.align } minwidth={ column.minWidth }>{ row[column.id] ?? '-' }</TableCell>
          ) } */}
        {/* TODO FIX DISPLAY DATA FROM RELATION */}

        {/* { id: 'member_id', label: 'MemberID', minWidth: 100, align: "left" },
    { id: 'principal_id', label: 'Mapping ID', minWidth: 100, align: "left" },
    { id: 'nik', label: 'NIK', minWidth: 100, align: "left" },
    { id: 'current_policy.policy_number', label: 'Policy Number', minWidth: 100, align: "left" },
    { id: 'effective_date', label: 'Effective Date', minWidth: 100, align: "left" },
    { id: 'name', label: 'Name', minWidth: 100, align: "left" },
    { id: 'nric', label: 'NRIC', minWidth: 100, align: "left" },
    { id: 'email', label: 'E-mail', minWidth: 100, align: "left" },
    { id: 'plan_id', label: 'PlanID', minWidth: 100, align: "left" },
    { id: 'termination_date', label: 'Termination Date', minWidth: 100, align: 'right' },
    { id: 'activation_date', label: 'Activation Date', minWidth: 100, align: "right" },
     */}
        <TableCell align="left">{props.row.member_id}</TableCell>
        <TableCell align="left">{props.row.principal_id}</TableCell>
        <TableCell align="left">{props.row.employeds?.[0]?.nik}</TableCell>
        <TableCell align="left">{props.row.current_policy?.policy_id}</TableCell>
        <TableCell align="left">{props.row.current_policy?.start}</TableCell>
        <TableCell align="left">{props.row.name}</TableCell>
        <TableCell align="left">{props.row.nric}</TableCell>
        <TableCell align="left">{props.row.email}</TableCell>
        <TableCell align="left">{props.row.current_plan?.code}</TableCell>
        <TableCell align="left">{props.row.current_policy?.start}</TableCell>
        <TableCell align="left">{props.row.current_policy?.end}</TableCell>
        <TableCell align="right" style={{ position: 'sticky', right: 0}}><Button variant="outlined" color="success" style={{backgroundColor: "#ffffff"}} size="small" onClick={() => {onSelect(props.row); setOpenDialog(false); }}>Select</Button></TableCell>
      </TableRow>
      {/* COLLAPSIBLE ROW */}
      {/* <TableRow>
          <TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={10}>
            <Collapse in={open} timeout="auto" unmountOnExit>
              <Box sx={{ borderBottom: 1 }}>
                <Typography variant="body2" gutterBottom component="div">
                  No Extra Data
                </Typography>
              </Box>
            {false && <Box sx={{ margin: 1 }} />}
            </Collapse>
          </TableCell>
        </TableRow> */}
    </React.Fragment>
  );

  const headStyle = {
    fontWeight: 'bold',
  };
  const TableContent = () => (
    <Table aria-label="collapsible table">
      {/* ------------------ TABLE HEADER ------------------ */}
      <TableBody>
        <TableRow>
          <TableCell style={headStyle} align="left" />
          <TableCell style={headStyle} align="left">
            Type
          </TableCell>
          <TableCell style={headStyle} align="left">
            Code
          </TableCell>
          <TableCell style={headStyle} align="left">
            Name
          </TableCell>
          <TableCell style={headStyle} align="left">
            Version
          </TableCell>
          <TableCell style={headStyle} align="right">
            Status
          </TableCell>
          <TableCell style={headStyle} align="right">
            Action
          </TableCell>
        </TableRow>
      </TableBody>
      {/* ------------------ END TABLE HEADER ------------------ */}

      {/* ------------------ TABLE ROW ------------------ */}
      {dataTableLoading ? (
        <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} onSelect/>
          ))}
        </TableBody>
      )}
      {/* ------------------ END TABLE ROW ------------------ */}
    </Table>
  );

  const getContent = () => (
    <Stack spacing={1} marginTop={2}>
      <form onSubmit={handleFilterSubmit}>
      <TextField label="Search" variant="outlined" fullWidth onChange={handleSearchChange} value={searchFilter.search} autoFocus/>
      </form>
      <DataTable
        isLoading={dataTableLoading}
        lastRequest={0}
        data={dataTableData}
        handlePageChange={handlePageChange}
        TableContent={<TableContent />}
      />
    </Stack>
  );
  
  return (
    <MuiDialog
      title={{name: "Select Member"}}
      openDialog={openDialog}
      setOpenDialog={setOpenDialog}
      content={getContent()}
      maxWidth="xl"
    />
  );
}
