import React, { useEffect, useState, useCallback } from 'react';
import PropTypes from 'prop-types';
import { Grid, Typography, Card, Button, Box, TextField } from '@mui/material';
import { useDispatch, useSelector } from 'react-redux';
import PageContainer from '../../components/container/PageContainer';
import { fetchSystem, setSystem } from '../../redux/reducers/SystemReducer';
import APIs from '../../api/APIs';

const systemType = {
  COMMISSION: 'commission',
  GAS_DEPOSIT: 'gas_deposit',
  SPECIAL_COLLECTION: 'special_collection',
}

function validateNumber(value) {
  if (value === "") {
    alert("값을 입력해주세요.");
    return false;
  }
  const splitted = value.split('.');
  if (splitted.length === 2 && splitted[1].length > 2) {
    alert('최소값은 0.01입니다');
    return false;
  }
  const num = Number(value);
  if (Number.isNaN(num)) {
    alert("숫자를 입력해주세요.");
    return false;
  }
  if (Number(value) < 0) {
    alert("0보다 작은 값은 설정할 수 없습니다.")
    return false;
  }

  return true;
}

const System = () => {
  const dispatch = useDispatch();
  const { data } = useSelector(state => state.system);

  const [commission, setCommition] = useState("");
  const [gasDeposit, setGasDeposit] = useState("");
  const [specialCollection, setSpecialCollection] = useState('');

  useEffect(() => {
    if (!data) {
      dispatch(fetchSystem());
    }
  }, []);

  const changeSystem = useCallback(async (type, value) => {
    await APIs.changeSystem({
      type, value
    }).then(() => {
      alert('저장 성공');
      dispatch(setSystem({ type, value }))
    }).catch(() => {
      alert('저장 실패');
    })
  }, [APIs, dispatch, setSystem])

  const handleClickSubmit = async (type, value) => {
    let changeValue;
    switch(type) {
      case systemType.COMMISSION:
      case systemType.GAS_DEPOSIT:
        if(validateNumber(value)) {
          changeValue = Number(value);
        } else {
          return;
        }
        break;
      default:
        changeValue = value;
    }
    
    changeSystem(type, changeValue); 
  }

  return (
    <PageContainer title="시스템 설정">
      <Grid container spacing={0}>
        <Grid item lg={3} md={3} xs={12}>
          <Card>
            <Typography
              sx={{
                textAlign: 'center',
                fontWeight: 'bold',
                marginBottom: 0
              }}
              variant="h4"
              gutterBottom
            >
              커미션 설정
            </Typography>
            <Typography
              color="textSecondary"
              variant="h5"
              fontWeight="400"
              sx={{
                mt: 1,
              }}
            >
              <Box>현재: {data?.commission}%</Box>
              <Box display="flex" sx={{ mt: '10px' }}>
                <Box sx={{ whiteSpace: 'nowrap', margin: '8px 10px 0 0' }}>신규 값:</Box>
                <TextField size="small" fullWidth sx={{ padding: 0 }} onChange={e => setCommition(e.target.value)} />
                <Box sx={{ width: '20px', margin: '7px 0 0 10px' }}>%</Box>
              </Box>
            </Typography>
            <Box sx={{ textAlign: 'center', mt: '20px' }} >
              <Button variant="contained" size="small" onClick={() => handleClickSubmit(systemType.COMMISSION, commission)}>
                수정완료
              </Button>
            </Box>
          </Card>
        </Grid>
        <Grid item lg={3} md={3} xs={12}>
          <Card>
            <Typography
              sx={{
                textAlign: 'center',
                fontWeight: 'bold',
                marginBottom: 0
              }}
              variant="h4"
              gutterBottom
            >
              네트워크 수수료 설정
            </Typography>
            <Typography
              color="textSecondary"
              variant="h5"
              fontWeight="400"
              sx={{
                mt: 1,
              }}
            >
              <Box>현재: {data?.gas_deposit}ETH</Box>
              <Box display="flex" sx={{ mt: '10px' }}>
                <Box sx={{ whiteSpace: 'nowrap', margin: '8px 10px 0 0' }}>신규값 설정:</Box>
                <TextField size="small" fullWidth sx={{ padding: 0 }} onChange={e => setGasDeposit(e.target.value)} />
                <Box sx={{ width: '20px', margin: '7px 0 0 10px' }}>ETH</Box>
              </Box>
            </Typography>
            <Box sx={{ textAlign: 'center', mt: '20px' }} >
              <Button variant="contained" size="small" onClick={() => handleClickSubmit(systemType.GAS_DEPOSIT, gasDeposit)}>
                수정완료
              </Button>
            </Box>
          </Card>
        </Grid>
        <Grid item lg={3} md={3} xs={12}>
          <Card>
            <Typography
              sx={{
                textAlign: 'center',
                fontWeight: 'bold',
                marginBottom: 0
              }}
              variant="h4"
              gutterBottom
            >
              스페셜 컬렉션 설정
            </Typography>
            <Typography
              color="textSecondary"
              variant="h5"
              fontWeight="400"
              sx={{
                mt: 1,
              }}
            >
              <Box>현재: {data?.special_collection}</Box>
              <Box display="flex" sx={{ mt: '10px' }}>
                <Box sx={{ whiteSpace: 'nowrap', margin: '8px 10px 0 0' }}>신규값 설정:</Box>
                <TextField size="small" fullWidth sx={{ padding: 0 }} onChange={e => setSpecialCollection(e.target.value)} />
                <Box sx={{ width: '20px', margin: '7px 0 0 10px' }} />
              </Box>
            </Typography>
            <Box sx={{ textAlign: 'center', mt: '20px' }} >
              <Button variant="contained" size="small" onClick={() => handleClickSubmit(systemType.SPECIAL_COLLECTION, specialCollection)}>
                수정완료
              </Button>
            </Box>
          </Card>
        </Grid>
        <Grid item lg={3} md={3} xs={12}>
          <Card sx={{ height: '190px' }} />
        </Grid>
        <Grid item lg={3} md={3} xs={12}>
          <Card sx={{ height: '190px' }} />
        </Grid>
        <Grid item lg={3} md={3} xs={12}>
          <Card sx={{ height: '190px' }} />
        </Grid>
      </Grid>
    </PageContainer>
  );
};

export default System;
