'use client';

import React, {FC, useCallback, useEffect, useState} from 'react';
import { Modal, Button, List, message } from 'antd';
import { CloseOutlined } from '@ant-design/icons';
import { i18nText } from '../../i18nKeys';
import { useLocalStorage } from '../../hooks/useLocalStorage';
import { AUTH_TOKEN_KEY } from '../../constants/common';
import { ExpertsTags, Tag } from '../../types/tags';
import { CustomSwitch } from '../view/CustomSwitch';
import { setTags } from '../../actions/profile';

type EditExpertTagsModalProps = {
    open: boolean;
    handleCancel: () => void;
    locale: string;
    data?: ExpertsTags;
    refresh: () => void;
};

export const EditExpertTagsModal: FC<EditExpertTagsModalProps> = ({
    open,
    handleCancel,
    locale,
    data,
    refresh
}) => {
    const [jwt] = useLocalStorage(AUTH_TOKEN_KEY, '');
    const [loading, setLoading] = useState<boolean>(false);
    const [expertTags, setExpertTags] = useState<Tag[]>([]);

    useEffect(() => {
        setExpertTags(data?.themesTags || []);
    }, [data]);

    const onSaveTags = () => {
        setLoading(true);
        setTags(locale, jwt, { themesGroups: data?.themesGroups, themesTags: expertTags })
            .then(() => {
                handleCancel();
                refresh();
            })
            .catch(() => {
                message.error('Не удалось сохранить направления');
            })
            .finally(() => {
                setLoading(false);
            })
    };

    const updateTag = useCallback((id: number, isSelected: boolean) => {
        setExpertTags(expertTags.map((tag) => {
            if (tag.id === id) {
                tag.isSelected = isSelected;
            }
            return tag;
        }))
    }, [expertTags, setExpertTags]);

    return (
        <Modal
            className="b-modal"
            open={open}
            title={undefined}
            onOk={undefined}
            onCancel={handleCancel}
            footer={false}
            width={498}
            closeIcon={<CloseOutlined style={{ fontSize: 20, color: '#000' }}/>}
        >
            <div className="b-modal__expert__content">
                <div className="b-modal__expert__title">{i18nText('selectTopic', locale)}</div>
                <div className="b-modal__expert__inner">
                    {data?.themesGroups && data.themesGroups.filter(({ isActive }) => isActive).map(({ id, name }) => (
                        <div key={`group_${id}`}>
                            <h3 className="title-h4">{name}</h3>
                            {expertTags?.length > 0 ? (
                                <div className="b-filter__inner">
                                    <List
                                        itemLayout="vertical"
                                        size="small"
                                        dataSource={expertTags.filter(({ isActive, groupId }) => (isActive && groupId == id)) || []}
                                        split={false}
                                        style={{ width: '100%' }}
                                        renderItem={({ id, name, isSelected }) => (
                                            <List.Item key={`tag_${id}`} style={{ padding: 0 }}>
                                                <div className="b-filter__item">
                                                    <div className="b-filter__title">{name}</div>
                                                    <CustomSwitch
                                                        defaultChecked={isSelected || false}
                                                        onChange={(checked: boolean) => updateTag(id, checked)}
                                                    />
                                                </div>
                                            </List.Item>
                                        )}
                                    />
                                </div>
                            ) : <div>No tags</div>}
                        </div>
                    ))}
                </div>
                <div className="b-modal__expert__button">
                    <Button
                        className="card-detail__apply"
                        onClick={onSaveTags}
                        loading={loading}
                    >
                        {i18nText('save', locale)}
                    </Button>
                </div>
            </div>
        </Modal>
    );
};
