import { useEffect, useRef, useState } from "react";
import { readTextFromClipboard } from "../Functions/ParseChallenge";
import NavBar from "../NavBar";
import Container from "../Container";
import { toast } from "sonner";
import { IoInformationCircleOutline } from "react-icons/io5";

function HomePage() {
    const [pssh, setPssh] = useState("");
    const [licurl, setLicurl] = useState("");
    const [proxy, setProxy] = useState("");
    const [headers, setHeaders] = useState("");
    const [cookies, setCookies] = useState("");
    const [data, setData] = useState("");
    const [message, setMessage] = useState("");
    const [isVisible, setIsVisible] = useState(false);
    const [devices, setDevices] = useState([]);
    const [selectedDevice, setSelectedDevice] = useState("default");

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

    const bottomRef = useRef(null);
    const messageRef = useRef(null); // Reference to result container

    const handleReset = () => {
        if (isVisible) {
            setIsVisible(false);
        }
        setPssh("");
        setLicurl("");
        setProxy("");
        setHeaders("");
        setCookies("");
        setData("");
    };

    const handleSubmitButton = (event) => {
        event.preventDefault();

        fetch("/api/decrypt", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                pssh: pssh,
                licurl: licurl,
                proxy: proxy,
                headers: headers,
                cookies: cookies,
                data: data,
                device: selectedDevice, // Include selected device in the request
            }),
        })
            .then((response) => response.json())
            .then((data) => {
                const resultMessage = data["message"].replace(/\n/g, "<br />");
                setMessage(resultMessage);
                setIsVisible(true);
            })
            .catch((error) => {
                console.error("Error during decryption request:", error);
                setMessage(`Error: Unable to process request. Reason: ${error.message}`);
                setIsVisible(true);
            });
    };

    const handleCopy = (event) => {
        event.preventDefault();
        if (messageRef.current) {
            const textToCopy = messageRef.current.innerText; // Grab the plain text (with visual line breaks)
            toast.success("Copied to clipboard");
            navigator.clipboard.writeText(textToCopy).catch((err) => {
                toast.error(`Failed to copy. Reason: ${err.message}`);
                console.error(err);
            });
        }
    };

    const handleFetchPaste = (event) => {
        event.preventDefault();
        readTextFromClipboard()
            .then(() => {
                setPssh(document.getElementById("pssh").value);
                setLicurl(document.getElementById("licurl").value);
                setHeaders(document.getElementById("headers").value);
                setData(document.getElementById("data").value);
            })
            .catch((err) => {
                toast.error(`Failed to paste from fetch. Reason: ${err.message}`);
                console.error("Failed to paste from fetch:", err);
            });
    };

    useEffect(() => {
        if (isVisible && bottomRef.current) {
            bottomRef.current.scrollIntoView({ behavior: "smooth" });
        }
    }, [message, isVisible]);

    useEffect(() => {
        fetch("/login/status", {
            method: "POST",
        })
            .then((res) => res.json())
            .then((statusData) => {
                if (statusData.message === "True") {
                    return fetch("/userinfo", { method: "POST" });
                } else {
                    throw new Error("Not logged in");
                }
            })
            .then((res) => res.json())
            .then((deviceData) => {
                const combinedDevices = [
                    ...deviceData.Widevine_Devices,
                    ...deviceData.Playready_Devices,
                ];

                // Add default devices if logged in
                const allDevices = [
                    "CDRM-Project Public Widevine CDM",
                    "CDRM-Project Public PlayReady CDM",
                    ...combinedDevices,
                ];

                // Set devices and select a device if logged in
                setDevices(allDevices.length > 0 ? allDevices : []);
                setSelectedDevice(allDevices.length > 0 ? allDevices[0] : "default");
            })
            .catch(() => {
                // User isn't logged in, set default device to 'default'
                setDevices([]); // Don't display devices list
                setSelectedDevice("default");
            });
    }, []);

    return (
        <>
            <NavBar />
            <Container>
                <div className="mx-auto flex w-full max-w-2xl flex-col justify-center">
                    <fieldset className="fieldset">
                        <legend className="fieldset-legend text-base">PSSH*</legend>
                        <input
                            type="text"
                            className="input w-full font-mono"
                            placeholder="Enter PSSH here"
                            value={pssh}
                            onChange={(e) => setPssh(e.target.value)}
                            required
                        />
                        <p className="label text-red-500">* Required</p>
                    </fieldset>
                    <fieldset className="fieldset">
                        <legend className="fieldset-legend text-base">License URL*</legend>
                        <input
                            type="text"
                            className="input w-full font-mono"
                            placeholder="Enter License URL here"
                            value={licurl}
                            onChange={(e) => setLicurl(e.target.value)}
                            required
                        />
                        <p className="label text-red-500">* Required</p>
                    </fieldset>
                    <fieldset className="fieldset">
                        <legend className="fieldset-legend text-base">Proxy</legend>
                        <input
                            type="text"
                            className="input w-full font-mono"
                            placeholder="Enter Proxy here (https://example.com:8080)"
                            value={proxy}
                            onChange={(e) => setProxy(e.target.value)}
                        />
                    </fieldset>
                    <fieldset className="fieldset">
                        <legend className="fieldset-legend text-base">
                            Headers*
                            <div
                                className="tooltip"
                                data-tip="You can use https://curlconverter.com/python/ to paste the header values here"
                            >
                                <IoInformationCircleOutline className="h-5 w-5" />
                            </div>
                        </legend>
                        <textarea
                            className="textarea h-48 w-full font-mono"
                            placeholder="Enter headers here (JSON format). E.g. {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'}"
                            value={headers}
                            onChange={(e) => setHeaders(e.target.value)}
                            required
                        />
                        <p className="label text-red-500">* Required</p>
                    </fieldset>
                    <fieldset className="fieldset">
                        <legend className="fieldset-legend text-base">Cookies</legend>
                        <textarea
                            className="textarea h-48 w-full font-mono"
                            placeholder="Enter cookies here (JSON format)"
                            value={cookies}
                            onChange={(e) => setCookies(e.target.value)}
                        />
                    </fieldset>
                    <fieldset className="fieldset">
                        <legend className="fieldset-legend text-base">Data</legend>
                        <textarea
                            className="textarea h-48 w-full font-mono"
                            placeholder="Enter data here (JSON format)"
                            value={data}
                            onChange={(e) => setData(e.target.value)}
                        />
                    </fieldset>
                    {/* Device Selection Dropdown, only show if logged in */}
                    {devices.length > 0 && (
                        <>
                            <fieldset className="fieldset">
                                <legend className="fieldset-legend text-base">Select device</legend>
                                <select
                                    className="select w-full"
                                    value={selectedDevice}
                                    onChange={(e) => setSelectedDevice(e.target.value)}
                                >
                                    {devices.map((device, index) => (
                                        <option key={index} value={device}>
                                            {device}
                                        </option>
                                    ))}
                                </select>
                            </fieldset>
                        </>
                    )}
                    <div className="mx-auto my-4 flex w-full flex-col items-center justify-center gap-2 lg:flex-row">
                        <button
                            type="button"
                            className="btn btn-primary btn-wide"
                            onClick={handleSubmitButton}
                            disabled={pssh === "" || licurl === "" || headers === ""}
                        >
                            Submit
                        </button>
                        <button
                            type="button"
                            className="btn btn-info btn-wide"
                            onClick={handleFetchPaste}
                        >
                            Paste from fetch
                        </button>
                        <button
                            type="button"
                            className="btn btn-error btn-wide"
                            onClick={handleReset}
                        >
                            Reset
                        </button>
                    </div>
                </div>

                {isVisible && (
                    <>
                        <div className="mx-auto my-4 flex w-full max-w-2xl flex-col justify-center">
                            <div className="card bg-base-100 card-lg border border-gray-500 shadow-sm">
                                <div className="card-body">
                                    <h2 className="card-title">Result</h2>
                                    <div className="divider"></div>
                                    <p
                                        className="w-full grow overflow-y-auto font-mono break-words"
                                        ref={messageRef}
                                        dangerouslySetInnerHTML={{ __html: message }}
                                    />
                                    <div ref={bottomRef} />
                                    <div
                                        className="card-actions mt-4 justify-end"
                                        onClick={handleCopy}
                                    >
                                        <button className="btn btn-success">Copy results</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </>
                )}
            </Container>
        </>
    );
}

export default HomePage;
