import { useTable } from "react-table";
import { useMemo } from "react";
import "./StatusDisplay.css";

function ProgressBar({ progress, total }) {
    const percent = total ? Math.round((progress / total) * 100) : 0;
    return (
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <div
                style={{
                    background: "#181a20",
                    borderRadius: 6,
                    width: 80,
                    height: 14,
                    overflow: "hidden",
                    border: "1px solid #3a7afe",
                    marginRight: 8,
                }}
            >
                <div
                    style={{
                        width: `${percent}%`,
                        height: "100%",
                        background: "#3a7afe",
                        transition: "width 0.3s",
                    }}
                />
            </div>
            <span style={{ color: "#e0e6ed", fontSize: 13 }}>
                {progress}/{total} ({percent}%)
            </span>
        </div>
    );
}

export default function StatusesDisplayHUD({ statusMessages }) {
    const msg = {};
    const dataPre = {};
    const columns = [
        { Header: "When", accessor: "WHEN" },
        { Header: "Scheduled", accessor: "SCHEDULED" },
        { Header: "Queued", accessor: "QUEUED" },
        {
            Header: "Processing",
            accessor: "VECTOR_CALC",
            Cell: ({ value }) =>
                value && value.type === "progress" ? (
                    <ProgressBar
                        progress={value.progress}
                        total={value.how_many}
                    />
                ) : (
                    value || ""
                ),
        },
        { Header: "Calculating", accessor: "SCORE_CALC" },
        { Header: "Status", accessor: "STATUS" },
    ];

    statusMessages.forEach((m) => {
        let when_key = "other";
        if (m["task"] == "SCHEDULED")
            m["when"].forEach((w) => {
                msg[w] = "Scheduled";
                dataPre[w] = {
                    SCHEDULED: "✓",
                    QUEUED: "",
                    VECTOR_CALC: "",
                    SCORE_CALC: "",
                    STATUS: "",
                };
            });
        else {
            if ("when" in m) when_key = m["when"];
            let c_task = m["task"];

            let msg_show;
            switch (c_task) {
                case "SCHEDULED":
                    msg_show = "Scheduled";
                    dataPre[when_key]["SCHEDULED"] = "✓";
                    break;
                case "QUEUEING":
                    msg_show = "In compute queue";
                    dataPre[when_key]["QUEUED"] = "✓";
                    break;
                case "SCORE_CALC_IN_FOLDER_START":
                    msg_show = "Calculating Scores";
                    dataPre[when_key]["VECTOR_CALC"] = "...";
                    break;
                case "VECTOR_CALC_IN_FOLDER_START":
                    msg_show = "Started processing videos";
                    dataPre[when_key]["VECTOR_CALC"] = "...";
                    break;
                case "VECTOR_CALC_IN_FOLDER_BUMP":
                    msg_show =
                        "Processing videos: " +
                        m["progress"] +
                        "/" +
                        m["how_many"];
                    // dataPre[when_key]["VECTOR_CALC"] =
                    //     m["progress"] + "/" + m["how_many"];
                    dataPre[when_key]["VECTOR_CALC"] = {
                        progress: m["progress"],
                        how_many: m["how_many"],
                        type: "progress",
                    };
                    break;
                case "VECTOR_CALC_IN_FOLDER_DONE":
                    msg_show = "Finished processing videos";
                    dataPre[when_key]["VECTOR_CALC"] = "✓";
                    break;

                case "SCORE_CALC_IN_FOLDER_DONE":
                    msg_show = "Finished calculating scores";
                    dataPre[when_key]["VECTOR_CALC"] = "✓";
                    dataPre[when_key]["SCORE_CALC"] = "✓";
                    break;
                default:
                    msg_show = c_task;
            }
            msg[when_key] = msg_show;
            // console.log(when_key);
            dataPre[when_key]["STATUS"] = msg_show;
        }
    });

    Object.entries(dataPre).forEach(([k, v]) => {
        v["WHEN"] = k;
    });
    const data = useMemo(() => Object.values(dataPre), [dataPre]);
    const columnsMemo = useMemo(() => columns, []);

    const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } =
        useTable({ columns: columnsMemo, data });

    return (
        <div>
            {rows.length > 0 && (
                <div className="table-container">
                    <table
                        {...getTableProps()}
                        style={{ "--col-count": columns.length - 1 }}
                    >
                        <thead>
                            {headerGroups.map((headerGroup) => (
                                <tr {...headerGroup.getHeaderGroupProps()}>
                                    {headerGroup.headers.map((column) => (
                                        <th {...column.getHeaderProps()}>
                                            {column.render("Header")}
                                        </th>
                                    ))}
                                </tr>
                            ))}
                        </thead>
                        <tbody {...getTableBodyProps()}>
                            {rows.map((row) => {
                                prepareRow(row);
                                return (
                                    <tr {...row.getRowProps()}>
                                        {row.cells.map((cell) => (
                                            <td {...cell.getCellProps()}>
                                                {cell.render("Cell")}
                                            </td>
                                        ))}
                                    </tr>
                                );
                            })}
                        </tbody>
                    </table>
                </div>
            )}
        </div>
    );
}

export function StatusDisplay({ when, message }) {
    let msg_show = "";

    msg_show = when + ": " + message;

    return (
        <div
            className="status-message"
            style={{
                color: "#fff",
                background: "#23272f",
                padding: "8px",
                margin: "4px 0",
                borderRadius: "4px",
                minHeight: "20px",
            }}
        >
            {msg_show}
        </div>
    );
}

//   <div
//         className="status-messages"
//         style={{
//           color: "#fff",
//           background: "#23272f",
//           padding: "8px",
//           margin: "8px 0",
//           borderRadius: "4px",
//           minHeight: "40px",
//         }}
//       >
//         {statusMessages.map((msg, idx) => (
//           <div key={idx}>{msg}</div>
//         ))}
//       </div>
