"use client";
import Layout from "@/components/layout/Layout";
import { Flat } from "@alptugidin/react-circular-progress-bar";
import Link from "next/link";
import CounterUpDirectly from "@/components/elements/CounterUpDirectly";
import About2 from "@/components/sections/About2";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";

export default function Report() {
    const [reportData, setReportData] = useState(null);
    const [reportResult, setReportResult] = useState(null);
    const router = useRouter();

    useEffect(() => {
        const storedData = sessionStorage.getItem("reportData");
        const storedResult = sessionStorage.getItem("reportResult");
        if (storedData) {
            try {
                const parsedData = JSON.parse(storedData);
                setReportData(parsedData);
            } catch (error) {
                console.error("Error parsing JSON from sessionStorage", error);
                setReportData(null);
            }
        } else {
            setReportData(null);
            router.push("/");
        }

        if (storedResult) {
            try {
                const parsedResult = JSON.parse(storedResult);
                setReportResult(parsedResult);
            } catch (error) {
                console.error("Error parsing JSON from sessionStorage", error);
                setReportResult(null);
            }
        } else {
            setReportResult(null);
            router.push("/");
        }
    }, []);

    let domainAuthority = reportResult?.domainAuthority;
    let spamScore = reportResult?.spamScore;
    let authority = reportResult?.rankingKeywords;

    let backlinks = reportResult?.backlinksTotal;
    let backlinksSuffix = "";
    if (backlinks > 1000 && backlinks < 1000000) {
        backlinksSuffix = "K";
        backlinks = backlinks / 1000;
    } else if (backlinks > 1000000) {
        backlinksSuffix = "M";
        backlinks = backlinks / 1000000;
    }

    const formatCount = (value) => {
        if (value >= 1000000) {
            return (value / 1000000).toFixed(1);
        } else if (value >= 1000) {
            return (value / 1000).toFixed(1);
        }
        return value;
    };

    backlinks = formatCount(backlinks);

    let overallScore;

    if (domainAuthority < 91) {
        overallScore = Math.floor(domainAuthority * 1.1);
    } else {
        overallScore = domainAuthority;
    }

    const averageScore = 74;
    let comparison;

    if (overallScore > averageScore) {
        comparison = "higher";
    } else if (overallScore < averageScore) {
        comparison = "lower";
    } else {
        comparison = "the same";
    }

    return (
        <>
            {reportData && reportResult && (
                <Layout headerStyle={4} footerStyle={3} transparent={false}>
                    <section className="report-area">
                        <div className="container">
                            <div className="report-box">
                                <div className="col">
                                    <div className="header-design">
                                        <img src="/assets/img/images/h2_about_shape01.png" alt="cosmetic" />
                                        <img src="/assets/img/images/h2_about_shape02.png" alt="cosmetic" />
                                    </div>
                                    <div className="row">
                                        <div className="col-xl-2 col-lg-2 col-md-12">
                                            <div className="report-graph-size">
                                                <Flat
                                                    progress={overallScore}
                                                    range={{ from: 0, to: 100 }}
                                                    sign={{ value: "", position: "end" }}
                                                    text={"of 100"}
                                                    showMiniCircle={true}
                                                    showValue={true}
                                                    sx={{
                                                        strokeColor: "#3887fe",
                                                        barWidth: 10,
                                                        bgStrokeColor: "#3887fe",
                                                        bgColor: { value: "#000000", transparency: "20" },
                                                        shape: "full",
                                                        strokeLinecap: "round",
                                                        valueSize: 25,
                                                        valueWeight: "bold",
                                                        valueColor: "#000000",
                                                        valueFamily: "Helvetica",
                                                        textSize: 13,
                                                        textWeight: "normal",
                                                        textColor: "#000000",
                                                        textFamily: "Helvetica",
                                                        loadingTime: 2000,
                                                        valueAnimation: true,
                                                    }}
                                                />
                                            </div>
                                        </div>
                                        <div className="col-xl-10 col-lg-10 col-md-12">
                                            <h1 className="text-black report-text-title">
                                                Site Audit Result for{" "}
                                                <span className="text-primary">{reportResult.websiteName}</span>
                                            </h1>
                                            <Link
                                                className="report-text-title-url"
                                                href={`https://${reportResult.websiteName}`}
                                            >
                                                https://{reportResult.websiteName}
                                            </Link>
                                            <p className="report-text text-black">
                                                <b>{reportResult.websiteName}</b> received an SEO score of{" "}
                                                <b>{overallScore}</b> out of <b>100</b>, which is <b>{comparison} </b>
                                                than the average score of <b>{averageScore}</b>. Our preliminary
                                                analysis has identified{" "}
                                                <b>
                                                    {reportResult.errorIssueCount + reportResult.importantIssueCount}{" "}
                                                    Crucial Issues
                                                </b>{" "}
                                                that should be addressed in order to improve your website's search
                                                visibility.
                                            </p>
                                            <div className="report-button-group">
                                                <Link className="btn report-button" href="#domain">
                                                    Domain Overview
                                                </Link>
                                                <Link className="btn report-button" href="#issue">
                                                    Errors - {reportResult.errorIssueCount}
                                                </Link>
                                                <Link className="btn report-button" href="#issue">
                                                    Warnings - {reportResult.importantIssueCount}
                                                </Link>
                                                <Link className="btn report-button" href="#potentials">
                                                    Growth Potentials
                                                </Link>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="container" id="domain">
                            <div className="row justify-content-center">
                                <div className="col">
                                    <div className="report-box">
                                        <div className="col">
                                            <h1 className="text-black report-text-title">Domain Overview</h1>
                                            <div className="row domain-overview-group text-center">
                                                <div className="col-lg-3 col-md-6">
                                                    <div className="domain-overview-item">
                                                        <h4>Domain Authority</h4>
                                                        <h1>
                                                            <CounterUpDirectly count={domainAuthority} />
                                                        </h1>
                                                    </div>
                                                </div>
                                                <div className="col-lg-3 col-md-6">
                                                    <div className="domain-overview-item">
                                                        <h4>Backlinks</h4>
                                                        <h1 className="count">
                                                            <CounterUpDirectly count={backlinks} />
                                                            {backlinksSuffix}
                                                        </h1>
                                                    </div>
                                                </div>
                                                <div className="col-lg-3 col-md-6">
                                                    <div className="domain-overview-item">
                                                        <h4>Page Authority</h4>
                                                        <h1>
                                                            <CounterUpDirectly count={authority} />
                                                        </h1>
                                                    </div>
                                                </div>
                                                <div className="col-lg-3 col-md-6">
                                                    <div className="domain-overview-item">
                                                        <h4>Spam Score</h4>
                                                        <h1>
                                                            <CounterUpDirectly count={spamScore} />%
                                                        </h1>
                                                    </div>
                                                </div>
                                            </div>
                                            {61 <= spamScore ? (
                                                <p className="report-text text-black">
                                                    A domain with a <b>bad spam score</b> is likely flagged in multiple
                                                    spam databases and may have a history of sending spammy or unwanted
                                                    emails. This score indicates a high risk of being{" "}
                                                    <b>blocked or filtered by email providers</b>, impacting email
                                                    deliverability significantly. It's crucial to
                                                    <b>investigate and address the reasons behind the bad score</b>,
                                                    such as cleaning email lists, avoiding spammy practices, and
                                                    improving overall domain reputation.
                                                </p>
                                            ) : 31 <= spamScore >= 61 ? (
                                                <p className="report-text text-black">
                                                    A domain with this spam score rate may have
                                                    <b>a moderate presence in spam databases</b> or could occasionally
                                                    send emails that some recipients may mark as spam. This score
                                                    doesn't necessarily indicate malicious intent but suggests that
                                                    there may be
                                                    <b>some instances where email deliverability could be affected</b>.
                                                    It's advisable to
                                                    <b>monitor and ensure best practices</b> to maintain or improve the
                                                    score over time.
                                                </p>
                                            ) : (
                                                <p className="report-text text-black">
                                                    A domain with a <b>low spam score</b> indicates that it has a
                                                    <b>minimal or negligible presence in spam databases</b>. This
                                                    suggests that the domain has a <b>clean reputation</b>, with little
                                                    to no reported incidents of spam activity. Websites with a good
                                                    score are typically trusted by email providers and less likely to be
                                                    flagged as spam when sending emails.
                                                </p>
                                            )}
                                            <div className="table-responsive">
                                                <table class="table table-striped">
                                                    <thead>
                                                        <tr>
                                                            <th scope="col" className="text-center">
                                                                Most Visited Pages
                                                            </th>
                                                            <th scope="col" className="text-center">
                                                                Visibility
                                                            </th>
                                                            <th scope="col" className="text-center">
                                                                Page Authority
                                                            </th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        {reportResult.mostDomain.map((item, index) => (
                                                            <tr key={index}>
                                                                <th scope="row">
                                                                    {index + 1} -{" "}
                                                                    <Link
                                                                        href={`https://${item.url}`}
                                                                        className="report-domain-url"
                                                                    >
                                                                        {item.url}
                                                                    </Link>
                                                                </th>
                                                                <td className="report-icon-parent text-center">
                                                                    {item.score < 39 ? (
                                                                        <i className="report-icon red fas fa-times" />
                                                                    ) : item.score <= 59 ? (
                                                                        <i className="report-icon yellow fas fa-exclamation" />
                                                                    ) : (
                                                                        <i className="report-icon green fas fa-check" />
                                                                    )}
                                                                </td>
                                                                <td className="text-center">{item.score}</td>
                                                            </tr>
                                                        ))}
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="container" id="issue">
                            <div className="row justify-content-center">
                                <div className="col-lg-6">
                                    <div className="report-box">
                                        <div className="col">
                                            <h1 className="text-black report-text-title">
                                                Errors - {reportResult.errorIssueCount}
                                            </h1>
                                            <p className="report-text text-black">
                                                These are the most significant issues currently
                                                <b> preventing your website from achieving a higher ranking</b> in any
                                                search engine, including Google Search.
                                            </p>
                                            <div className="report-list">
                                                <ul className="list-wrap">
                                                    {reportResult?.errorList.map((error) => (
                                                        <li>
                                                            <i className="report-icon red fas fa-times" />
                                                            {error}
                                                        </li>
                                                    ))}
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div className="col-lg-6">
                                    <div className="report-box">
                                        <div className="col">
                                            <h1 className="text-black report-text-title">
                                                Warnings - {reportResult.importantIssueCount}
                                            </h1>
                                            <p className="report-text text-black">
                                                These are less significant, yet still important issues that should be
                                                addressed and resolved in order to
                                                <b> further enhance your website's Google search visibility.</b>
                                            </p>
                                            <div className="report-list">
                                                <ul className="list-wrap">
                                                    {reportResult?.warningList.map((warning) => (
                                                        <li>
                                                            <i className="report-icon yellow fas fa-exclamation" />
                                                            {warning}
                                                        </li>
                                                    ))}
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="container" id="potentials">
                            <div className="row justify-content-center">
                                <div className="col">
                                    <div className="report-box">
                                        <div className="col">
                                            <h1 className="text-black report-text-title">Growth Potentials</h1>
                                            <p className="report-text text-black">
                                                A domain with a <b>low spam score</b> indicates that it has a{" "}
                                                <b>minimal or negligible presence in spam databases</b>. This suggests
                                                that the domain has a <b>clean reputation</b>, with little to no
                                                reported incidents of spam activity. Websites with a good score are
                                                typically trusted by email providers and less likely to be flagged as
                                                spam when sending emails.
                                            </p>
                                            <div className="table-responsive">
                                                <table class="table table-striped">
                                                    <thead>
                                                        <tr className="text-center">
                                                            <th scope="col">Variables</th>
                                                            <th scope="col">Current Metrics</th>
                                                            <th scope="col">Potentials Outcome</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        {reportResult?.dataPotentials.map((item, index) => (
                                                            <tr key={index}>
                                                                <th scope="row">{item.variable}</th>
                                                                <td className="text-center">{item.current}</td>
                                                                <td className="text-center">{item.potentials}</td>
                                                            </tr>
                                                        ))}
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <About2 />
                    </section>
                </Layout>
            )}
        </>
    );
}
