'use client'
import React, { ChangeEvent, ChangeEventHandler, LegacyRef, MouseEventHandler, MutableRefObject, ReactNode, useLayoutEffect, useRef } from "react"
import TableGen from "../TableGen"
import { Attributes, CreationAttributes } from "@sequelize/core";
import { Post } from "@/model/Post";
import { useState } from "react";
import { Project } from "@/model/Project";
import toast from "react-hot-toast"
import { ActionResult } from "@/app/lib/actions/ActionResult";
import { handleActionResult } from "@/app/lib/actions/clientActionHandler";
import PostEditor, { EditorProps } from "./PostEditor";
import { getPosts } from "@/app/lib/actions/entityManagement/postActions";

type Actions = {
    deletePost:(id:number)=>Promise<ActionResult<boolean>>
    getPosts:()=>Promise<ActionResult<Attributes<Post>[]>>
    getProjects:()=>Promise<ActionResult<Attributes<Project>[]>>
    savePost:(data:Partial<Attributes<Post>>)=>Promise<ActionResult<Attributes<Post>[]>>
}

type Props = {
    children?:ReactNode;
    headings:Array<string>;
    data:Attributes<Post>[];
    projects:Attributes<Project>[];
    actions:Actions;
}




export default function PostTable(props:Props){
    

    function closeEditor(){
        setEditor({
            open:false
        })
    }

    function showEditor(entry:Attributes<Post>){
        setEditor({
            open: true,
            post: entry
        })
    }

    const initEditorState:Partial<EditorProps> = {
        open: false,
        post: {}
    }

    const [posts, setPosts] = useState(props.data);
    const [editor, setEditor] = useState(initEditorState)
    const [projects, setProjects] = useState(props.projects);
    
    
    function deletePost(entry:Attributes<Post>){
        props.actions?.deletePost(entry.id)
        .then(actionResult=>{
            const result = handleActionResult(actionResult);
            if (! result) return;
            posts.splice(posts.indexOf(entry),1);
            setPosts([...posts])
            toast.success('Removed Post:' +entry.id);
        });
        
    }
    
    const aifa = (a:ReactNode,b:ReactNode) => a ? a : b
    
    function refetch(){
        props.actions?.getPosts().then((p)=>{
            const result = handleActionResult(p)
            if (result) setPosts(result)
        });
        props.actions.getProjects().then(e=>{
            const result = handleActionResult(e);
            if (result) setProjects(result)
        })
    }

    function savePost(e:Partial<Attributes<Post>>){
        props.actions.savePost({
            id:e.id,
            content: e.content,
            title: e.title,
            project_id: e.project_id
        })
        .then(res=>handleActionResult(res))
        .then(getPosts)
        .then(res=>{
            if (!res.error) setPosts(res.result as Attributes<Post>[]);
        })
        closeEditor();
    };

    return <>
        <TableGen headings={props.headings}>
            {posts.map((d:Attributes<Post>)=>{
                return <><tr key={d.id}>
                    <th key={`row${d.id}`} scope="row">{d.id}</th>
                    <td key='titlefield'>{d.title}</td>
                    <td key='contentfield'>{d.content.length<255 ? d.content :`${d.content.substring(0,255)}...`}</td>
                    <td key='project'>{
                        aifa((projects.find((e)=>{
                            return (e.id == d.project_id)
                        })?.readableIdentifier), 'uncategorized')
                    }</td>
                    <td key='createdatfield'>{d.createdAt?.toString()}</td>
                    <td key='updatedatfield'>{d.updatedAt?.toString()}</td>
                    <td key='btnedit'><button type="button" className="btn btn-primary" onClick={()=>showEditor(d)}>Edit</button></td>
                    <td key='btndelete'><button type="button" className="btn btn-danger" onClick={()=>deletePost(d)}> Delete</button></td>
                </tr>
                {(editor.open && editor.post && editor.post.id == d.id)? 
                <tr key={'activeEditor'}><th scope="row" colSpan={props.headings.length}><PostEditor callbacks={{savePost:savePost, closeEditor:closeEditor}} open={editor.open} post={editor.post} projects={projects} ></PostEditor></th></tr>:""}
                </>
            })}
        </TableGen>
    </>
}