import React, {createRef, useState, Fragment, FC} from 'react';
import {Layout, Col, Row, Button, Image} from 'antd';
import { EditOutlined, CloseOutlined } from '@ant-design/icons';
import ConversationList from "@/components/ConversationList";
import Chatbox from "@/components/Chatbox";
import CustomerInfo from "@/components/CustomerInfo";
import ActionTabs from "@/components/ActionTabs";
import {HelpSideBar} from "@/components/Help";
import HeaderComponent from "@/components/HeaderComponent";

import {useDispatch, useSelector} from "react-redux";
import {AppState} from "@/store/typing";
import {UserInfo} from "@/typings/user";
import {actions} from "@/store/actions";

import GlobalModal from '@/components/GlobalModal';
import GlobalDrawer from "@/components/GlobalDrawer";
import BadgeStatus from "@/components/BadgeStatus";
import NetworkError from "@/components/Error/NetworkError";

import {ClientSettings} from "@/typings";

import TYPING_ANIMATION_IMAGE from "@/assets/typing-animation.gif";
import DashBoard from "@/components/DashBoard";

import {user_list} from "@/test/test_state";

import '@/styles/app.css';


const { Header, Content, Sider } = Layout;

const WINDOW_HEIGHT = global.window.innerHeight;


const UserNameForm = ({user}: {user: UserInfo | null}) => {
    const [openForm, setFormOpen] = useState<boolean>(false);
    const dispatch = useDispatch();

    if( ! user ) {
        return null;
    }

    const userInputRef = createRef<HTMLInputElement>();
    const updateName = () => {
        let new_name = userInputRef.current?.value;
        dispatch(actions.updateUserInfo({
            id: user.id,
            name: new_name,
        }));
        setFormOpen(false);
    }

    if(!openForm) {
        return (
            <Fragment>
                <BadgeStatus online={user.online || false}>
                    {user.name}
                    {
                        user.typing && <Image preview={false} style={{height:20}} src={TYPING_ANIMATION_IMAGE} />
                    }
                </BadgeStatus> ( <EditOutlined onClick={() => setFormOpen(true)} title={'Thay đổi tên'} /> )
            </Fragment>
        )
    }

    return (
        <Fragment>
            <input type={'text'} size={30} ref={userInputRef} defaultValue={user.name} /> <Button onClick={updateName}>OK</Button>
        </Fragment>
    )
}


function getUserById(user_list: UserInfo[], user_id: string) : UserInfo | null {
    let filtered_list = user_list.filter(user => user.id === user_id);
    return filtered_list.length > 0 ? filtered_list[0] : null;
}


const ShowUserSpace = () => {

    // TODO:

    const chatting_with_user = useSelector((state: AppState) => state.chatting_with_user );
    const dispatch = useDispatch();

    let chatting_user_info = getUserById(user_list, chatting_with_user);
    if( ! chatting_user_info && user_list.length > 0) {
        // auto show the first user in the list if there
        dispatch(actions.chatWithUser(user_list[0].id));
    }

    // else show the dashboard
    if( ! chatting_user_info ) {
        return <DashBoard />
    }

    return (
            <Fragment>
                <div>
                    <UserNameForm user={chatting_user_info} />
                </div>

                <Row>
                    <Col span={12}>
                        {/* add key to force to component to remount when user id change to simplify the component's code*/}
                        <Chatbox key={chatting_user_info.id} user_info={chatting_user_info} />
                    </Col>

                    <Col span={12} className="scrollable" style={{height: 600, overflow: 'auto'}}>
                        <h3 style={{fontSize:16, fontWeight:'bold'}}>Lựa chọn</h3>

                        <ActionTabs customer_id={chatting_user_info.id} />

                        <h3 style={{fontSize:16, fontWeight:'bold'}}>Thông tin khách hàng</h3>

                        <CustomerInfo user_info={chatting_user_info} />

                    </Col>
                </Row>
            </Fragment>
    )
}


const App: FC<{client_setting: ClientSettings}> = ({client_setting}) => {

    const HEADER_HEIGHT = 70;
    const [closeHelp, setHelpClose] = useState<boolean>(false);
    const LAYOUT_CLOSED = closeHelp ? {width:1200, marginLeft:'auto', marginRight: 'auto'} : {marginTop: HEADER_HEIGHT, height: WINDOW_HEIGHT - HEADER_HEIGHT, overflow: 'auto'};

    return (
        <Layout>
            <Header style={{ position: 'fixed', zIndex: 1, width: '100%' }}>
                <HeaderComponent />
            </Header>
            <Layout style={LAYOUT_CLOSED}>

                <Sider width={250} className="scrollable">
                    <ConversationList />
                </Sider>

                <Content>
                    <ShowUserSpace />
                </Content>

                {
                    !closeHelp &&
                    <Sider width={400} >
                        <h2>Trợ giúp <CloseOutlined onClick={() => setHelpClose(true)} title={'Đóng'} />  </h2>
                        <HelpSideBar />
                    </Sider>
                }
            </Layout>

            <NetworkError />
            <GlobalModal />
            <GlobalDrawer />

        </Layout>
    )
};

export default App;
