'use client';

import React, { useCallback, useEffect, useState } from 'react';
import styled from 'styled-components';
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 { CustomSelect, Loader } from '../view';
import { useLocalStorage } from '../../hooks/useLocalStorage';
import { AUTH_TOKEN_KEY, AUTH_USER } from '../../constants/common';
import { getRecentSessions, getRequestedSessions, getUpcomingSessions } from '../../actions/profile';
import { Session, Sessions, SessionType } from '../../types/sessions';

const Tab = styled.div``;

export const SessionsTabs = ({ intlConfig, locale }: { intlConfig: Record<string, string>, locale: string }) => {
    const [activeTab, setActiveTab] = useState<number>(0);
    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 [userId] = useLocalStorage(AUTH_USER, '');

    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.data || [],
                    [SessionType.REQUESTED]: requested.data?.requestedSessions || [],
                    [SessionType.RECENT]: recent.data || []
                });
            })
            .catch((err) => {
                setErrorData(err);
            })
            .finally(() => {
                setLoading(false);
            });
    };

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

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

    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">
                            <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
                                                ? `Today ${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>
                    )
                }) : (
                    <div>not found</div>
                )}
            </div>
        </>
    );

    const tabs = [
        {
            key: SessionType.UPCOMING,
            label: (
                <>
                    {intlConfig?.upcoming || 'Tab 1'}
                    {sessions?.upcoming?.length > 0 ? (<span className="count">{sessions?.upcoming.length}</span>) : null}
                </>
            ),
            children: getChildren(sessions?.upcoming)
        },
        {
            key: SessionType.REQUESTED,
            label: (
                <>
                    {intlConfig?.requested || 'Tab 2'}
                    {sessions?.requested?.length > 0 ? (<span className="count">{sessions?.requested.length}</span>) : null}
                </>
            ),
            children: getChildren(sessions?.requested)
        },
        {
            key: SessionType.RECENT,
            label: intlConfig?.recent || 'Tab 3',
            children: getChildren(sessions?.recent)
        }
    ];

    return (
        <Loader
            isLoading={loading}
            errorData={errorData}
            refresh={fetchData}
        >
            <div className="tabs-session">
                {tabs.map((tab, index) => (
                    <Tab
                        key={index}
                        className={`tabs-session__item ${index === activeTab ? 'active' : ''}`}
                        onClick={() => setActiveTab(index)}
                    >
                        {tab.label}
                    </Tab>
                ))}
            </div>
            {tabs[activeTab].children}
        </Loader>
    );
};
