'use client';

import React, { useCallback, useEffect, useState, MouseEvent } 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 { Loader } from '../../view/Loader';
import { useLocalStorage } from '../../../hooks/useLocalStorage';
import { AUTH_TOKEN_KEY, AUTH_USER } from '../../../constants/common';
import { getRecentSessions, getRequestedSessions, getUpcomingSessions } from '../../../actions/sessions';
import { Session, Sessions, SessionType } from '../../../types/sessions';
import { useRouter, usePathname } from '../../../navigation';
import { i18nText } from '../../../i18nKeys';

type SessionsTabsProps = {
    locale: string;
    activeTab: SessionType;
};

export const SessionsTabs = ({ locale, activeTab }: SessionsTabsProps) => {
    const [sort, setSort] = useState<string>();
    const [sessions, setSessions] = useState<Sessions>();
    const [loading, setLoading] = useState<boolean>(true);
    const [errorData, setErrorData] = useState<any>();
    const [jwt] = useLocalStorage(AUTH_TOKEN_KEY, '');
    const [userData] = useLocalStorage(AUTH_USER, '');
    const { id: userId = 0 } = userData ? JSON.parse(userData) : {};
    const router = useRouter();
    const pathname = usePathname();

    const fetchData = () => {
        setErrorData(undefined);
        setLoading(true);
        Promise.all([
            getUpcomingSessions(locale, jwt),
            getRequestedSessions(locale, jwt),
            getRecentSessions(locale, jwt)
        ])
            .then(([upcoming, requested, recent]) => {
                setSessions({
                    [SessionType.UPCOMING]: upcoming || [],
                    [SessionType.REQUESTED]: requested?.requestedSessions || [],
                    [SessionType.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?: Session[]) => (
        <>
            {/* <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 }) => {
                    const client = clients?.length ? clients[0] : null;
                    const current = +userId !== client?.id ? client : coach;
                    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={current?.faceImageUrl || '/images/person.png'} className="" alt="" />
                                </div>
                                <div className="card-profile__header__inner">
                                    <div>
                                        <div className="card-profile__header__name">{`${current?.name} ${current?.surname || ''}`}</div>
                                        <div className="card-profile__header__title">{title}</div>
                                        <div className={`card-profile__header__date${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>
                                </div>
                            </div>
                        </div>
                    )
                }) : (
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={i18nText('noData', locale)} />
                )}
            </div>
        </>
    );

    const tabs = [
        {
            key: SessionType.UPCOMING,
            label: (
                <>
                    {i18nText('session.upcoming', locale)}
                    {sessions?.upcoming && sessions?.upcoming?.length > 0 ? (<span className="count">{sessions?.upcoming.length}</span>) : null}
                </>
            ),
            children: getChildren(sessions?.upcoming)
        },
        {
            key: SessionType.REQUESTED,
            label: (
                <>
                    {i18nText('session.requested', locale)}
                    {sessions?.requested && sessions?.requested?.length > 0 ? (<span className="count">{sessions?.requested.length}</span>) : null}
                </>
            ),
            children: getChildren(sessions?.requested)
        },
        {
            key: SessionType.RECENT,
            label: i18nText('session.recent', locale),
            children: getChildren(sessions?.recent)
        }
    ];

    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/sessions/${key}`)}
                    >
                        {label}
                    </Space>
                ))}
            </div>
            {tabs.filter(({ key }) => key === activeTab)[0].children}
        </Loader>
    );
};
