import { BaseControl, Button, Popover, TextareaControl } from "@wordpress/components"
import { close, edit, trash } from "@wordpress/icons"
import { useEffect, useState, useRef } from "@wordpress/element"
import { __ } from "@wordpress/i18n"
import { deleteCommentMutationOptions, updateCommentMutationOptions } from "@/shared/plugin-comments/mutation-options"
import { useMutation } from "@tanstack/react-query"
import { useForm } from "@tanstack/react-form"
import usePluginSelectedStore from "@/stores/pluginSelectedStore"
import { autop } from "@wordpress/autop"

const NoteItem = ({ comment }: { comment: PluginComment }) => {

    const {plugin} = usePluginSelectedStore()

    /**
     * Delete comment
     */

    const [deletePopoverOpen, setDeletePopoverOpen] = useState(false)

    const { mutate: deleteComment, isPending: isDeletingComment } = useMutation(deleteCommentMutationOptions())

    const handleDelete = () => {
        deleteComment(comment, {
            onSettled: () => {
                setDeletePopoverOpen(false)
            }
        })
    }

    /**
     * Edit comment
     */

    const [editOpen, setEditOpen] = useState(false)
    
    const { mutate: updateComment } = useMutation(updateCommentMutationOptions())

    const toggleEdit = () => {
        setEditOpen(!editOpen)
    }

    const form = useForm({
        defaultValues: {
            comment_content: comment.comment_content ?? '',
        },
        onSubmit: (values) => {
            updateComment({
                comment_id: comment.id ?? 0,
                comment_content: values.value.comment_content,
                plugin_slug: plugin?.slug ?? '',
            })
            toggleEdit()
        }
    })

    /**
     * Focus on input when edit is opened
     */

    const inputRef = useRef<HTMLTextAreaElement>(null)

    useEffect(() => {
        if (editOpen) {
            const length = inputRef.current?.value.length ?? 0;
            inputRef.current?.focus();
            inputRef.current?.setSelectionRange(length, length);
        }
    }, [editOpen])

    if (isDeletingComment) {
        return
    }

    return (
        <div key={comment.id} className="bg-white py-1 flex items-start gap-2 justify-between">
            <div className="flex-1 grid grid-cols-1">
                <div className="flex flex-wrap items-center gap-2 !text-neutral-400">
                    <div className="flex items-center gap-1">
                        {
                            comment.comment_user_avatar && (
                                <img src={comment.comment_user_avatar} alt={comment.comment_user_display_name} className="!w-4 !h-4 !rounded-full" />
                            )
                        }
                        <span className="!text-xs !font-normal !my-0 !py-0">{comment.comment_user_display_name}</span>
                    </div>
                    -
                    <time dateTime={comment.comment_date} className="!text-xs !font-normal !my-0 !py-0">{comment.comment_display_date}</time>
                </div>

                {
                    !editOpen && (
                        <div className="prose max-w-none !text-base !font-normal !text-neutral-500" dangerouslySetInnerHTML={{ __html: autop(comment.comment_content ?? '') }}></div>
                    )
                }

                {
                    editOpen && (
                        <div className="flex items-center gap-2">
                            <div className="flex-1 space-y-4">
                                <form.Field
                                    name="comment_content"
                                    children={(field) => (
                                        <BaseControl
                                            label={''}
                                        >
                                            <TextareaControl
                                                value={field.state.value}
                                                onChange={(value) => field.handleChange(value as string)}
                                                placeholder={__('Add your notes here...', 'ploogins-ai-assistant')}
                                                rows={1}
                                                ref={inputRef}
                                            />
                                            {field.state.meta.errors.length > 0 && (
                                                <em>{field.state.meta.errors.join(',')}</em>
                                            )}
                                        </BaseControl>
                                    )}
                                />


                                <div className="flex items-center gap-2 justify-end">

                                    <Button variant="tertiary" onClick={() => {
                                        form.reset()
                                        toggleEdit()
                                    }} icon={close}>
                                        {__('Cancel', 'ploogins-ai-assistant')}
                                    </Button>

                                    <Button variant="primary" onClick={() => {
                                        form.handleSubmit()
                                    }}>
                                        {__('Save', 'ploogins-ai-assistant')}
                                    </Button>
                                </div>
                            </div>
                        </div>
                    )
                }
            </div>
            
            <div className="flex items-center gap-2 pr-2">
                <Button icon={edit} isPressed={editOpen} onClick={toggleEdit} />
                <Button icon={trash} onClick={() => setDeletePopoverOpen(true)}>
                    {deletePopoverOpen && (
                        <Popover onClose={() => setDeletePopoverOpen(false)}>
                            <div className="min-w-[150px] flex justify-center items-center p-2">
                                <button role="button" className="cursor-pointer !text-sm !text-red-500 hover:underline" onClick={handleDelete}>{__('Confirm delete', 'ploogins-ai-assistant')}</button>
                            </div>
                        </Popover>
                    )}
                </Button>
            </div>
        </div>
    )
}

export default NoteItem