import { FC, useContext, useEffect, useState } from 'react';
import dayjs from 'dayjs';
import classNames from 'classnames';
import useDarkMode from '../../hooks/useDarkMode';
import Button from '../bootstrap/Button';
import ThemeContext from '../../contexts/themeContext';
import Card, { CardBody} from '../bootstrap/Card';
import { useAuth } from '../../contexts/authContext';
import RowdayService from '../../services/RowdayService';
import { ChatListItem } from '../Chat';
import CommentAvatar from '../../assets/avatar/avatar1.jpg';

import Icon from '../icon/Icon';
import LivestreamService from '../../services/LivestreamService';


interface ICommentsViewersProps {
  vsUsername: string;
}

type TListTab = 'Comments' | 'Online';
const LIST_TAB: { [key: string]: TListTab } = {
  COMMENTS: 'Comments',
  ONLINE: 'Online',
};

const CommentsViewers: FC<ICommentsViewersProps> = ({ vsUsername }) => {

	const { mobileDesign } = useContext(ThemeContext);
  const { themeStatus } = useDarkMode();
  const {userData} = useAuth();

  const [activeListTab, setActiveListTab] = useState(LIST_TAB.COMMENTS);
  const [commentsData, setCommentsData] = useState({
    comments: [],
    commentsCount: 0
  });
  const [liveTrafficData, setLiveTrafficData] = useState({
    liveTraffic: [],
    liveTrafficCount: []
  });
	
  const handleActiveListTab = (tabName: TListTab) => {
    setActiveListTab(tabName);
  };

  const getStatusActiveListTabColor = (tabName: TListTab): string => {
    if (activeListTab === tabName) {
      switch (tabName) {
        case LIST_TAB.COMMENTS:
          return 'success';

        case LIST_TAB.ONLINE:
          return 'danger';
      
        default:
          return 'primary'
      }
    }
        
    return 'light';
  };

  const postLivetraffic = async (status: string) => {

    const livetrafficForm = {
      ref: 'vs',
      status: status,
      user_id: userData?.id,
      email: userData?.email,
    }

    const getLivetraffic = await LivestreamService.postLivetraffic(livetrafficForm)
    if (getLivetraffic.success) {
      console.log(getLivetraffic)
      setLiveTrafficData({
        liveTraffic: getLivetraffic.data.liveTraffic,
        liveTrafficCount: getLivetraffic.data.liveTrafficCount
      });
    }
  }

  const fetchComments = async(code: string) => {
    const getComments = await RowdayService.getVSComments(code)
    if (getComments.success) {
      console.log(getComments)
      setCommentsData({
        comments: getComments.data.comments,
        commentsCount: getComments.data.commentsCount
      });
    }
  }

  useEffect(() => {
		fetchComments(vsUsername!);
    postLivetraffic('on');
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);

	return (
		<>
      <div className='row mt-5 mb-5'>
        <div className='col'>
          <Card className='pb-5 fle-bg-antiquewhite'>
            <div className="w-100 bg-light btn-group" role="group" aria-label="Comments And Viewers">
              {Object.keys(LIST_TAB).map((key) => (
                <Button type="button" className="" size={'lg'} rounded={'pill'}
                  key={key}
                  color={getStatusActiveListTabColor(LIST_TAB[key])}
                  onClick={() => handleActiveListTab(LIST_TAB[key])}>
                  {LIST_TAB[key]}
                </Button>
              ))}
            </div>

            <CardBody className=''>
              <div>
                {activeListTab === LIST_TAB.COMMENTS && 
                  <div className=''>
                    {commentsData.comments.map((comm: any) => (
                      <ChatListItem key={comm.id}
                        isActive={true}
                        src={CommentAvatar}
                        srcSet={CommentAvatar}
                        name={comm.user.firstname}
                        surname={comm.user.lastname}
                        isOnline={false}
                        color={'primary'}
                        lastSeenTime={dayjs(comm.created_at).add(-5, 'week').fromNow()}
                        latestMessage={comm.comment}
                      />
                    ))}
                  </div>
                }
                {activeListTab === LIST_TAB.ONLINE && 
                  <>
                    {liveTrafficData.liveTraffic.map((traffic: any) => (
                      <div className='d-flex flex-wrap d-xxl-block bg-light rounded-pill w-75' key={traffic.id}>
                        <Icon className="me-3" icon={'Person'} color={'danger'} size='3x' />
                        <span className='fs-5 me-3'> {traffic.name} </span>
                        <Icon className="me-3" icon={'Flag'} color={'success'} size='3x'/>
                        <span className={classNames('fs-5 me-3', {},)}> {traffic.country}</span>
                      </div>
                    ))}
                  </>
                  
                }
              </div>
            </CardBody>
          </Card>
        </div>
      </div>
    
			
      
		</>
	);
};

export default CommentsViewers;
