'use client';

import React, { MouseEvent, useCallback, useEffect, useState } from 'react';
import { Empty, Space } from 'antd';
import dayjs from 'dayjs';
import 'dayjs/locale/ru';
import 'dayjs/locale/en';
import 'dayjs/locale/de';
import 'dayjs/locale/it';
import 'dayjs/locale/fr';
import 'dayjs/locale/es';
import { RoomsType } from '../../../types/rooms';
import { getRecentRooms, getUpcomingRooms } from '../../../actions/rooms';
import { Loader } from '../../view/Loader';
import { useLocalStorage } from '../../../hooks/useLocalStorage';
import { AUTH_TOKEN_KEY } from '../../../constants/common';
import { usePathname, useRouter } from '../../../navigation';
import { i18nText } from '../../../i18nKeys';
import { CreateRoom } from './CreateRoom';

type RoomsTabsProps = {
    locale: string;
    activeTab: RoomsType;
};

export const RoomsTabs = ({ locale, activeTab }: RoomsTabsProps) => {
    const [sort, setSort] = useState<string>();
    const [rooms, setRooms] = useState<any>();
    const [loading, setLoading] = useState<boolean>(true);
    const [errorData, setErrorData] = useState<any>();
    const [jwt] = useLocalStorage(AUTH_TOKEN_KEY, '');
    const router = useRouter();
    const pathname = usePathname();

    const fetchData = () => {
        setErrorData(undefined);
        setLoading(true);
        Promise.all([
            getUpcomingRooms(locale, jwt),
            getRecentRooms(locale, jwt)
        ])
            .then(([upcoming, recent]) => {
                setRooms({
                    [RoomsType.UPCOMING]: upcoming || [],
                    [RoomsType.RECENT]: recent || []
                });
            })
            .catch((err) => {
                setErrorData(err);
            })
            .finally(() => {
                setLoading(false);
            });
    };

    useEffect(() => {
        fetchData();
    }, []);

    const onChangeSort = useCallback((value: string) => {
        setSort(value);
    }, [sort]);

    const onClickSession = (event: MouseEvent<HTMLDivElement>, id: number) => {
        event.stopPropagation();
        event.preventDefault();
        router.push(`${pathname}/${id}`);
    };

    const getChildren = (list?: any[]) => (
        <>
            {/* <div className="filter-session">
                <div className="filter-session__item">
                    <CustomSelect
                        label="Topic"
                        value={sort}
                        onChange={onChangeSort}
                        options={[
                            { value: 'topic1', label: 'Topic 1' },
                            { value: 'topic2', label: 'Topic 2' },
                            { value: 'topic3', label: 'Topic 3' },
                            { value: 'topic4', label: 'Topic 4' }
                        ]}
                    />
                </div>
            </div> */}
            <div className="list-session">
                {list && list?.length > 0 ? list?.map(({ id, scheduledStartAtUtc, scheduledEndAtUtc, title, coach, clients, supervisor, maxClients }) => {
                    const startDate = dayjs(scheduledStartAtUtc).locale(locale);
                    const endDate = dayjs(scheduledEndAtUtc).locale(locale);
                    const today = dayjs().format('YYYY-MM-DD') === startDate.format('YYYY-MM-DD');

                    return (
                        <div key={id} className="card-profile session__item" onClick={(e: MouseEvent<HTMLDivElement>) => onClickSession(e, id)}>
                            <div className="card-profile__header">
                                <div className="card-profile__header__portrait">
                                    <img src={coach?.faceImageUrl || '/images/person.png'} className="" alt="" />
                                </div>
                                <div className="card-profile__header__inner">
                                    <div>
                                        <div className="card-profile__header__name">{`${coach?.name} ${coach?.surname || ''}`}</div>
                                        <div className="card-profile__header__title">{title}</div>
                                        <div className={`card-profile__header__date${activeTab === RoomsType.RECENT ? ' history' : (today ? ' chosen' : '')}`}>
                                            {today
                                                ? `${i18nText('today', locale)} ${startDate.format('HH:mm')} - ${endDate.format('HH:mm')}`
                                                : `${startDate.format('D MMMM')} ${startDate.format('HH:mm')} - ${endDate.format('HH:mm')}`}
                                        </div>
                                        <div className="card-room__details">
                                            {supervisor && (
                                                <>
                                                    <div>{i18nText('room.supervisor', locale)}</div>
                                                    <div>{`${supervisor?.name} ${supervisor?.surname || ''}`}</div>
                                                </>
                                            )}
                                            <div>{i18nText('room.members', locale)}</div>
                                            <div>{`${clients.length}/${maxClients}`}</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    )
                }) : (
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={i18nText('noData', locale)} />
                )}
            </div>
        </>
    );

    const tabs = [
        {
            key: RoomsType.UPCOMING,
            label: (
                <>
                    {i18nText('room.upcoming', locale)}
                    {rooms?.upcoming && rooms?.upcoming?.length > 0 ? (<span className="count">{rooms?.upcoming.length}</span>) : null}
                </>
            ),
            children: getChildren(rooms?.upcoming)
        },
        {
            key: RoomsType.RECENT,
            label: i18nText('room.recent', locale),
            children: getChildren(rooms?.recent)
        },
        {
            key: RoomsType.NEW,
            label: i18nText('room.newRoom', locale),
            children: <CreateRoom locale={locale} jwt={jwt} />
        }
    ];

    return (
        <Loader
            isLoading={loading}
            errorData={errorData}
            refresh={fetchData}
        >
            <div className="tabs-session">
                {tabs.map(({ key, label }) => (
                    <Space
                        key={key}
                        className={`tabs-session__item ${key === activeTab ? 'active' : ''}`}
                        onClick={() => router.push(`/account/rooms/${key}`)}
                    >
                        {label}
                    </Space>
                ))}
            </div>
            {tabs.filter(({ key }) => key === activeTab)[0].children}
        </Loader>
    );
};
