import React, { useContext, useEffect, useState } from 'react'
import { ConfigContext } from '../../Context/ConfigContext'
import axios from 'axios'
import { useParams } from 'react-router-dom'
import { DateFormaterMonth, DateFormater, TimeFormater, formatDateTime } from '../../Components/GlobalFunctions'
import Swal from "sweetalert2";
import Select from "react-select";
import Flatpickr from "react-flatpickr";
import "flatpickr/dist/themes/material_blue.css";

const TaskList = () => {
    const { apiHeaderJson, apiURL, user_id } = useContext(ConfigContext)
    const headers = apiHeaderJson
    const { status } = useParams();

    const [data, setData] = useState([])
    const [loading, setLoading] = useState(true)

    // States for edit modal
    const [dateRange, setDateRange] = useState([null, null]);
    const [title, setTitle] = useState("");
    const [description, setDescription] = useState("");
    const [profileRow, setProfileRow] = useState([]);
    const [profile_id, setProfile_id] = useState(0);
    const [priority, setPriority] = useState(1);
    const [projectTaskId, setProjectTaskId] = useState(null);
    const [projectId, setProjectId] = useState(null);
    const [projectRow, setProjectRow] = useState([]);
    const [selectedProjectId, setSelectedProjectId] = useState(null);
    const [assignedDateSortOrder, setAssignedDateSortOrder] = useState("desc");
    const [next, setNext] = useState(false);
    const [prev, setPrev] = useState(false);
    const [page, setPage] = useState(1);
    const [limit] = useState(10);
    const [totalRecords, setTotalRecords] = useState(0);
    const [totalPages, setTotalPages] = useState(0);

    // States for comments
    const [commentData, setCommentData] = useState([]);
    const [comment, setComment] = useState("");
    const [ptc_id, setPTC_id] = useState(0);
    const today = new Date();

    const [filterPriority, setFilterPriority] = useState(null);
    const [filterProject, setFilterProject] = useState("");

    const priorityFilterOptions = [
        { value: 1, label: "Low" },
        { value: 2, label: "Medium" },
        { value: 3, label: "High" }
    ];

    const statusOptions = [
        { value: 1, label: 'Assign' },
        { value: 2, label: 'Complete' }
    ]

    const toggleAssignedDateSort = () => {
        setAssignedDateSortOrder((prev) =>
            prev === "asc" ? "desc" : "asc"
        );
    };

    const filteredData = data
        .filter((row) => {
            const priorityMatch = filterPriority
                ? row.project_task_priority === filterPriority.value
                : true;

            const projectMatch = filterProject
                ? row.project_title?.toLowerCase().includes(filterProject.toLowerCase())
                : true;

            return priorityMatch && projectMatch;
        })
        .sort((a, b) => {
            const dateA = new Date(a.project_task_assigned_datetime);
            const dateB = new Date(b.project_task_assigned_datetime);

            return assignedDateSortOrder === "asc"
                ? dateA - dateB
                : dateB - dateA;
        });

    const GetProjects = async () => {
        try {
            const response = await axios.get(`${apiURL}api/projects`);
            const { success, data } = response.data;

            if (success) {
                setProjectRow(
                    data.map((row) => ({
                        value: row.project_id,
                        label: row.project_title,
                    }))
                );
            }
        } catch (error) {
            console.log(error);
        }
    };

    const GetList = async () => {
        try {
            const response = await axios
                .get(`${apiURL}api/tasks/getAllProjectTaskByStatus`, {
                    headers,
                    params: { status: status, page, limit }
                });
            const { data, success } = response.data;

            if (success) {
                setData(data);
                setNext(response.data.next);
                setPrev(response.data.prev);
                setPage(response.data.page);
                setTotalRecords(response.data.total_records);
                setTotalPages(response.data.total_pages);
            }
            setLoading(false);
        } catch (error) {
            setLoading(false);
            console.log(error);
        }
    };

    const handleStatusChange = async (project_task_status, project_task_id) => {
        try {
            const result = await Swal.fire({
                title: "Are you sure?",
                text: `Do you really want to ${project_task_status === 1 ? "Assign" : "Complete"}?`,
                icon: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                cancelButtonText: "No"
            });

            if (result.isConfirmed) {
                const body = {
                    project_task_id,
                    project_task_status: project_task_status
                }
                const response = await axios.post(`${apiURL}api/tasks/UpdateTaskStatus`, body, { headers })
                const { success, message } = response.data

                if (success) {
                    Swal.fire('Success', message, 'success')
                    GetList()
                }
            }
        } catch (error) {
            console.log("error changing status", error)
        }
    }

    // Get Profiles for assignee dropdown
    const GetProfiles = async () => {
        try {
            const response = await axios.get(`${apiURL}api/profiles`);
            const { data, success } = response.data;
            if (success === true) {
                setProfileRow(
                    data.map((row) => ({
                        value: row.profile_id,
                        label: `${row.profile_name} -- ${row.pc_category_title}`,
                    }))
                );
            }
        } catch (error) {
            console.log(error);
        }
    };

    const handleSelect = (selectedOption) => {
        setProfile_id(selectedOption ? selectedOption.value : null);
    };

    const handlePriorityChange = (value) => {
        setPriority(value);
    };

    const GetInfo = async (id) => {
        try {
            const response = await axios.get(`${apiURL}api/tasks`, {
                params: { project_task_id: id },
            });
            const { data, success } = response.data;
            if (success === true && data.length > 0) {
                const task = data[0];
                setProjectId(task.pt_project_id)
                setProjectTaskId(task.project_task_id);
                setTitle(task.project_task_title);
                setDescription(task.project_task_description);
                setProfile_id(task.project_task_assigned_to);
                setDateRange(task.project_task_due_datetime);
                setPriority(task.project_task_priority);
            }
        } catch (error) {
            console.log(error);
        }
    };

    const handleSubmit = async () => {

        const project_id = projectTaskId ? projectId : selectedProjectId

        const Body = {
            pt_project_id: project_id,
            project_task_title: title,
            project_task_description: description,
            project_task_due_datetime: dateRange.length === 1 ? formatDateTime(dateRange[0]) : dateRange,
            project_task_assigned_to: profile_id,
            project_task_assigned_by: "1",
            project_task_priority: priority,
            project_task_assigned_datetime: formatDateTime(today),
        };

        if (projectTaskId) {
            Body.project_task_id = projectTaskId;
        }

        try {
            const requestMethod = projectTaskId ? "post" : "post";
            const response = await axios[requestMethod](`${apiURL}api/tasks`, Body);

            if (response.data.success) {
                Swal.fire({
                    icon: "success",
                    title: response.data.message,
                    showConfirmButton: false,
                    timer: 1500,
                });
                document.getElementById("close-modals")?.click();
                GetList();
                handleResetForm();
            }
        } catch (error) {
            console.log(error);
            Swal.fire({
                icon: "error",
                title: "Error",
                text: "Failed to save task",
            });
        }
    };

    const handleDelete = (id) => {
        Swal.fire({
            title: "Are you sure?",
            text: "You won't be able to revert this!",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            confirmButtonText: "Yes, delete it!",
        }).then((result) => {
            if (result.isConfirmed) {
                axios
                    .delete(`${apiURL}api/tasks`, {
                        params: { project_task_id: id },
                    })
                    .then((response) => {
                        Swal.fire({
                            title: `<strong>${response.data.success ? "Success" : "Failed"
                                }</strong>`,
                            text: response.data.message,
                            icon: response.data.success ? "success" : "error",
                            timer: 1000,
                            timerProgressBar: true,
                            showConfirmButton: false,
                        });

                        if (response.data.success) {
                            GetList();
                        }
                    })
                    .catch((error) => {
                        Swal.fire({
                            title: <strong>Error</strong>,
                            html: error,
                            icon: "error",
                        });
                    });
            }
        });
    };

    // Get comments for a task
    const GetComments = async (pt_id) => {
        try {
            setPTC_id(pt_id);
            const response = await axios.get(`${apiURL}api/tasks/comments`, {
                params: { pt_id: pt_id },
            });
            const { data, success } = response.data;

            if (success === true) {
                setCommentData(data);
            }
        } catch (error) {
            console.log(error);
        }
    };

    // Handle comment submission
    const handleSubmitComment = async () => {
        const Body = {
            pt_id: ptc_id,
            pt_comment: comment,
            pt_comment_by: user_id,
        };
        try {
            const response = await axios.post(`${apiURL}api/tasks/comments`, Body);
            const { success } = response.data;
            if (success) {
                GetComments(ptc_id);
                setComment("");
            }
        } catch (error) {
            console.log(error);
        }
    };

    // Reset form fields
    const handleResetForm = () => {
        setDateRange([null, null]);
        setTitle("");
        setDescription("");
        setProfile_id(0);
        setPriority(1);
        setProjectTaskId(null);
        setProjectId(null);
        setSelectedProjectId(null)
    };

    const getStatusBadge = (status) => {
        let badgeClass = '';
        let statusText = '';

        switch (status) {
            case 1:
                badgeClass = 'bg-warning-subtle text-warning';
                statusText = 'Pending';
                break;
            case 2:
                badgeClass = 'bg-success-subtle text-success';
                statusText = 'Completed';
                break;
            default:
                badgeClass = 'bg-secondary-subtle text-secondary';
                statusText = 'Unknown';
        }

        return <span className={`badge ${badgeClass}`}>{statusText}</span>;
    }

    const getPriorityBadge = (priority) => {
        let badgeClass = '';
        let priorityText = '';

        switch (priority) {
            case 1:
                badgeClass = 'bg-primary text-white';
                priorityText = 'Low';
                break;
            case 2:
                badgeClass = 'bg-secondary text-white';
                priorityText = 'Medium';
                break;
            case 3:
                badgeClass = 'bg-danger text-white';
                priorityText = 'High';
                break;
            default:
                badgeClass = 'bg-light text-white';
                priorityText = 'Unknown';
        }

        return <span className={`badge ${badgeClass}`}>{priorityText}</span>;
    }

    const handlePrev = () => {
        if (prev) {
            setPage((prevPage) => prevPage - 1);
        }
    };

    const handleNext = () => {
        if (next) {
            setPage((prevPage) => prevPage + 1);
        }
    };

    const handleChange = (e) => {
        setPage(parseInt(e.target.value, 10));
    };

    useEffect(() => {
        GetList();
        GetProfiles();
        GetProjects()
    }, [status])

    return (
        <div className="main-content">
            <div className="page-content">
                <div className="container-fluid">
                    <div className="row">
                        <div className="col-12">
                            <div className="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 className="mb-sm-0">Task List</h4>
                                <div className="page-title-right">
                                    <ol className="breadcrumb m-0">
                                        <li className="breadcrumb-item">
                                            <a>Dashboard</a>
                                        </li>
                                        <li className="breadcrumb-item active">Task List</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div className="row">
                        <div className="col-md-12">
                            <div className="card">
                                <div className="card-header" style={{ background: "#000000" }}>
                                    <div className="row d-flex align-items-center">
                                        <div className="col-md-6">
                                            <h4 className='text-white mb-0'>Task List</h4>
                                        </div>

                                        <div className="col-md-6 text-end">
                                            <button
                                                className="btn btn-secondary btn-label"
                                                data-bs-toggle="modal"
                                                data-bs-target="#taskModal"
                                                onClick={() => {
                                                    handleResetForm();
                                                    setProjectTaskId(null);
                                                }}
                                            >
                                                <i className="ri-add-line label-icon"></i>
                                                Assign Task
                                            </button>
                                        </div>
                                    </div>
                                </div>

                                <div className="card-body">
                                    <div className="row mb-3">
                                        <div className="col-md-3 mb-2">
                                            <input
                                                type="text"
                                                className="form-control"
                                                placeholder="Search by project name..."
                                                value={filterProject}
                                                onChange={(e) => setFilterProject(e.target.value)}
                                            />
                                        </div>

                                        <div className="col-md-3 mb-2">
                                            <Select
                                                options={priorityFilterOptions}
                                                value={filterPriority}
                                                onChange={(option) => setFilterPriority(option)}
                                                isClearable={true}
                                                placeholder="Select by Priority"
                                            />
                                        </div>

                                        <div className="col-md-1">
                                            <button
                                                type="button"
                                                className="btn btn-light"
                                                onClick={() => {
                                                    setFilterPriority(null);
                                                    setFilterProject("");
                                                }}
                                            >
                                                Clear
                                            </button>
                                        </div>
                                    </div>
                                    <div className="table-responsive table-card">
                                        <table className="table table-bordered table-striped table-nowrap table-hover mb-0">
                                            {loading ? (
                                                <tbody>
                                                    <tr>
                                                        <td colSpan="10" className="text-center">
                                                            <div className="spinner-border text-primary" role="status">
                                                                <span className="visually-hidden">Loading...</span>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                </tbody>
                                            ) : (
                                                <>
                                                    <thead className="table-light text-center">
                                                        <tr>
                                                            <th>Task ID</th>
                                                            <th>Project</th>
                                                            <th>Task</th>
                                                            <th>Description</th>
                                                            <th>Due Date</th>
                                                            <th>Assigned To</th>
                                                            <th
                                                                style={{ cursor: "pointer", userSelect: "none" }}
                                                                onClick={toggleAssignedDateSort}
                                                            >
                                                                Assigned Date{" "}
                                                                <i
                                                                    className={
                                                                        assignedDateSortOrder === "asc"
                                                                            ? "ri-arrow-up-s-line align-middle"
                                                                            : "ri-arrow-down-s-line align-middle"
                                                                    }
                                                                ></i>
                                                            </th>
                                                            <th>Priority</th>
                                                            <th>Status</th>
                                                            <th>Action</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        {filteredData.length > 0 ? (
                                                            filteredData.map((row) => (
                                                                <tr key={row.project_task_id} className="text-center">
                                                                    <td>{row.project_task_id}</td>
                                                                    <td>{row.project_title}</td>
                                                                    <td>{row.project_task_title}</td>
                                                                    <td style={{ maxWidth: "180px" }} title={row.project_task_description}>
                                                                        <div className="ellipsis-1">
                                                                            {row.project_task_description}
                                                                        </div>
                                                                    </td>
                                                                    <td>{DateFormaterMonth(row.project_task_due_datetime)}</td>
                                                                    <td>{row.assigned_to_name}</td>
                                                                    <td>{DateFormaterMonth(row.project_task_assigned_datetime)}</td>
                                                                    <td>{getPriorityBadge(row.project_task_priority)}</td>
                                                                    <td>{getStatusBadge(row.project_task_status)}</td>
                                                                    <td>
                                                                        <div className="btn-group" role="group">
                                                                            {/* Edit Button */}
                                                                            <button
                                                                                className="btn btn-sm btn-soft-primary"
                                                                                data-bs-toggle="modal"
                                                                                data-bs-target="#taskModal"
                                                                                onClick={() => GetInfo(row.project_task_id)}
                                                                                title="Edit Task"
                                                                            >
                                                                                <i className="ri-edit-line"></i>
                                                                            </button>

                                                                            {/* Comments Button */}
                                                                            <button
                                                                                className="btn btn-sm btn-soft-info mx-1"
                                                                                data-bs-toggle="offcanvas"
                                                                                data-bs-target="#commentsOffcanvas"
                                                                                aria-controls="commentsOffcanvas"
                                                                                onClick={() => GetComments(row.project_task_id)}
                                                                                title="View Comments"
                                                                            >
                                                                                <i className="ri-chat-3-line"></i>
                                                                            </button>

                                                                            {/* Delete Button */}
                                                                            <button
                                                                                className="btn btn-sm btn-soft-danger"
                                                                                onClick={() => handleDelete(row.project_task_id)}
                                                                                title="Delete Task"
                                                                            >
                                                                                <i className="ri-delete-bin-5-line"></i>
                                                                            </button>

                                                                            {/* Status Dropdown */}
                                                                            {row.project_task_status !== 2 && (
                                                                                <div className="dropdown d-inline-block ms-1">
                                                                                    <button
                                                                                        className="btn btn-sm btn-soft-secondary dropdown-toggle"
                                                                                        type="button"
                                                                                        data-bs-toggle="dropdown"
                                                                                        aria-expanded="false"
                                                                                        title="Change Status"
                                                                                    >
                                                                                        <i className='ri-list-check'></i>
                                                                                    </button>
                                                                                    <ul className="dropdown-menu">
                                                                                        {statusOptions
                                                                                            .filter((option) => {
                                                                                                if (status == 0) return true;
                                                                                                if (status == 1) return option.value === 2;
                                                                                            })
                                                                                            .map(option => (
                                                                                                <li key={option.value}>
                                                                                                    <button
                                                                                                        className="dropdown-item"
                                                                                                        onClick={() => handleStatusChange(option.value, row.project_task_id)}
                                                                                                    >
                                                                                                        {option.label}
                                                                                                    </button>
                                                                                                </li>
                                                                                            ))}
                                                                                    </ul>
                                                                                </div>
                                                                            )}
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                            ))
                                                        ) : (
                                                            <tr>
                                                                <td colSpan={10} className="text-center">
                                                                    No tasks found
                                                                </td>
                                                            </tr>
                                                        )}
                                                    </tbody>
                                                    <tfoot className="table-light">
                                                        <tr>
                                                            <th colSpan={6}>
                                                                <div className="d-flex justify-content-between">
                                                                    <button
                                                                        disabled={
                                                                            prev === false && loading === false
                                                                                ? true
                                                                                : false
                                                                        }
                                                                        type="button"
                                                                        onClick={() => handlePrev()}
                                                                        className={`btn btn-warning btn-label waves-effect waves-light`}
                                                                    >
                                                                        <i className="ri-arrow-left-line label-icon align-middle fs-16 me-2" />{" "}
                                                                        Previous
                                                                    </button>
                                                                    <div
                                                                        className="col-md-4"
                                                                        style={{
                                                                            display: "flex",
                                                                            alignItems: "center",
                                                                        }}
                                                                    >
                                                                        {
                                                                            <small>
                                                                                Total Records: {totalRecords} | Total
                                                                                Pages: {totalPages} | Current Page:{" "}
                                                                                {page}
                                                                            </small>
                                                                        }
                                                                    </div>
                                                                    <div className="col-md-2">
                                                                        <select
                                                                            className="form-select"
                                                                            onChange={(e) => handleChange(e)}
                                                                        >
                                                                            {Array.from(
                                                                                { length: totalPages },
                                                                                (_, i) => (
                                                                                    <option
                                                                                        key={i + 1}
                                                                                        selected={page === i + 1}
                                                                                        value={i + 1}
                                                                                    >
                                                                                        {i + 1}
                                                                                    </option>
                                                                                )
                                                                            )}
                                                                        </select>
                                                                    </div>
                                                                    <button
                                                                        disabled={
                                                                            next === false && loading === false
                                                                                ? true
                                                                                : false
                                                                        }
                                                                        type="button"
                                                                        onClick={() => handleNext()}
                                                                        className={`btn btn-primary btn-label waves-effect right waves-light`}
                                                                    >
                                                                        <i className="ri-arrow-right-line label-icon align-middle fs-16 ms-2" />{" "}
                                                                        Next
                                                                    </button>
                                                                </div>
                                                            </th>
                                                        </tr>
                                                    </tfoot>
                                                </>
                                            )}
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {/* Task Modal */}
            <div
                className="modal fade"
                id="taskModal"
                data-bs-backdrop="static"
                data-bs-keyboard="false"
                tabIndex={-1}
                role="dialog"
                aria-labelledby="taskModalLabel"
                aria-hidden="true"
            >
                <div className="modal-dialog modal-dialog-centered" role="document">
                    <div className="modal-content ">
                        <div className="modal-header">
                            <h5 className="modal-title" id="taskModalLabel">
                                {projectTaskId ? "Update Task" : "New Task"}
                            </h5>
                            <button
                                type="button"
                                className="btn-close"
                                data-bs-dismiss="modal"
                                aria-label="Close"
                                onClick={handleResetForm}
                            ></button>
                        </div>
                        <div className="modal-body px-5">
                            <div className="row">
                                {!projectTaskId && (
                                    <div className="col-md-12 mb-3">
                                        <label>Project :</label>
                                        <Select
                                            options={projectRow}
                                            placeholder="Select Project"
                                            value={
                                                selectedProjectId
                                                    ? projectRow.find(
                                                        (option) => option.value === selectedProjectId
                                                    )
                                                    : null
                                            }
                                            onChange={(option) =>
                                                setSelectedProjectId(option ? option.value : null)
                                            }
                                        />
                                    </div>
                                )}
                                <div className="col-md-12">
                                    <label>Title:</label>
                                    <input
                                        type="text"
                                        value={title}
                                        onChange={(e) => setTitle(e.target.value)}
                                        name="title"
                                        className="form-control"
                                        placeholder="Enter task title"
                                    />
                                </div>
                                <div className="mt-3 col-md-12">
                                    <label>Description :</label>
                                    <textarea
                                        type="text"
                                        value={description}
                                        name="description"
                                        className="form-control"
                                        onChange={(e) => setDescription(e.target.value)}
                                        placeholder="Enter task description"
                                        rows="3"
                                    />
                                </div>
                                <div className="col-md-12 mt-3 ">
                                    <label>Assign to :</label>
                                    <Select
                                        onChange={handleSelect}
                                        options={profileRow}
                                        placeholder="Please Select Profile"
                                        value={
                                            profile_id
                                                ? profileRow.find(
                                                    (option) => option.value === profile_id
                                                )
                                                : null
                                        }
                                    />
                                </div>
                                <div className="col-md-12 mt-3">
                                    <label>Due Date</label>
                                    <Flatpickr
                                        data-enable-time
                                        placeholder="Please Select Date"
                                        className="form-control date-picker "
                                        value={dateRange}
                                        onChange={(selectedDates) => {
                                            setDateRange(selectedDates);
                                        }}
                                        options={{
                                            minDate: "today",
                                            dateFormat: "Y-m-d H:i",
                                        }}
                                    />
                                </div>
                                <div className="col-md-12 mt-3">
                                    <label>Task Priority :</label>
                                    <div className="row ms-2">
                                        <div className="col-md-4 form-check form-radio-warning ">
                                            <input
                                                className="form-check-input"
                                                type="radio"
                                                id="High"
                                                name="priority"
                                                checked={priority === 3}
                                                onChange={() => handlePriorityChange(3)}
                                            />
                                            <label htmlFor="High">High</label>
                                        </div>
                                        <div className="col-md-4 form-check form-radio-secondary ">
                                            <input
                                                className="form-check-input"
                                                type="radio"
                                                id="Medium"
                                                name="priority"
                                                checked={priority === 2}
                                                onChange={() => handlePriorityChange(2)}
                                            />
                                            <label htmlFor="Medium">Medium</label>
                                        </div>
                                        <div className="col-md-4 form-check form-radio-info ">
                                            <input
                                                className="form-check-input"
                                                type="radio"
                                                id="Low"
                                                name="priority"
                                                checked={priority === 1}
                                                onChange={() => handlePriorityChange(1)}
                                            />
                                            <label htmlFor="Low">Low</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="modal-footer">
                            <button
                                type="button"
                                className="btn btn-light"
                                data-bs-dismiss="modal"
                                id="close-modals"
                                onClick={handleResetForm}
                            >
                                Close
                            </button>
                            <button
                                type="button"
                                className="btn btn-success"
                                onClick={handleSubmit}
                                disabled={
                                    !title ||
                                    !description ||
                                    !profile_id ||
                                    !dateRange ||
                                    !priority ||
                                    (!projectTaskId && !selectedProjectId)
                                }
                            >
                                {projectTaskId ? "Update" : "Submit"}
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            {/* Comments Offcanvas */}
            <div
                className="offcanvas offcanvas-start"
                tabIndex={-1}
                id="commentsOffcanvas"
                aria-labelledby="commentsOffcanvasLabel"
            >
                <div className="offcanvas-header border-bottom">
                    <h5 className="offcanvas-title" id="commentsOffcanvasLabel">
                        Task Comments
                    </h5>
                    <button
                        type="button"
                        className="btn-close text-reset"
                        data-bs-dismiss="offcanvas"
                        aria-label="Close"
                    />
                </div>
                <div className="offcanvas-body p-0 overflow-hidden">
                    <div data-simplebar style={{ height: "calc(100vh - 112px)" }}>
                        <div className="acitivity-timeline p-4">
                            {commentData.length === 0 ? (
                                <div className="text-center text-muted">
                                    No comments yet. Start the conversation by adding a comment.
                                </div>
                            ) : (
                                commentData.map((item, index) => {
                                    return (
                                        <div className="acitivity-item d-flex" key={index}>
                                            <div className="flex-shrink-0 avatar-xs acitivity-avatar">
                                                <div className="avatar-title bg-success-subtle text-success rounded-circle">
                                                    {item.pt_comment_by === 1 ? "A" : "C"}
                                                </div>
                                            </div>
                                            <div className="flex-grow-1 ms-3">
                                                <h6 className="mb-1">
                                                    {item?.profile_name}
                                                </h6>
                                                <p className="text-muted mb-2">{item.pt_comment}</p>
                                                <small className="mb-0 text-muted">
                                                    {DateFormater(item.pt_comment_datetime)} -
                                                    {TimeFormater(item.pt_comment_datetime)}
                                                </small>
                                            </div>
                                        </div>
                                    );
                                })
                            )}

                            <form className="mt-4">
                                <div className="row g-3">
                                    <div className="col-lg-12">
                                        <label
                                            htmlFor="commentInput"
                                            className="form-label"
                                        >
                                            Leave a Comment
                                        </label>
                                        <textarea
                                            className="form-control bg-light border-light"
                                            id="commentInput"
                                            name="comment"
                                            value={comment}
                                            onChange={(e) => setComment(e.target.value)}
                                            rows={3}
                                            placeholder="Enter your comment..."
                                        />
                                    </div>
                                    <div className="col-12 text-end">
                                        <button
                                            type="button"
                                            className="btn btn-primary"
                                            onClick={handleSubmitComment}
                                            disabled={!comment}
                                        >
                                            Post Comment
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default TaskList