/*
 * Copyright (c) 2021-2026 ahriman team.
 *
 * This file is part of ahriman
 * (see https://github.com/arcan1s/ahriman).
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
import "highlight.js/styles/github.css";

import { Box } from "@mui/material";
import { useQuery } from "@tanstack/react-query";
import CodeBlock from "components/common/CodeBlock";
import hljs from "highlight.js/lib/core";
import diff from "highlight.js/lib/languages/diff";
import { QueryKeys } from "hooks/QueryKeys";
import { useClient } from "hooks/useClient";
import type { Changes } from "models/Changes";
import type { RepositoryId } from "models/RepositoryId";
import React, { useEffect, useRef } from "react";

hljs.registerLanguage("diff", diff);

interface ChangesTabProps {
    packageBase: string;
    repository: RepositoryId;
}

export default function ChangesTab({ packageBase, repository }: ChangesTabProps): React.JSX.Element {
    const client = useClient();
    const codeRef = useRef<HTMLElement>(null);

    const { data } = useQuery<Changes>({
        queryKey: QueryKeys.changes(packageBase, repository),
        queryFn: () => client.fetchPackageChanges(packageBase, repository),
        enabled: !!packageBase,
    });

    const changesText = data?.changes ?? "";

    useEffect(() => {
        if (codeRef.current) {
            codeRef.current.innerHTML = hljs.highlight(changesText, { language: "diff" }).value;
        }
    }, [changesText]);

    return <Box sx={{ mt: 1 }}>
        <CodeBlock codeRef={codeRef} className="language-diff" getText={() => changesText} height={400} />
    </Box>;
}
