import React, { useEffect, useState } from 'react';
import {
  Card,
  CardContent,
  Typography,
  TableHead,
  Table,
  TableBody,
  TableCell,
  TableRow,
  Grid,
  MenuItem,
  TextField,
  FormControl,
  InputLabel,
  Select,
  Button,
  Paper,
  TableContainer,
  Box,
} 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/CollectionRow';
import CustomTextField from '../../components/forms/custom-elements/CustomTextField';
import { fetchCollection } from '../../redux/reducers/CollectionReducer';
import DateUtil from '../../utils/DateUtil';
import NumberUtil from '../../utils/NumberUtil';
import Pagination from '../../components/metarare/Pagination';
import store from '../../redux/Store';

const SearchFilterType = {
  NAME: 'name',
  ADDRESS: 'address'
}

const KrSearchFilter = {
  [SearchFilterType.NAME]: '컬렉션이름',
  [SearchFilterType.ADDRESS]: '지갑주소',
}

const Collection = () => {
  const dispatch = useDispatch();
  const { list } = useSelector(state => state.collection);
  const [selectedDate, setSelectedDate] = useState([null, null]);
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(25);
  const [status, setStatus] = useState('none');
  const [minPrice, setMinPrice] = useState(0);
  const [maxPrice, setMaxPrice] = useState(0);
  const [searchFilter, setSearchFilter] = useState(SearchFilterType.NAME);
  const [searchText, setSearchText] = useState('');
  const [data, setData] = useState([]);

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

  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 handleChangeMinPrice = (event) => {
    event.target.value = NumberUtil.replaceOnlyNumber(event.target.value);

    setMinPrice(Number(event.target.value));
  }

  const handleChangeMaxPrice = (event) => {
    event.target.value = NumberUtil.replaceOnlyNumber(event.target.value);

    setMaxPrice(Number(event.target.value));
  }

  const handleClickFilter = () => {
    const { list } = store.getState().collection;
    const data = list
      // 날짜
      .filter(item => {
        const startDate = DateUtil.getStartTime(selectedDate[0]).getTime();
        const endDate = DateUtil.getEndTime(selectedDate[1]).getTime();
        const date = DateUtil.getDateFormat(item.recent_trading_day).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 (!minPrice && !maxPrice) return true;

        if (minPrice && !maxPrice) {
          return item.total_volume >= minPrice;
        }
        if (!minPrice && maxPrice) {
          return item.total_volume <= maxPrice;
        }

        return item.total_volume >= minPrice && item.total_volume <= maxPrice;
      })
      // 상태
      .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);
  }

  const buttonSx = {
    ml: '20px',
    color: '#fff',
    whiteSpace: 'nowrap',
  }

  return (
    <PageContainer title="컬렉션 관리">
      <Box sx={{ ml: '15px', mr: '15px' }}>
        <Grid 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>
          <Box sx={{ display: 'inline-flex', width: '100%' }}>
            <CustomTextField
              id=""
              sx={{ ml: '20px' }}
              placeholder="컬렉션가치 최소금액"
              variant="outlined"
              size="small"
              label="최소금액"
              fullWidth
              onChange={handleChangeMinPrice}
            />
            <Box sx={{ margin: '9px 16px 0' }}> ~ </Box>
            <CustomTextField
              id=""
              placeholder="컬렉션가치 최대금액"
              variant="outlined"
              size="small"
              label="최대금액"
              fullWidth
              onChange={handleChangeMaxPrice}
            />
          </Box>
        </Grid>
        <Grid display="flex" sx={{ mt: '20px' }}>
          <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={status}
              label="상태"
              onChange={handleChangeStatus}
              sx={{ width: '150px' }}
              size="small"
            >
              <MenuItem value='none'>선택안함</MenuItem>
              <MenuItem value='visible'>보이기</MenuItem>
              <MenuItem value='invisible'>감추기</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.NAME}>컬렉션이름</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"
            sx={{
              ...buttonSx,
            }}
            onClick={handleClickFilter}
          >
            조회
          </Button>
        </Grid>
      </Box>
      <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>
                  <TableCell>
                    <Typography variant="h5">공용여부</Typography>
                  </TableCell>
                  <TableCell>
                    <Typography variant="h5">큐레이션 순서</Typography>
                  </TableCell>
                  <TableCell>
                    <Typography variant="h5">상태</Typography>
                  </TableCell>
                  <TableCell>
                    <Typography variant="h5">URL</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 Collection;
