import {Modal} from 'antd';
import React, { useEffect, useState } from 'react';
import LoadingBar from "../LoadingBar";
import { makeApiRequest } from "../../common";
import {useDispatch} from "react-redux";
import {deleteLogs} from "../../httpServices/httpServiceLog";
import {savedAlert} from "../../actions/alertActions";
import { useTranslations } from "../../hooks/useTranslation";

const ActivityTable = ({ activities, isLoading, currentPage, getLogs }) => {
    const { t } = useTranslations();
    const tableHead = [t('user'), t('date'), t('time'), t('action_performed')];
    const [selectAllChecked, setSelectAllChecked] = useState(false);
    const [checkboxes, setCheckboxes] = useState([]);
    const [showDeleteButton, setShowDeleteButton] = useState(false);
    const [isDeleted, setDeleted] = useState(false);
    const [selectedCheckboxes, setSelectedCheckboxes] = useState([]);
    const dispatch = useDispatch();

    useEffect(() => {
        if (activities.logs) {
            console.log(activities.logs)
            const initialCheckboxes = activities.logs.map(log => ({ id: log.id, checked: false }));
            setCheckboxes(initialCheckboxes);
        }
    }, [activities.logs]);

    useEffect(() => {
        const anyCheckboxChecked = checkboxes.some(checkbox => checkbox.checked);
        setShowDeleteButton(anyCheckboxChecked);
        setSelectAllChecked(anyCheckboxChecked && checkboxes.every(checkbox => checkbox.checked));
    }, [checkboxes]);

    useEffect(() => {
        if (isDeleted){
            savedAlert({
                title: "Success",
                description: "Archive deleted successfully!",
            })
            setDeleted(false)
        }
    }, [showDeleteButton, isDeleted]);

    const handleSelectAllChange = () => {
        const updatedCheckboxes = checkboxes.map(checkbox => ({
            ...checkbox,
            checked: !selectAllChecked
        }));
        setCheckboxes(updatedCheckboxes);
    };

    const handleCheckboxChange = (index) => {
        const updatedCheckboxes = [...checkboxes];
        updatedCheckboxes[index] = {
            ...updatedCheckboxes[index],
            checked: !updatedCheckboxes[index].checked
        };
        setCheckboxes(updatedCheckboxes);
    };

    const deleteLogs = async (logs) => {
        const deleteLogStatus = await makeApiRequest('delete-logs', 'POST', logs);
        console.log(deleteLogStatus)
        if(deleteLogStatus.success){
            getLogs()
            setDeleted(true)
        }
    }

    const handleDeleteButtonClick = () => {
        const selectedIds = checkboxes
            .filter(checkbox => checkbox.checked)
            .map(checkbox => checkbox.id);
        setSelectedCheckboxes(selectedIds);
        console.log(selectedIds)

        let updateModal = Modal.confirm({
            title: "Confirmation",
            content: "Are you sure you want to delete activities?",
            centered:true,
            onCancel() {
                updateModal.destroy()
            },
            onOk(){
                deleteLogs({
                    logs: selectedIds
                })
            }
        });
    };

    return (
        <>
            <div className="arcm-table-holder">
                <div className="arcm-table-header">
                    <div className="arcm-grid arcm-grid-cols-4 arcm-rounded-sm arcm-bg-gray-2 arcm-dark:bg-meta-4 arcm-sm:grid-cols-4">
                        {tableHead.map((head, index) => (
                            index === 0 ? (
                                <div className="arcm-p-3 arcm-xl:p-3 arcm-text-left arcm-flex arcm-gap-3" key={index}>
                                    <div className="arcm-flex-shrink-0">
                                        <input
                                            className="slect-all-checkbox"
                                            type="checkbox"
                                            checked={selectAllChecked}
                                            onChange={handleSelectAllChange}
                                        />
                                    </div>
                                    <h5 className="arcm-text-[14px] arcm-font-bold arcm-uppercase">{head}</h5>
                                    {showDeleteButton && (
                                        <button
                                            className="arcm-px-4 arcm-py-2 arcm-bg-red-500 arcm-text-white arcm-rounded hover:bg-red-600 arcm-text-[14px] arcm-leading-[8px]"
                                            onClick={handleDeleteButtonClick}
                                        >
                                            Delete
                                        </button>
                                    )}
                                </div>
                            ) : (
                                <div
                                    className={`arcm-p-3 arcm-xl:p-3 ${index === 0 ? 'arcm-text-left' : index === tableHead.length - 1 ? 'arcm-text-right' : 'arcm-text-center'}`}
                                    key={index}
                                >
                                    <h5 className="arcm-text-[14px] arcm-font-bold arcm-uppercase">{head}</h5>
                                </div>
                            )
                        ))}
                    </div>
                </div>

                <div className="arcm-table-body">
                    {isLoading ? (
                        <LoadingBar />
                    ) : (
                        activities.logs && activities.logs.map((log, index) => (
                            <div key={index} className="arcm-grid arcm-grid-cols-4 arcm-sm:grid-cols-4">
                                <div className="arcm-flex arcm-items-center arcm-gap-3 arcm-p-2 arcm-xl:p-2">
                                    <div className="arcm-flex-shrink-0">
                                        <input
                                            type="checkbox"
                                            value={log.id}
                                            checked={checkboxes[index] ? checkboxes[index].checked : false}
                                            onChange={() => handleCheckboxChange(index)}
                                        />
                                    </div>
                                    <div className="arcm-h-[40px] arcm-w-[40px] arcm-rounded-full arcm-bg-cover" style={{
                                        backgroundImage: `url(${log.user_image_url})`,
                                        backgroundRepeat: "no-repeat",
                                        backgroundPosition: "center"
                                    }}></div>
                                    <span className="arcm-text-[14px] arcm-inline">{log.display_name ? log.display_name : "(no name)"}</span>
                                </div>

                                <div className="arcm-hidden arcm-items-center arcm-justify-center arcm-p-2.5 sm:arcm-flex xl:arcm-p-5">
                                    <p className="arcm-font-medium arcm-text-black dark:arcm-text-white">{log.activity_date}</p>
                                </div>

                                <div className="arcm-hidden arcm-items-center arcm-justify-center arcm-p-2.5 sm:arcm-flex xl:arcm-p-5">
                                    <p className="arcm-font-medium arcm-text-black dark:arcm-text-white">{log.activity_time}</p>
                                </div>

                                <div className="arcm-hidden arcm-items-center arcm-justify-end arcm-p-2 sm:arcm-flex xl:arcm-p-2">
                                    <p className="arcm-font-medium arcm-text-black dark:arcm-text-white">{log.activity}</p>
                                </div>
                            </div>
                        ))
                    )}
                </div>
            </div>
        </>
    );
};

export default ActivityTable;