import * as React from 'react';
import { useCallback, useMemo } from 'react';
import { useAppDispatch, useAppSelector } from '../Store/reduxHooks';
import { selectMemberIds, setWeek } from './prayerCircleSlice';
import { Body, Button, Column, ColumnCellData, Flex, Grow, Table } from 'react-bootstrap-mobile';
import { PrayerCircleCalculator } from './PrayerCircleCalculator';

export type PartnerTableProps = {};

function PartnerTable({}: PartnerTableProps) {
    // Variables
    const membersIds = useAppSelector((state) => selectMemberIds(state));
    const members = useAppSelector((state) => state.prayerCircle.members);
    const week = useAppSelector((state) => state.prayerCircle.week ?? 0);
    const useWeekdays = useAppSelector((state) => state.prayerCircle.useWeekdays);
    const usePartners = useAppSelector((state) => state.prayerCircle.usePartners);
    const dispatch = useAppDispatch();

    const columnsWeek = useMemo(() => {
        const columns: Column<string>[] = [
            {
                Header: 'Partner 1',
                accessor: 'partner1', // accessor is the "key" in the data
            },
            {
                Header: 'Partner 2',
                accessor: 'partner2',
                width: '50%',
            },
        ];
        if (!usePartners) {
            columns.splice(1, 0, {
                Header: '',
                id: 'prayingTitles',
                Cell: () => (
                    <>
                        <Body block={true}>Ich bete für</Body>
                        <Body block={true} prio="secondary" size="small">
                            Für mich betet
                        </Body>
                    </>
                ),
            });
            // columns[0].Cell = (cellData: ColumnCellData<string>) => {
            //     const partner = cellData.value;
            //     console.log('cellData', cellData);
            //     return (
            //         <div>
            //             <Body>{partner}</Body>
            //             <span>
            //                 {/* <Body>Ich bete für</Body> */}
            //                 <Body prio="secondary" size="small">
            //                     Für mich betet
            //                 </Body>
            //             </span>
            //         </div>
            //     );
            // };

            columns[2].Cell = ({ cell: { column, row }, value: partner }: ColumnCellData<string>) => {
                const other = row.original[`${column.id}Other`];
                return (
                    <>
                        <Body block={true}>{partner}</Body>
                        <Body block={true} prio="secondary" size="small">
                            {other}
                        </Body>
                    </>
                );
            };
        }
        return columns;
    }, [usePartners]);

    const columnsWeekdays = useMemo(() => {
        const columns: Column<string>[] = [
            {
                Header: 'Person',
                accessor: 'person', // accessor is the "key" in the data
            },
            {
                Header: 'Mo',
                accessor: 'day0',
            },
            {
                Header: 'Di',
                accessor: 'day1',
            },
            {
                Header: 'Mi',
                accessor: 'day2',
            },
            {
                Header: 'Do',
                accessor: 'day3',
            },
            {
                Header: 'Fr',
                accessor: 'day4',
            },
            {
                Header: 'Sa',
                accessor: 'day5',
            },
            {
                Header: 'So',
                accessor: 'day6',
            },
        ];
        if (!usePartners) {
            columns[0].Cell = ({ value: partner }: ColumnCellData<string>) => {
                return (
                    <Flex>
                        <Grow>{partner}</Grow>
                        <Grow>
                            <Body block={true}>Ich bete für</Body>
                            <Body block={true} prio="secondary" size="small">
                                Für mich betet
                            </Body>
                        </Grow>
                    </Flex>
                );
            };

            const renderFunction = (cellData: ColumnCellData<string>) => {
                const partner = cellData.value;
                const other = cellData.cell.row.original[`${cellData.cell.column.id}Other`];
                return (
                    <>
                        <Body block={true}>{partner}</Body>
                        <Body block={true} prio="secondary" size="small">
                            {other}
                        </Body>
                    </>
                );
            };
            columns[1].Cell = renderFunction;
            columns[2].Cell = renderFunction;
            columns[3].Cell = renderFunction;
            columns[4].Cell = renderFunction;
            columns[5].Cell = renderFunction;
            columns[6].Cell = renderFunction;
            columns[7].Cell = renderFunction;
        }
        return columns;
    }, [usePartners]);

    // States

    // Refs

    // Callbacks
    const incrementWeek = useCallback(() => dispatch(setWeek(week + 1)), [week, dispatch]);
    const decrementWeek = useCallback(() => dispatch(setWeek(week - 1)), [week, dispatch]);

    // Effects

    // Other
    const [partnerTable, invertedPartnerTable] = useMemo(
        () => PrayerCircleCalculator.generateTableFor(membersIds, usePartners),
        [membersIds, usePartners]
    );

    if (!partnerTable || !invertedPartnerTable || membersIds.length === 0) {
        return null;
    }

    // console.log(partnerTable, invertedPartnerTable);

    const partnerTableNames = partnerTable.map((partnerColumn, index) => {
        return Object.keys(partnerColumn).map((id) => {
            const name = members[id]?.name ?? id;
            const partnerName = members[partnerColumn[id]]?.name ?? partnerColumn[id];
            const otherPartnerName = members[invertedPartnerTable[index][id]]?.name ?? invertedPartnerTable[index][id];
            return [name, partnerName, otherPartnerName];
        }) as [string, string, string][];
    });

    let data: Record<string, string>[] = [];
    if (!useWeekdays) {
        const column = partnerTableNames[week % partnerTableNames.length];
        data = column.map(([name1, name2, name3]) => ({
            partner1: name1,
            partner2: name2,
            partner2Other: name3,
        }));
    } else {
        data = [];
        for (let i = 0; i < 7; i++) {
            const colIndex = (week * 7 + i) % partnerTableNames.length;
            const column = partnerTableNames[colIndex];
            column.forEach(([person, partner1, partner2], index) => {
                if (!data[index]) {
                    data[index] = { person };
                }
                data[index][`day${i}`] = partner1;
                data[index][`day${i}Other`] = partner2;
            });
        }
    }

    const columns = useWeekdays ? columnsWeekdays : columnsWeek;

    // Render Functions

    return (
        <>
            <Flex>
                <Button onClick={decrementWeek}>&lt;</Button>
                <Grow center>Woche {week + 1}</Grow>
                <Button onClick={incrementWeek}>&gt;</Button>
            </Flex>
            {/* <List renderItem={renderPartnerPaar} keyExtractor={partnerKeyExtractor} items={partners}/> */}
            <Table data={data} columns={columns} />
        </>
    );
}

const tmp = React.memo(PartnerTable) as typeof PartnerTable;
export { tmp as PartnerTable };
