import React, {useCallback, useEffect, useRef, useState} from 'react';

import {useDispatch, useSelector} from 'react-redux';
import {FormattedMessage} from 'react-intl';
import {Virtuoso} from 'react-virtuoso';

import {BadgeTypeDefinition} from '../../types/badges';
import Client from '../../client/api';
import {RHS_STATE_TYPE_BADGES} from '../../constants';
import {isCreateTypeModalVisible, getEditTypeModalData} from '../../selectors';
import {setRHSView, setRHSType, openEditTypeModal} from '../../actions/actions';

import AllTypesRow from './all_types_row';

import './all_types.scss';

const AllTypes: React.FC = () => {
    const dispatch = useDispatch();
    const [loading, setLoading] = useState(true);
    const [types, setTypes] = useState<BadgeTypeDefinition[]>([]);

    const createTypeVisible = useSelector(isCreateTypeModalVisible);
    const editTypeData = useSelector(getEditTypeModalData);
    const isModalOpen = createTypeVisible || editTypeData !== null;
    const wasModalOpen = useRef(false);

    const fetchTypes = useCallback(async () => {
        const client = new Client();
        const resp = await client.getTypes();
        setTypes(resp.types);
        setLoading(false);
    }, []);

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

    // Refetch types when type modal closes (after save/delete)
    useEffect(() => {
        if (wasModalOpen.current && !isModalOpen) {
            fetchTypes();
        }
        wasModalOpen.current = isModalOpen;
    }, [isModalOpen, fetchTypes]);

    const handleEdit = useCallback((badgeType: BadgeTypeDefinition) => {
        dispatch(openEditTypeModal(badgeType));
    }, [dispatch]);

    const handleDelete = useCallback(async (badgeType: BadgeTypeDefinition) => {
        const client = new Client();
        await client.deleteType(String(badgeType.id));
        setTypes((prev) => prev.filter((t) => t.id !== badgeType.id));
    }, []);

    const handleClick = useCallback((badgeType: BadgeTypeDefinition) => {
        dispatch(setRHSType(badgeType.id, badgeType.name));
        dispatch(setRHSView(RHS_STATE_TYPE_BADGES));
    }, [dispatch]);

    if (loading) {
        return (
            <div className='AllTypes AllTypes--loading'>
                <div className='spinner'/>
            </div>
        );
    }

    if (types.length === 0) {
        return (
            <div className='AllTypes__empty'>
                <FormattedMessage
                    id='badges.types.empty'
                    defaultMessage='Типов пока нет'
                />
            </div>
        );
    }

    return (
        <Virtuoso
            style={{flex: '1 1 auto'}}
            data={types}
            increaseViewportBy={300}
            overscan={200}
            itemContent={(_index, t) => (
                <AllTypesRow
                    key={t.id}
                    badgeType={t}
                    onClick={handleClick}
                    onEdit={handleEdit}
                    onDelete={handleDelete}
                />
            )}
        />
    );
};

export default AllTypes;
