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/LogRow';
import CustomTextField from '../../components/forms/custom-elements/CustomTextField';
import { fetchLog } from '../../redux/reducers/LogReducer';
import DateUtil from '../../utils/DateUtil';
import Pagination from '../../components/metarare/Pagination';

const SearchFilterType = {
  ADMIN_ID: 'admin_id'
}

const KrSearchFilter = {
  [SearchFilterType.ADMIN_ID]: '수행자',
}

const Log = () => {
  const dispatch = useDispatch();
  const { list } = useSelector(state => state.log);
  const [selectedDate, setSelectedDate] = useState([null, null]);
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(25);
  const [actionType, setActionType] = useState('none');
  const [searchFilter, setSearchFilter] = useState(SearchFilterType.ADMIN_ID);
  const [searchText, setSearchText] = useState('');
  const [data, setData] = useState([]);

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

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

  console.log(list)

  const handleChangeActionType = (event) => {
    setActionType(event.target.value);
  };

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

  const handleClickFilter = () => {
    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 (actionType === 'none') return true;
        return item.action_type === actionType;
      })
      // search
      .filter(item => {
        if (!searchText) return true;

        if (searchFilter === SearchFilterType.ADMIN_ID) {
          return item[searchFilter] === Number(searchText);
        }
        return !!item[searchFilter].includes(searchText);
      })

    setPage(0);
    setData(data);
  }

  return (
    <PageContainer title="유저 관리">
      <Grid sx={{ ml: '15px', mr: '15px' }} display="flex">
        <FormControl sx={{ minWidth: 'auto' }}>
          <InputLabel id="demo-simple-select-helper-label">상태</InputLabel>
          <Select
            labelId="demo-simple-select-helper-label"
            id="demo-simple-select-helper"
            value={actionType}
            label="상태"
            onChange={handleChangeActionType}
            sx={{ width: '150px' }}
            size="small"
          >
            <MenuItem value='none'>선택안함</MenuItem>
            <MenuItem value='user'>유저</MenuItem>
            <MenuItem value='artist'>작가</MenuItem>
            <MenuItem value='collection'>컬렉션</MenuItem>
            <MenuItem value='system'>시스템</MenuItem>
            <MenuItem value='admin'>관리자</MenuItem>
          </Select>
        </FormControl>
        <LocalizationProvider dateAdapter={AdapterDateFns}>
          <DateRangePicker
            startText="Start Date"
            endText="End Date"
            value={selectedDate}
            onChange={(newValue) => {
              setSelectedDate(newValue);
            }}
            renderInput={(startProps, endProps) => (
              <>
                <TextField {...startProps} sx={{ width: '150px', ml: '20px' }} 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={searchFilter}
            label="검색필터"
            onChange={handleChangeSearchFilter}
            sx={{ width: '150px' }}
            size="small"
          >
            <MenuItem value={SearchFilterType.ADMIN_ID}>수행자</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>
                </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 Log;
