import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { Box, Button, Collapse, FormControl, IconButton, Link, MenuItem, Select, Table, TableBody, TableCell, TableHead, TableRow, Typography } from '@mui/material';

import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';
import { useDispatch } from 'react-redux';
import CustomTextField from '../forms/custom-elements/CustomTextField';
import useStatus from '../../hooks/useStatus';
import APIs from '../../api/APIs';
import NumberUtil from '../../utils/NumberUtil';
import { fetchCollection, changeCollectionData, updateCurationNumber } from '../../redux/reducers/CollectionReducer';
import URLInfo from '../../constants/URLInfo';

function CollectionRow(props) {
  const dispatch = useDispatch();
  const { row } = props;
  const [open, setOpen] = useState(false);
  const [curation, setCuration] = useState(0);
  const [disabledCuration, setDisabledCuration] = useState(true);
  const { status, handleChangeStatus, handleClickStatusApply } = useStatus(row.status, APIs.changeCollectionStatus, row.id, changeCollectionData)

  const curationBtnText = disabledCuration ? '수정' : '적용';
  useEffect(() => {
    setCuration(row.curating_number);
  }, [row.curating_number]);
  const handleClickCuration = async () => {
    if (!disabledCuration) {
      await APIs.changeCollectionCuration({ id: row.id, index: Number(curation) })
        .then(() => {
          alert('저장 성공');
          dispatch(updateCurationNumber(Number(curation)));
          dispatch(fetchCollection());
        })
        .catch(() => {
          alert('저장 실패')
        })
    }
    setDisabledCuration(!disabledCuration);
  }

  const handleChangeCuration = (event) => {
    if (Number(event.target.value) > 25) {
      alert('큐레이션은 25번 이상으로 넘어갈 수 없습니다.');
      return;
    }
    event.target.value = NumberUtil.replaceOnlyNumber(event.target.value);
    setCuration(event.target.value);
  }

  const tableCellStyle = {
    borderBottom: '0',
    padding: '10px'
  }

  return (
    <>
      <TableRow>
        <TableCell
          sx={{
            ...tableCellStyle
          }}
        >
          <IconButton aria-label="expand row" size="small" onClick={() => setOpen(!open)}>
            {open ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
          </IconButton>
        </TableCell>
        <TableCell
          sx={{
            ...tableCellStyle
          }}
        >
          <Box display="flex" alignItems="center">
            <Typography variant="h5" fontWeight="600">
              {row.id}
            </Typography>
          </Box>
        </TableCell>
        <TableCell
          sx={{
            ...tableCellStyle
          }}
        >
          <Typography variant="h5" fontWeight="400">
            {row.name}
          </Typography>
        </TableCell>
        <TableCell
          sx={{
            ...tableCellStyle
          }}
        >
          <Typography variant="h5" fontWeight="400">
            {row.symbol}
          </Typography>
        </TableCell>
        <TableCell
          sx={{
            ...tableCellStyle
          }}
        >
          <Typography variant="h5" fontWeight="400">
            {Number(row.total_volume.toFixed(5))}
          </Typography>
        </TableCell>
        <TableCell
          sx={{
            ...tableCellStyle
          }}
        >
          <Typography variant="h5" fontWeight="400">
            {row.total_like_count}
          </Typography>
        </TableCell>
        <TableCell
          sx={{
            ...tableCellStyle
          }}
        >
          <Typography variant="h5" fontWeight="400">
            {row.recent_trading_day}
          </Typography>
        </TableCell>
        <TableCell
          sx={{
            ...tableCellStyle
          }}
        >
          <Typography variant="h5" fontWeight="400" display="inline-flex">
            {row.is_official.toString()}
          </Typography>
        </TableCell>
        <TableCell
          sx={{
            overflow: 'hidden',
            ...tableCellStyle
          }}
        >
          <CustomTextField
            id="outlined-search"
            size="small"
            variant="outlined"
            value={curation}
            sx={{ width: '50px' }}
            disabled={disabledCuration}
            onChange={handleChangeCuration}
          />
          <Button variant="outlined" size="small" color="primary" sx={{ ml: '20px', height: '40px' }} onClick={handleClickCuration}>
            {curationBtnText}
          </Button>
        </TableCell>
        <TableCell
          sx={{
            ...tableCellStyle
          }}
        >

          <FormControl sx={{ minWidth: 'auto' }}>
            <Select
              labelId="demo-simple-select-helper-label"
              id="demo-simple-select-helper"
              value={status}
              onChange={(e) => handleChangeStatus(e, row.id)}
              sx={{ width: '120px' }}
              size="small"
            >
              <MenuItem value='none'>선택안함</MenuItem>
              <MenuItem value='visible'>보이기</MenuItem>
              <MenuItem value='invisible'>감추기</MenuItem>
            </Select>
          </FormControl>
          <Button variant="outlined" size="small" color="primary" sx={{ ml: '20px', height: '40px' }} onClick={handleClickStatusApply}>
            적용
          </Button>
        </TableCell>
        <TableCell
          sx={{
            borderBottom: '0',
          }}
        >
          <Typography fontWeight="400">
            <Link size="small" href={URLInfo.getCollectionProfile(row.name)} variant="body2">바로가기</Link>
          </Typography>
        </TableCell>
      </TableRow>
      <TableRow sx={{ borderBottom: '1px solid rgba(224, 224, 224, 1)' }}>
        <TableCell sx={{ paddingBottom: 0, paddingTop: 0, borderBottom: 0 }} colSpan={6}>
          <Collapse in={open} timeout="auto" unmountOnExit>
            <Box margin={1}>
              <Typography
                gutterBottom
                variant="h5"
                sx={{
                  mt: 2,
                  backgroundColor: (theme) => theme.palette.grey.A700,
                  p: '5px 15px',
                  color: (theme) =>
                    `${theme.palette.mode === 'dark'
                      ? theme.palette.grey.A200
                      : 'rgba(0, 0, 0, 0.87)'
                    }`,
                }}
              >
                History
              </Typography>
              <Table size="small" aria-label="purchases">
                <TableHead>
                  <TableRow>
                    <TableCell>
                      <Typography variant="h6">컬렉션 주소</Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="h6">최고 거래가</Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="h6">최저 거래가</Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="h6">세일중인 작품 총합</Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="h6">작품 수 </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="h6">컬렉션에 작품을 올린 유저의 수 </Typography>
                    </TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  <TableRow>
                    <TableCell component="th" scope="row">
                      <Typography color="textSecondary" fontWeight="400">
                        {row.contract_address}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography color="textSecondary" fontWeight="400">
                        {row.highest_sale_price}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography color="textSecondary" fontWeight="400">
                        0
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography fontWeight="400">
                        {row.market_cap}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography fontWeight="400">
                        {row.items}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography fontWeight="400">
                        0
                      </Typography>
                    </TableCell>
                  </TableRow>
                </TableBody>
              </Table>
            </Box>
          </Collapse>
        </TableCell>
      </TableRow>
    </>
  );
}

export default CollectionRow;

CollectionRow.propTypes = {
  row: PropTypes.shape({
    id: PropTypes.number.isRequired,
    name: PropTypes.string.isRequired,
    symbol: PropTypes.string.isRequired,
    total_volume: PropTypes.number.isRequired,
    total_like_count: PropTypes.number.isRequired,
    is_official: PropTypes.bool.isRequired,
    recent_trading_day: PropTypes.string.isRequired,
    curating_number: PropTypes.number.isRequired,
    status: PropTypes.string.isRequired,
    contract_address: PropTypes.string.isRequired,
    highest_sale_price: PropTypes.number.isRequired,
    market_cap: PropTypes.number.isRequired,
    items: PropTypes.number.isRequired,
  }),
};