import { useEffect, useState } from "react";
import NavBar from "../NavBar";
import Container from "../Container";
import { FaCopy } from "react-icons/fa";
import { toast } from "sonner";

const { protocol, hostname, port } = window.location;

let fullHost = `${protocol}//${hostname}`;
if (
    (protocol === "http:" && port !== "80") ||
    (protocol === "https:" && port !== "443" && port !== "")
) {
    fullHost += `:${port}`;
}

const handleCopy = (text) => {
    navigator.clipboard.writeText(text);
    toast.success("Copied to clipboard");
};

function API() {
    const [deviceInfo, setDeviceInfo] = useState({
        device_type: "",
        system_id: "",
        security_level: "",
        host: "",
        secret: "",
        device_name: "",
    });

    const [prDeviceInfo, setPrDeviceInfo] = useState({
        security_level: "",
        host: "",
        secret: "",
        device_name: "",
    });

    useEffect(() => {
        // Fetch Widevine info
        fetch("/remotecdm/widevine/deviceinfo")
            .then((response) => response.json())
            .then((data) => {
                setDeviceInfo({
                    device_type: data.device_type,
                    system_id: data.system_id,
                    security_level: data.security_level,
                    host: data.host,
                    secret: data.secret,
                    device_name: data.device_name,
                });
            })
            .catch((error) => console.error("Error fetching Widevine info:", error));

        // Fetch PlayReady info
        fetch("/remotecdm/playready/deviceinfo")
            .then((response) => response.json())
            .then((data) => {
                setPrDeviceInfo({
                    security_level: data.security_level,
                    host: data.host,
                    secret: data.secret,
                    device_name: data.device_name,
                });
            })
            .catch((error) => console.error("Error fetching PlayReady info:", error));
    }, []);

    useEffect(() => {
        document.title = "API | CDRM-Project";
    }, []);

    const decryptRequest = `import requests

print(requests.post(
    url='${fullHost}/api/decrypt',
    headers={
        'Content-Type': 'application/json',
    },
    json={
        'pssh': 'AAAAW3Bzc2gAAAAA7e+LqXnWSs6jyCfc1R0h7QAAADsIARIQ62dqu8s0Xpa7z2FmMPGj2hoNd2lkZXZpbmVfdGVzdCIQZmtqM2xqYVNkZmFsa3IzaioCSEQyAA==',
        'licurl': 'https://cwip-shaka-proxy.appspot.com/no_auth',
        'headers': str({
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:134.0) Gecko/20100101 Firefox/134.0',
            'Accept': '*/*',
            'Accept-Language': 'en-US,en;q=0.5',
        })
    }
).json()['message'])`;

    const searchRequest = `import requests

print(requests.post(
    url='${fullHost}/api/cache/search',
    json={
        'input': 'AAAAW3Bzc2gAAAAA7e+LqXnWSs6jyCfc1R0h7QAAADsIARIQ62dqu8s0Xpa7z2FmMPGj2hoNd2lkZXZpbmVfdGVzdCIQZmtqM2xqYVNkZmFsa3IzaioCSEQyAA=='
    }
).json())`;

    return (
        <>
            <NavBar />
            <Container>
                <div className="mx-auto flex w-full max-w-2xl flex-col justify-center py-8">
                    <div className="join join-vertical w-full max-w-2xl">
                        <div
                            tabIndex={0}
                            className="collapse-arrow join-item collapse border border-gray-600"
                        >
                            <input type="checkbox" defaultChecked />
                            <div className="collapse-title text-lg font-semibold">
                                Sending a decryption request
                            </div>
                            <div className="collapse-content text-slate-300">
                                <pre className="my-4 overflow-auto rounded-lg font-mono break-all whitespace-pre-wrap">
                                    {decryptRequest}
                                </pre>
                                <div className="flex justify-end">
                                    <button
                                        type="button"
                                        className="btn btn-primary"
                                        onClick={() => handleCopy(decryptRequest)}
                                    >
                                        <FaCopy /> Copy
                                    </button>
                                </div>
                            </div>
                        </div>

                        <div
                            tabIndex={0}
                            className="collapse-arrow join-item collapse border border-gray-600"
                        >
                            <input type="checkbox" defaultChecked />
                            <div className="collapse-title text-lg font-semibold">
                                Sending a search request
                            </div>
                            <div className="collapse-content text-slate-300">
                                <pre className="my-4 overflow-auto rounded-lg font-mono break-all whitespace-pre-wrap">
                                    {searchRequest}
                                </pre>
                                <div className="flex justify-end">
                                    <button
                                        type="button"
                                        className="btn btn-primary"
                                        onClick={() => handleCopy(searchRequest)}
                                    >
                                        <FaCopy /> Copy
                                    </button>
                                </div>
                            </div>
                        </div>

                        <div
                            tabIndex={0}
                            className="collapse-arrow join-item collapse border border-gray-600"
                        >
                            <input type="checkbox" defaultChecked />
                            <div className="collapse-title text-lg font-semibold">
                                PyWidevine RemoteCDM info
                            </div>
                            <div className="collapse-content text-slate-300">
                                <p>
                                    <strong>Device Type:</strong>{" "}
                                    <span className="font-mono">
                                        {deviceInfo.device_type || "N/A"}
                                    </span>
                                </p>
                                <p>
                                    <strong>System ID:</strong>{" "}
                                    <span className="font-mono">
                                        {deviceInfo.system_id || "N/A"}
                                    </span>
                                </p>
                                <p>
                                    <strong>Security Level:</strong>{" "}
                                    <span className="font-mono">
                                        {deviceInfo.security_level || "N/A"}
                                    </span>
                                </p>
                                <p>
                                    <strong>Host:</strong>{" "}
                                    <span className="font-mono">{fullHost}/remotecdm/widevine</span>
                                </p>
                                <p>
                                    <strong>Secret:</strong>{" "}
                                    <span className="font-mono">{deviceInfo.secret || "N/A"}</span>
                                </p>
                                <p>
                                    <strong>Device Name:</strong>{" "}
                                    <span className="font-mono">
                                        {deviceInfo.device_name || "N/A"}
                                    </span>
                                </p>
                            </div>
                        </div>

                        <div
                            tabIndex={0}
                            className="collapse-arrow join-item collapse border border-gray-600"
                        >
                            <input type="checkbox" defaultChecked />
                            <div className="collapse-title text-lg font-semibold">
                                PyPlayready RemoteCDM info
                            </div>
                            <div className="collapse-content text-slate-300">
                                <p>
                                    <strong>Security Level:</strong>{" "}
                                    <span className="font-mono">
                                        {prDeviceInfo.security_level || "N/A"}
                                    </span>
                                </p>
                                <p>
                                    <strong>Host:</strong>{" "}
                                    <span className="font-mono">
                                        {fullHost}/remotecdm/playready
                                    </span>
                                </p>
                                <p>
                                    <strong>Secret:</strong>{" "}
                                    <span className="font-mono">
                                        {prDeviceInfo.secret || "N/A"}
                                    </span>
                                </p>
                                <p>
                                    <strong>Device Name:</strong>{" "}
                                    <span className="font-mono">
                                        {prDeviceInfo.device_name || "N/A"}
                                    </span>
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </Container>
        </>
    );
}

export default API;
