import React, { useEffect, useState } from 'react';
import {
  Card,
  CardContent,
  Typography,
  TableHead,
  Table,
  TableBody,
  TableCell,
  TableRow,
  Grid,
  MenuItem,
  TextField,
  FormControl,
  InputLabel,
  Select,
  Button,
  Paper,
  TableContainer,
} from '@mui/material';
import { DateRangePicker, LocalizationProvider } from '@mui/lab';
import AdapterDateFns from '@mui/lab/AdapterDateFns';
import { useDispatch, useSelector } from 'react-redux';
import PageContainer from '../../components/container/PageContainer';
import Row from '../../components/metarare/UserRow';
import CustomTextField from '../../components/forms/custom-elements/CustomTextField';
import Pagination from '../../components/metarare/Pagination';
import { fetchUser } from '../../redux/reducers/UserReducer';
import DateUtil from '../../utils/DateUtil';
import store from '../../redux/Store';

const SearchFilterType = {
  EMAIL: 'email',
  ADDRESS: 'address'
}

const KrSearchFilter = {
  [SearchFilterType.EMAIL]: '이메일',
  [SearchFilterType.ADDRESS]: '지갑주소',
}

const User = () => {
  const dispatch = useDispatch();
  const { list } = useSelector(state => state.user);
  const [selectedDate, setSelectedDate] = useState([null, null]);
  const [status, setStatus] = useState('none');
  const [searchFilter, setSearchFilter] = useState(SearchFilterType.EMAIL);
  const [searchText, setSearchText] = useState('');
  const [data, setData] = useState([]);
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(25);

  useEffect(() => {
    if (!list.length) {
      dispatch(fetchUser());
    }
  }, []);

  useEffect(() => {
    if (list.length) {
      setData(list);
    }
  }, [list]);

  console.log(list)


  const handleChangeStatus = (event) => {
    setStatus(event.target.value);
  };

  const handleChangeSearchFilter = (event) => {
    setSearchFilter(event.target.value);
  };

  const handleClickFilter = () => {
    const { list } = store.getState().user;
    const data = list
      // 날짜
      .filter(item => {
        const startDate = DateUtil.getStartTime(selectedDate[0]).getTime();
        const endDate = DateUtil.getEndTime(selectedDate[1]).getTime();
        const date = DateUtil.getDateFormat(item.created_at).getTime();

        if (!selectedDate[0] && !selectedDate[1]) {
          return true;
        }
        if (selectedDate[0] && !selectedDate[1]) {
          return date >= startDate;
        }
        if (!selectedDate[0] && selectedDate[1]) {
          return date <= endDate;
        }
        return date >= startDate && date <= endDate;
      })
      // 상태
      .filter(item => {
        if (status === 'none') return true;
        return item.status === status;
      })
      // search
      .filter(item => {
        if (!searchText) return true;
        return !!item[searchFilter].includes(searchText);
      })

    setPage(0);
    setData(data);
  }

  return (
    <PageContainer title="유저 관리">
      <Grid sx={{ ml: '15px', mr: '15px' }} display="flex">
        <LocalizationProvider dateAdapter={AdapterDateFns}>
          <DateRangePicker
            startText="Start Date"
            endText="End Date"
            value={selectedDate}
            onChange={(newValue) => {
              setSelectedDate(newValue);
            }}
            renderInput={(startProps, endProps) => (
              <>
                <TextField {...startProps} sx={{ width: '150px' }} size="small" />
                <TextField {...endProps} sx={{ width: '150px', ml: '20px' }} size="small" />
              </>
            )
            }
          />
        </LocalizationProvider>
        <FormControl sx={{ minWidth: 'auto', ml: '20px' }}>
          <InputLabel id="demo-simple-select-helper-label">상태</InputLabel>
          <Select
            labelId="demo-simple-select-helper-label"
            id="demo-simple-select-helper"
            value={status}
            label="상태"
            onChange={handleChangeStatus}
            sx={{ width: '150px' }}
            size="small"
          >
            <MenuItem value='none'>선택안함</MenuItem>
            <MenuItem value='stable'>정상</MenuItem>
            <MenuItem value='blocked'>정지</MenuItem>
            <MenuItem value='withdrawal'>탈퇴</MenuItem>
          </Select>
        </FormControl>
        <FormControl sx={{ minWidth: 'auto', ml: '20px' }}>
          <InputLabel id="demo-simple-select-helper-label">검색필터</InputLabel>
          <Select
            labelId="demo-simple-select-helper-label"
            id="demo-simple-select-helper"
            value={searchFilter}
            label="검색필터"
            onChange={handleChangeSearchFilter}
            sx={{ width: '150px' }}
            size="small"
          >
            <MenuItem value={SearchFilterType.EMAIL}>이메일</MenuItem>
            <MenuItem value={SearchFilterType.ADDRESS}>지갑주소</MenuItem>
          </Select>
        </FormControl>
        <CustomTextField
          id="outlined-search"
          placeholder={KrSearchFilter[searchFilter]}
          size="small"
          type="search"
          variant="outlined"
          inputProps={{ 'aria-label': 'Search Contacts' }}
          sx={{ ml: '20px' }}
          fullWidth
          onChange={e => setSearchText(e.target.value)}
        />
        <Button variant="contained" size="small" color="primary" sx={{ ml: '20px;' }} onClick={handleClickFilter}>
          조회
        </Button>
      </Grid>
      <Card>
        <CardContent>
          <TableContainer component={Paper}>
            <Table
              aria-label="collapsible table"
              sx={{
                whiteSpace: 'nowrap'
              }}
            >
              <TableHead>
                <TableRow>
                  <TableCell />
                  <TableCell>
                    <Typography variant="h5">번호</Typography>
                  </TableCell>
                  <TableCell>
                    <Typography variant="h5">이메일</Typography>
                  </TableCell>
                  <TableCell>
                    <Typography variant="h5">지갑주소</Typography>
                  </TableCell>
                  <TableCell>
                    <Typography variant="h5">가입일자</Typography>
                  </TableCell>
                  <TableCell>
                    <Typography variant="h5">상태</Typography>
                  </TableCell>
                  <TableCell>
                    <Typography variant="h5">유저 프로필</Typography>
                  </TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {(rowsPerPage > 0
                  ? data.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                  : data
                ).map((row, index) => (
                  <Row key={`${row.id}_${index}`} row={row} />
                ))}
              </TableBody>
              <Pagination dataLength={data.length} page={page} setPage={setPage} rowsPerPage={rowsPerPage} setRowsPerPage={setRowsPerPage} />
            </Table>
          </TableContainer>
        </CardContent>
      </Card>
    </PageContainer>
  );
};

export default User;
