import React, { useState, useEffect, useRef } from 'react';
import { Theme, FormControl } from '@material-ui/core';
import {makeStyles} from '@material-ui/core/styles';
import Button from '../components/custom-button';
// import RoleRadio from '../components/role-radio';
import Icon from '../components/icon';
import FormInput from '../components/form-input';
// import FormSelect, {FormSelectItems} from '../components/form-select';
import { isElectron } from '../utils/platform';
import { usePlatform } from '../containers/platform-container';
import {useHistory} from 'react-router-dom';
import { roomStore } from '../stores/room';
// import { genUid } from '../utils/helper';
// import MD5 from 'js-md5';
import { globalStore } from '../stores/global';
import {endPoint, goLogin} from '../services/agora-end-points';
import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";
import InputLabel from "@material-ui/core/InputLabel";
import {useLocation} from "react-router-dom";

import { Base64 } from 'js-base64';

export const roomTypes = [
  {value: 0, text: 'One-to-One', path: 'one-to-one'},
  {value: 1, text: 'Small Class', path: 'small-class'},
  {value: 2, text: 'Large Class', path: 'big-class'},
];

const useStyles = makeStyles ((theme: Theme) => ({
  formControl: {
    minWidth: '240px',
    maxWidth: '240px',
  },
  hide:{
    display: 'none'
  }
}));

type SessionInfo = {
  roomName: string
  roomType: number
  yourName: string
  yourPass: string
  role: string
  classId: string
}

const defaultState: SessionInfo = {
  roomName: '',
  roomType: 1,
  role: '',
  yourName: '',
  yourPass: '',
  classId: ''
}

function HomePage() {
  const style = useStyles();

  const history = useHistory();

  const handleSetting = (evt: any) => {
    history.push({pathname: `/device_test`});
  }

  const {
    HomeBtn
  } = usePlatform();

  const ref = useRef<boolean>(false);

  useEffect(() => {
    return () => {
      ref.current = true;
    }
  }, []);

  const [session, setSessionInfo] = useState<SessionInfo>(defaultState);

  const [required, setRequired] = useState<any>({} as any);
  const [classes, setClasses] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const handleClassChange = (event: any) => {
    setSessionInfo({
      ...session,
      classId: event.target.value
    });
    // console.log('handleClassChange', event.target.value);
  };
  const fetchClasses = async (val: any) => {
    console.log('fetchClasses', val, session.yourName);
    if (!session.yourName) {
      setSessionInfo({
        ...session,
        classId: ''
      });
      setClasses([])
      return
    }
    setLoading(true);
    globalStore.showLoading();
    const data = await endPoint.fetchClasses(session.yourName);
    console.log(data);
    setLoading(false);
    globalStore.stopLoading();
    setSessionInfo({
      ...session,
      classId: ''
    });
    setClasses(data)
  }


  const doCheckWithToken = (userInfo: any) => {
    loginLive(userInfo);
  }

  const doCheckWithUser = () => {
    endPoint.login({username: session.yourName, password: session.yourPass, classid: session.classId}, isDebug).then((userInfo: any) => {
      loginLive(userInfo);
    }).catch((err: any) => {
      globalStore.showToast({
        type: 'rtmClient',
        message: err
      })
    });
  }
  const loginLive = (userInfo: any) => {
    console.log(userInfo);
    session.roomName = userInfo["class_id"];// userInfo["class_id"];
    // session.yourName = userInfo["nick_name"];
    if (userInfo["classRole"]==="tea") {
      session.role = "teacher"
    } else if (userInfo["classRole"]==="developer"){
      session.role = "developer"
    } else {
      session.role = "student"
    }
    // session.role = userInfo["classRole"]==="tea"?"teacher":"student"
    session.roomType = 1;

    if (!roomTypes[session.roomType]) return;
    const path = roomTypes[session.roomType].path
    const payload = {
      uid: `${userInfo["id"]}`, // userInfo["classRole"]==="tea"?"100":`${session.yourName.substr(-2)}`, // `${userInfo["id"]}`, // genUid(),
      rid: `${session.roomName}`, // `${session.roomType}${MD5(session.roomName)}`,
      role: session.role,
      roomName: session.roomName,
      roomType: session.roomType,
      video: 0,
      audio: 0,
      chat: 1,
      account: `${userInfo["nick_name"]}`,
      token: '',
      boardId: '',
      linkId: 0,
      sharedId: 0,
      lockBoard: 0,
    }
    ref.current = true;
    globalStore.showLoading();
    roomStore.loginAndJoin(payload).then(() => {
      roomStore.updateSessionInfo(payload);
      history.push(`/classroom/${path}`);
    }).catch((err: any) => {
      if (err.reason) {
        globalStore.showToast({
          type: 'rtmClient',
          message: err.reason
        })
      } else {
        globalStore.showToast({
          type: 'rtmClient',
          message: 'login failure, please checkout ur network'
        })
      }
      console.warn(err);
    }).finally(() => {
      ref.current = false;
      globalStore.stopLoading();
    })
  }
  const location = useLocation();
  // console.log(1111111111111, location );
  const params = new URLSearchParams(location.search);
  let token:any = params.get('token');
  let isDebug = params.get('debug') && params.get('debug') === '1' ? true : false;
  let hasLogin = params.get('login') && params.get('login') === '1' ? true : false;
  let isLocal = params.get('isLocal') && params.get('isLocal') === '1' ? true : false;
  console.log('token', token)
  console.log('isDebug', isDebug)
  console.log('hasLogin', hasLogin)
  console.log('isLocal', isLocal)
  if (token) {
    endPoint.setUserToken(token);
    const tokenParts = token.split('.')
    token = tokenParts[1];
    token = token.replace(/[+]/g, '-');
    token = token.replace(/[/]/g, '_');
    const eqc = token.length % 4;
    const ea: any = [];
    if ( eqc !== 0 ) {
      ea.length = 4 - eqc;
      token = `${token}${Array.from(ea).fill('=').join('')}`
    }


    let userInfo = Base64.decode(token);
    userInfo = JSON.parse(userInfo)
    console.log(userInfo)
    // const userInfo = {
    //   id: `${data.username}`,
    //     class_id: "test_03__123",
    //   classRole: `${data.username}`==="1"?"tea":"",
    //   roomType: 1,
    //   nick_name: `${data.username}`,
    //   // data.username: session.yourName,
    //   // data.password: session.yourPass
    // };
    doCheckWithToken(userInfo);
  } else {
    if (!hasLogin &&  !isDebug) {
      goLogin()
    }
  }
  const handleSubmit = () => {
    if (!session.yourName) {
      setRequired({...required, yourName: 'missing your name'});
      return;
    }

    if (!session.yourPass) {
      setRequired({...required, yourPass: 'missing your password'});
      return;
    }


    ///////////////////////////////
    /*
    if (window.location.origin.includes('://127.0.0.1') || window.location.origin.includes('://localhost')) {
    session.roomName = "test_03__123";// userInfo["class_id"];
    // session.yourName = userInfo["nick_name"];
    session.role = `${session.yourName}`==="1"?"teacher":"student";
    session.roomType = 1;

    const path = roomTypes[session.roomType].path
    const payload = {
      uid: `${session.yourName}`, // genUid(),
      rid: `${session.roomName}`, // `${session.roomType}${MD5(session.roomName)}`,
      role: session.role,
      roomName: session.roomName,
      roomType: session.roomType,
      video: 0,
      audio: 0,
      chat: 1,
      account: session.yourName,
      token: '',
      boardId: '',
      linkId: 0,
      sharedId: 0,
      lockBoard: 0,
    }
    ref.current = true;
    globalStore.showLoading();
    roomStore.loginAndJoin(payload).then(() => {
      roomStore.updateSessionInfo(payload);
      history.push(`/classroom/${path}`);
    }).catch((err: any) => {
      if (err.reason) {
        globalStore.showToast({
          type: 'rtmClient',
          message: err.reason
        })
      } else {
        globalStore.showToast({
          type: 'rtmClient',
          message: 'login failure, please checkout ur network'
        })
      }
      console.warn(err);
    }).finally(() => {
        ref.current = false;
        globalStore.stopLoading();
      })
    } else {

    endPoint.login({username: session.yourName, password: session.yourPass, classid: session.classId}).then((userInfo: any) => {
      console.log(userInfo);
      session.roomName = userInfo["class_id"];// userInfo["class_id"];
      // session.yourName = userInfo["nick_name"];
      session.role = userInfo["classRole"]==="tea"?"teacher":"student";
      session.roomType = 1;

      if (!roomTypes[session.roomType]) return;
      const path = roomTypes[session.roomType].path
      const payload = {
        uid: `${userInfo["id"]}`, // userInfo["classRole"]==="tea"?"100":`${session.yourName.substr(-2)}`, // `${userInfo["id"]}`, // genUid(),
        rid: `${session.roomName}`, // `${session.roomType}${MD5(session.roomName)}`,
        role: session.role,
        roomName: session.roomName,
        roomType: session.roomType,
        video: 0,
        audio: 0,
        chat: 1,
        account: session.yourName,
        token: '',
        boardId: '',
        linkId: 0,
        sharedId: 0,
        lockBoard: 0,
      }
      ref.current = true;
      globalStore.showLoading();
      roomStore.loginAndJoin(payload).then(() => {
        roomStore.updateSessionInfo(payload);
        history.push(`/classroom/${path}`);
      }).catch((err: any) => {
        if (err.reason) {
          globalStore.showToast({
            type: 'rtmClient',
            message: err.reason
          })
        } else {
          globalStore.showToast({
            type: 'rtmClient',
            message: 'login failure, please checkout ur network'
          })
        }
        console.warn(err);
      })
      .finally(() => {
          ref.current = false;
          globalStore.stopLoading();
      })
    }).catch((err: any) => {
      globalStore.showToast({
        type: 'rtmClient',
        message: err
      })
    });

    }

    */
    doCheckWithUser();

  }

  return (
    <div className={`flex-container ${isElectron ? 'draggable' : 'home-cover-web' }`}>
      {isElectron ? null :
      <div className="web-menu">
        <div className="web-menu-container">
          <div className="short-title">
            <span className="title">iTeachABC 直播教室</span>
            <span className="subtitle">Powered by iplayabc.com</span>
          </div>
          <Icon className="icon-setting" onClick={handleSetting}/>
        </div>
      </div>
      }
      <div className={`custom-card`}>
        <div className="flex-item cover">
          {isElectron ?
          <>
          <div className="short-title">
            <span className="title">Agora Education</span>
            <span className="subtitle">Powered by agora.io</span>
          </div>
          <div className="cover-placeholder"></div>
          </>
          : <div className="cover-placeholder-web"></div>
          }
        </div>
        <div className="flex-item card">
          <div className="position-top card-menu">
            <HomeBtn handleSetting={handleSetting}/>
          </div>
          <div className={`position-content flex-direction-column  ${hasLogin ? '' : style.hide}`}>
            <FormControl className={style.formControl}>
              <FormInput Label={"账号"} value={session.yourName} onChange={
                (val: string) => {
                  setSessionInfo({
                    ...session,
                    yourName: val
                  });
                }}
                onBlur={fetchClasses}
                requiredText={required.yourName}
              />
            </FormControl>

            {isDebug
              ?<FormControl className={style.formControl}>
                <FormInput Label={"频道"} value={session.classId} onChange={
                  (val: string) => {
                    setSessionInfo({
                      ...session,
                      classId: val
                    });
                  }}
                           requiredText="请输入频道"
                />
              </FormControl>
              :<FormControl className={style.formControl}>

              <InputLabel>请选择班级</InputLabel>
              <Select
                value={session.classId}
                onChange={handleClassChange}
              >
                {!classes.length ?
                  <MenuItem value="0">
                    <em>请正确输入账号</em>
                  </MenuItem>
                  :
                  classes.map((item: any, key: number) =>
                    <MenuItem key={key} value={item.id}>{item.name}</MenuItem>)

                }
                {/*<MenuItem value={10}>Ten</MenuItem>
                <MenuItem value={20}>Twenty</MenuItem>
                <MenuItem value={30}>Thirty</MenuItem>*/}
              </Select>

            </FormControl>}


            <FormControl className={style.formControl}>
              <FormInput Label={"密码"} type="password" value={session.yourPass} onChange={
                (val: string) => {
                  setSessionInfo({
                    ...session,
                    yourPass: val
                  });
                }}
                requiredText={required.yourPass}
              />
            </FormControl>
            <Button disables={loading} name={"Join"} onClick={handleSubmit}/>
          </div>
        </div>
      </div>
    </div>
  )
}
export default React.memo(HomePage);
