import React, { useEffect, useState } from 'react';
import {
  Card,
  CardContent,
  Typography,
  TableHead,
  Table,
  TableBody,
  TableCell,
  TableRow,
  Grid,
  MenuItem,
  FormControl,
  InputLabel,
  Select,
  Paper,
  TableContainer,
  Button,
  Box
} from '@mui/material';
import { useSelector, useDispatch } from 'react-redux';
import PageContainer from '../../components/container/PageContainer';
import Row from '../../components/metarare/AdminRow';
import CustomTextField from '../../components/forms/custom-elements/CustomTextField';
import AddAdmin from '../../components/metarare/AddAdmin';
import { fetchAdmin } from '../../redux/reducers/AdminReducer';
import Pagination from '../../components/metarare/Pagination';
import store from '../../redux/Store';

const AuthType = {
  USER: 'user',
  COLLECTION: 'collection',
  SYSTEM: 'system',
  ADMIN: 'admin',
  LOG: 'log'
}

const SearchFilterType = {
  EMAIL: 'email'
}

const KrSearchFilter = {
  [SearchFilterType.EMAIL]: '이메일',
}

const Admin = () => {
  const dispatch = useDispatch();
  const { list } = useSelector(state => state.admin);
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(25);
  const [status, setStatus] = useState('none');
  const [auth, setAuth] = useState('none');
  const [searchFilter, setSearchFilter] = useState(SearchFilterType.EMAIL);
  const [searchText, setSearchText] = useState('');
  const [data, setData] = useState([]);
  const [showAddAdmin, setShowAddAdmin] = useState(false);

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

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

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

  const handleChangeAuth = (event) => {
    setAuth(event.target.value);
  };

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

  const handleClickFilter = () => {
    const { list } = store.getState().admin;
    const data = list
      // 상태
      .filter(item => {
        if (status === 'none') return true;
        return item.status === status;
      })
      // 권한
      .filter(item => {
        if (auth === 'none') return true;
        return !!item[auth];
      })
      // search
      .filter(item => {
        if (!searchText) return true;
        return !!item[searchFilter].includes(searchText);
      })

    setPage(0);
    setData(data);
  }

  const buttonSx = {
    minWidth: 'auto',
    ml: '20px',
    whiteSpace: 'nowrap',
  }

  return (
    <PageContainer title="관리자 설정">
      <Grid sx={{ ml: '15px', mr: '15px' }} display="flex">
        <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>
          </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={auth}
            label="상태"
            onChange={handleChangeAuth}
            sx={{ width: '150px' }}
            size="small"
          >
            <MenuItem value='none'>선택안함</MenuItem>
            <MenuItem value={AuthType.USER}>유저관리</MenuItem>
            <MenuItem value={AuthType.COLLECTION}>컬렉션관리</MenuItem>
            <MenuItem value={AuthType.SYSTEM}>시스템설정</MenuItem>
            <MenuItem value={AuthType.ADMIN}>관리자설정</MenuItem>
            <MenuItem value={AuthType.LOG}>로그</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>
          </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>
        <Button
          variant="contained"
          size="small"
          sx={{
            ...buttonSx,
          }}
          onClick={() => setShowAddAdmin(true)}
        >
          관리자 추가
        </Button>
        {showAddAdmin && (
          <Box
            sx={{
              position: 'fixed',
              top: '0',
              right: '0',
              bottom: '0',
              left: '0',
              zIndex: 1,
            }}
          >
            <AddAdmin setShowAddAdmin={setShowAddAdmin} />
          </Box>
        )}
      </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>
                </TableRow>
              </TableHead>
              <TableBody>
                {(rowsPerPage > 0
                  ? data.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
                  : data
                ).map((row) => (
                  <Row key={row.id} row={row} />
                ))}
              </TableBody>
              <Pagination dataLength={data.length} page={page} setPage={setPage} rowsPerPage={rowsPerPage} setRowsPerPage={setRowsPerPage} />
            </Table>
          </TableContainer>
        </CardContent>
      </Card>
    </PageContainer>
  );
};

export default Admin;
