import React, { useEffect, useState } from 'react';
import { GridTable } from '@theorchard/suite-components';
import { GlyphIcon, Illustration } from '@theorchard/suite-icons';
import { camelCase } from 'lodash-es';
import { Link } from 'react-router-dom';
import {
    sortByColumn,
    sortDirection,
} from 'src/apollo/type-constants/schedule';
import { SEARCH_NO_RESULTS_FOUND, DEFAULT_ITEMS_PER_PAGE } from 'src/constants';
import { getContributorDetail } from 'src/urls/frontend-royalties';
import type {
    GridTableColumnDefinition,
    GridTableSortBy,
} from '@theorchard/suite-components';
import type { GetNRContributorsListQuery } from 'src/apollo/queries/nr-contributors/__generated__/get-nr-contributors';

type NrContributors = NonNullable<GetNRContributorsListQuery['nrContributors']>;
type NRContributor = NrContributors['contributors'] extends (infer T)[] | null
    ? T
    : null;

export const CONTRIBUTOR_SCHEDULE_HEADERS: GridTableColumnDefinition[] = [
    {
        name: 'name',
        template: 'contributorName',
        title: 'Contributors',
        sortable: true,
        Cell: ({ data: { id, name } }: any) => (
            <>
                {
                    <div>
                        <Link key={id} to={getContributorDetail(id)}>
                            {name}
                        </Link>
                        <br />
                        <span className="ContributorScheduleList-ContributorLabel">
                            {id}
                        </span>
                    </div>
                }
            </>
        ),
    },
    {
        name: 'abacusUnassignedContributionsCount',
        title: '# Unassigned Contributions',
        sortable: true,
    },
    {
        name: 'abacusSchedules',
        template: 'abacusSchedules',
        title: 'Schedules (# of Contributions)',
        Cell: ({ data: { abacusSchedules } }: any) => {
            return (
                <div className="new">
                    {abacusSchedules.map((s: any) => (
                        <div key={s.scheduleId}>
                            {`${s.scheduleName} - (${s.scheduleAttachments.totalCount})`}
                            {s.conditions?.autoAdd && (
                                <span className="AutoAdd">
                                    <GlyphIcon name="check" size={12} />
                                    <span className="AutoAdd-text">
                                        Auto add new
                                    </span>
                                </span>
                            )}
                        </div>
                    ))}
                </div>
            );
        },
    },
];

export interface ContributorScheduleTablePropTypes {
    contributorList: NRContributor[];
    isLoading: boolean;
    renderPagination: any;
    filterValues: any;
    setFilterValues: any;
}

export const ContributorScheduleTable: React.FC<
    ContributorScheduleTablePropTypes
> = ({
    contributorList,
    isLoading,
    renderPagination,
    filterValues,
    setFilterValues,
}) => {
    const [sortBy, setSortBy] = useState<GridTableSortBy[]>();
    useEffect(() => {
        /* eslint-disable @typescript-eslint/ban-ts-comment */
        if (sortBy)
            setFilterValues({
                ...filterValues,
                // @ts-ignore
                orderBy: sortByColumn[sortBy[0].key],
                // @ts-ignore
                orderDir: sortDirection[sortBy[0].direction],
            });
        /* eslint-enable @typescript-eslint/ban-ts-comment */
    }, [sortBy]);

    return (
        <>
            <div className="ContributorScheduleList-table">
                <GridTable
                    name="ContributorSchedule"
                    header={renderPagination()}
                    data={isLoading ? [] : contributorList}
                    rowKey="id"
                    bordered
                    loading={isLoading}
                    emptyStateIcon={<Illustration name="noResults" />}
                    emptyStateTitle={SEARCH_NO_RESULTS_FOUND}
                    columnDefs={CONTRIBUTOR_SCHEDULE_HEADERS}
                    sortBy={[
                        {
                            key: camelCase(filterValues?.orderBy),
                            direction: filterValues?.orderDir?.toLowerCase(),
                        },
                    ]}
                    onSort={setSortBy}
                    loadingRows={DEFAULT_ITEMS_PER_PAGE}
                />
            </div>
        </>
    );
};

export default ContributorScheduleTable;
