import type { Project } from "../types/project";
import type { Table } from "../types/table";
import { useState, type Dispatch, type SetStateAction } from "react";

export interface TablesState {
    tables: Table[]
}

export interface TablesActions {
    addTable: (table: Table) => void,
    deleteTable: (id: string) => void,
    updateTable: (updatedTable: Table) => void
}

export interface TableStateAndActions {
    tableState: TablesState,
    tableActions: TablesActions,
    tableDispatch: {setTables: Dispatch<SetStateAction<Table[]>>}
}

export function useTables(project: Project): TableStateAndActions {

    const [tables, setTables] = useState<Table[]>(project.tables);

    const addTable = async (table: Table) => {
        setTables(cur => [...cur, table])
    }

    const deleteTable = async (id: string) => {
        setTables(cur => cur.filter((cur) => cur.id !== id))
    }

    const updateTable = async (updatedTable: Table) => {
        setTables(cur => cur.map((table) => table.id === updatedTable.id ? updatedTable : table));
    }

    return {
        tableState: { tables },
        tableActions: {
            addTable,
            updateTable,
            deleteTable
        },
        tableDispatch: { setTables }
    }

}