import React, { useState, useEffect } from "react";
import { useAtom } from "jotai";
import { CurrentGRNAtom, VoiceAssistAtom, grnsAtom, CurrentRollAtom, TranscribeAtom } from "../Variables";
import { useNavigate } from "react-router";
import RollCard from "../Components/RollCard";

const GRNDetailPage = ({ sidebar }) => {
    const [currentGRN, setCurrentGRN] = useAtom(CurrentGRNAtom);
    const [voiceAssist, setVoiceAssist] = useAtom(VoiceAssistAtom);
    const [currentRoll, setCurrentRoll] = useAtom(CurrentRollAtom);
    const [transcribe, setTranscribe] = useAtom(TranscribeAtom);
    const [currentGRNRolls, setCurrentGRNRolls] = useState([]);
    const [fabricForm, setFabricForm] = useState("");
    const [POWidth, setPOWidth] = useState(0);
    const [PointsUOM, setPointsUOM] = useState("");
    const [Tolarence, setTolarence] = useState(0);
    const navigate = useNavigate();
    useEffect(() => {
        fetch("/api/grnRolls/" + currentGRN?.GRN)
            .then((res) => res.json())
            .then((data) => {
                setCurrentGRNRolls(data["data"]);
                voiceAssist.on(["roll *", "open roll *"], true).then((i, wildcard) => {
                    wildcard = wildcard.replace(/ /g, "");
                    let found = false;
                    for (let index = 0; index < data["data"].length; index++) {
                        if (data["data"][index].name.toLowerCase() == wildcard.toLowerCase()) {
                            setCurrentRoll(data["data"][index]);
                            setTranscribe((prev) => [...prev.slice(0, -1), { msg: "open roll " + wildcard, isCommand: true }]);
                            navigate("/roll");
                            found = true;
                        }
                    }
                    if (!found) {
                        voiceAssist.say("No roll found with that Number");
                    }
                });
            })
            .catch((err) => {
                window.location.href = "/";
            });
    }, [currentGRN]);
    useEffect(() => {
        setFabricForm(currentGRN?.fabricForm);
        setPOWidth(currentGRN?.POWidth);
        setPointsUOM(currentGRN?.PointsUOM);
        setTolarence(currentGRN?.Tolarence);
        voiceAssist.emptyCommands();
        voiceAssist.on(["open *", "grn *", "open grn *"], true).then((i, wildcard) => {
            wildcard = wildcard.replace(/\s/g, "");
            let found = false;
            for (let index = 0; index < grns.length; index++) {
                if (grns[index].GRN.toLowerCase() == wildcard.toLowerCase()) {
                    setCurrentGRN(grns[index]);
                    setTranscribe((prev) => [...prev.slice(0, -1), { msg: "open GRN " + wildcard, isCommand: true }]);
                    navigate("/grn");
                    localStorage.setItem("currentGRN", JSON.stringify(grns[index]));
                    found = true;
                }
            }
            if (!found) {
                voiceAssist.say("No GRN found with that Number");
            }
        });
        voiceAssist.on(["search *"], true).then((i, wildcard) => {
            wildcard = wildcard.replace(/ /g, "");
            setSearch(wildcard);
            setTranscribe((prev) => [...prev.slice(0, -1), { msg: "search " + wildcard, isCommand: true }]);
        });
        voiceAssist.on(["transcribe"]).then((i) => {
            setTranscribe((prev) => [...prev.slice(0, -1), { msg: "transcribe", isCommand: true }]);
            navigate("/transcribe");
        });
        voiceAssist.on(["home", "go to home"]).then((i) => {
            setTranscribe((prev) => [...prev.slice(0, -1), { msg: "home", isCommand: true }]);
            navigate("/");
        });
        voiceAssist.on(["refresh"]).then((i) => {
            window.location.reload();
        });
        voiceAssist.on(["c1 *", "C 1 *", "c 1 *", "C1 *", "c1*", "C 1*", "c 1*", "C1*"], true).then((i, wildcard) => {
            let finalWildcard = "";
            if (wildcard == 1) {
                finalWildcard = "Roll";
            } else {
                finalWildcard = "Than";
            }
            setFabricForm(finalWildcard);
            setTranscribe((prev) => [...prev.slice(0, -1), { msg: "Fabric Form Updated to " + finalWildcard, isCommand: true }]);
        });
        voiceAssist.on(["c2 *", "C 2 *", "c 2 *", "C2 *", "c2*", "C 2*", "c 2*", "C2*"], true).then((i, wildcard) => {
            setPOWidth(wildcard);
            setTranscribe((prev) => [...prev.slice(0, -1), { msg: "PO Width Updated to " + wildcard, isCommand: true }]);
        });
        voiceAssist.on(["c3 *", "C 3 *", "c 3 *", "C3 *", "c3*", "C 3*", "c 3*", "C3*"], true).then((i, wildcard) => {
            let finalWildcard = "";
            if (wildcard == 1) {
                finalWildcard = "YRD";
            } else {
                finalWildcard = "MTR";
            }
            setPointsUOM(finalWildcard);
            setTranscribe((prev) => [...prev.slice(0, -1), { msg: "Points UOM Updated to " + finalWildcard, isCommand: true }]);
        });
        voiceAssist.on(["c4 *", "C 4 *", "c 4 *", "C4 *", "c4*", "C 4*", "c 4*", "C4*"], true).then((i, wildcard) => {
            let finalWildcard = "";
            if (wildcard == 1) {
                finalWildcard = 20;
            } else {
                finalWildcard = 30;
            }
            setTolarence(finalWildcard);
            setTranscribe((prev) => [...prev.slice(0, -1), { msg: "Tolarence Updated to " + finalWildcard, isCommand: true }]);
        });
        voiceAssist.on(["submit GRN", "update GRN", "submit grn", "update grn"]).then((i) => {
            let formData = new FormData();
            formData.append("fabricForm", fabricForm);
            formData.append("POWidth", POWidth);
            formData.append("PointsUOM", PointsUOM);
            formData.append("Tolarence", Tolarence);
            console.log(currentGRN);
            fetch("/api/GRNUpdate/" + currentGRN?.GRN, {
                method: "POST",
                body: formData,
            })
                .then((res) => res.json())
                .then((data) => {
                    if (data["status"] == "success") {
                        setTranscribe((prev) => [...prev.slice(0, -1), { msg: data["msg"], isCommand: true }]);
                        voiceAssist.say(data["msg"]);
                    } else {
                        setTranscribe((prev) => [...prev.slice(0, -1), { msg: data["msg"], isCommand: false }]);
                        voiceAssist.say("GRN Update Failed");
                    }
                })
                .catch((err) => console.error(err));
        });
    }, [voiceAssist]);

    if (currentGRN?.GRN !== "") {
        return (
            <div className="p-10">
                <div className="flex flex-nowrap items-center justify-between">
                    <h1 className="text-2xl font-semibold text-primary-900">GRN : {currentGRN?.GRN}</h1>
                    <h1 className="text-lg  text-primary-900">* Only Fields with Command Code are editable</h1>
                </div>
                <div className={"w-full mt-3 grid-cols-1 md:grid-cols-4 grid overflow-hidden border-2 border-b-0 border-primary-950 rounded-lg " + (sidebar ? "text-xs" : "text-sm")}>
                    <div className="flex item-center justify-between border-b-2  border-primary-950">
                        <p className="bg-gradient-to-r from-primary-200 via-primary-200 to-white font-semibold px-3 py-1 ">GRN#</p>
                        <p className="px-3 py-1 truncate3 bg-white">{currentGRN?.GRN}</p>
                    </div>
                    <div className="flex item-center justify-between border-b-2  border-primary-950 md:border-l-2">
                        <p className="bg-gradient-to-r from-primary-200 via-primary-200 to-white font-semibold px-3 py-1 ">Supplier#</p>
                        <p className="px-3 py-1 truncate3 bg-white">{currentGRN?.supplier}</p>
                    </div>
                    <div className="flex item-center justify-between border-b-2  border-primary-950 md:border-l-2">
                        <p className="bg-gradient-to-r from-primary-200 via-primary-200 to-white font-semibold px-3 py-1 ">Buyer</p>
                        <p className="px-3 py-1 truncate3 bg-white">{currentGRN?.buyer}</p>
                    </div>
                    <div className="flex item-center justify-between border-b-2  border-primary-950 md:border-l-2">
                        <p className="bg-gradient-to-r from-primary-200 via-primary-200 to-white font-semibold px-3 py-1 ">Item#</p>
                        <p className="px-3 py-1 truncate3 bg-white">{currentGRN?.item}</p>
                    </div>
                    <div className="flex item-center justify-between border-b-2  border-primary-950">
                        <p className="bg-gradient-to-r from-primary-200 via-primary-200 to-white font-semibold px-3 py-1 ">Supplier Name</p>
                        <p className="px-3 py-1 truncate3 bg-white">{currentGRN?.supplierName}</p>
                    </div>
                    <div className="flex item-center justify-between border-b-2  border-primary-950 md:border-l-2">
                        <p className="bg-gradient-to-r from-primary-200 via-primary-200 to-white font-semibold px-3 py-1 ">PCH</p>
                        <p className="px-3 py-1 truncate3 bg-white">{currentGRN?.PCH}</p>
                    </div>
                    <div className="flex col-span-2 item-center justify-between border-b-2  border-primary-950 md:border-l-2">
                        <p className="bg-gradient-to-r from-primary-200 via-primary-200 to-white font-semibold px-3 py-1 ">Fabric Description</p>
                        <p className="px-3 py-1 truncate3 bg-white">{currentGRN?.fabricDescription}</p>
                    </div>
                    <div className="flex item-center justify-between border-b-2  border-primary-950">
                        <p className="bg-gradient-to-r from-primary-200 via-primary-200 to-white font-semibold px-3 py-1 ">Quantity</p>
                        <p className="px-3 py-1 truncate3 bg-white">{currentGRN?.quantity}</p>
                    </div>
                    <div className="flex item-center justify-between border-b-2  border-primary-950 md:border-l-2">
                        <p className="bg-gradient-to-r from-primary-200 via-primary-200 to-white font-semibold px-3 py-1 ">Color</p>
                        <p className="px-3 py-1 truncate3 bg-white">{currentGRN?.color}</p>
                    </div>
                    <div className="flex item-center justify-between border-b-2  border-primary-950 md:border-l-2">
                        <p className="bg-gradient-to-r from-primary-200 via-primary-200 to-white font-semibold px-3 py-1 ">Invoice#</p>
                        <p className="px-3 py-1 truncate3 bg-white">{currentGRN?.invoice}</p>
                    </div>
                    <div className="flex item-center justify-between border-b-2  border-primary-950 md:border-l-2">
                        <p className="bg-gradient-to-r from-primary-200 via-primary-200 to-white font-semibold px-3 py-1 whitespace-nowrap">
                            PO Width <span className="bg-primary-800 font-normal text-white p-1 rounded ml-2">(C2)</span>
                        </p>
                        <input
                            className="px-3 py-1 truncate3 focus:bg-primary-100 focus:outline-none"
                            value={POWidth}
                            onChange={(event) => {
                                setPOWidth(event.target.value);
                            }}
                        />
                    </div>
                    <div className="flex item-center justify-between border-b-2  border-primary-950">
                        <p className="bg-gradient-to-r from-primary-200 via-primary-200 to-white font-semibold px-3 py-1 ">Fabric Odour</p>
                        <p className="px-3 py-1 truncate3 bg-white">{currentGRN?.fabricOdour}</p>
                    </div>

                    <div className="flex item-center justify-between border-b-2  border-primary-950 md:border-l-2">
                        <p className="bg-gradient-to-r from-primary-200 via-primary-200 to-white font-semibold px-3 py-1 whitespace-nowrap">
                            Fabric Form <span className="bg-primary-800 font-normal text-white p-1 rounded">(C11/C12)</span>
                        </p>
                        <select
                            onChange={(event) => {
                                setFabricForm(event.target.value);
                            }}
                            value={fabricForm}
                            className="px-3 py-1 truncate3 focus:bg-primary-100 focus:outline-none"
                        >
                            <option value="Roll">Roll</option>
                            <option value="Than">Than</option>
                        </select>
                    </div>
                    <div className="flex item-center justify-between border-b-2  border-primary-950 md:border-l-2">
                        <p className="bg-gradient-to-r from-primary-200 via-primary-200 to-white font-semibold px-3 py-1 ">PO#</p>
                        <p className="px-3 py-1 truncate3 bg-white">{currentGRN?.PO}</p>
                    </div>
                    <div className="flex item-center justify-between border-b-2  border-primary-950 md:border-l-2">
                        <p className="bg-gradient-to-r from-primary-200 via-primary-200 to-white font-semibold px-3 py-1 ">Item Description</p>
                        <p className="px-3 py-1 truncate3 bg-white">{currentGRN?.itemDescription}</p>
                    </div>
                    <div className="flex item-center justify-between border-b-2  border-primary-950">
                        <p className="bg-gradient-to-r from-primary-200 via-primary-200 to-white font-semibold px-3 py-1 whitespace-nowrap">
                            Points UOM <span className="bg-primary-800 font-normal text-white p-1 rounded">(C31/C32)</span>
                        </p>
                        <select
                            onChange={(event) => {
                                setPointsUOM(event.target.value);
                            }}
                            value={PointsUOM}
                            className="px-3 py-1 truncate3 focus:bg-primary-100 focus:outline-none"
                        >
                            <option value="YRD">YRD</option>
                            <option value="MTR">MTR</option>
                        </select>
                    </div>
                    <div className="flex item-center justify-between border-b-2  border-primary-950 md:border-l-2">
                        <p className="bg-gradient-to-r from-primary-200 via-primary-200 to-white font-semibold px-3 py-1 ">Basic UOM</p>
                        <p className="px-3 py-1 truncate3 bg-white">{currentGRN?.basicUOM}</p>
                    </div>
                    <div className="flex item-center justify-between border-b-2  border-primary-950 md:border-l-2">
                        <p className="bg-gradient-to-r from-primary-200 via-primary-200 to-white font-semibold px-3 py-1 ">Warehouse</p>
                        <p className="px-3 py-1 truncate3 bg-white">{currentGRN?.Warehouse}</p>
                    </div>
                    <div className="flex item-center justify-between border-b-2  border-primary-950 md:border-l-2">
                        <p className="bg-gradient-to-r from-primary-200 via-primary-200 to-white font-semibold px-3 py-1 whitespace-nowrap">
                            Tolarence <span className="bg-primary-800 font-normal text-white p-1 rounded">(C41/C42)</span>
                        </p>
                        <select
                            onChange={(event) => {
                                setTolarence(event.target.value);
                            }}
                            value={Tolarence}
                            className="px-3 py-1 truncate3 focus:bg-primary-100 focus:outline-none"
                        >
                            <option value={20}>20</option>
                            <option value={30}>30</option>
                        </select>
                    </div>
                    <div className="flex item-center justify-between border-b-2  border-primary-950">
                        <p className="bg-gradient-to-r from-primary-200 via-primary-200 to-white font-semibold px-3 py-1 ">PO UOM</p>
                        <p className="px-3 py-1 truncate3 bg-white">{currentGRN?.POUOM}</p>
                    </div>

                    <div className="flex item-center justify-between border-b-2  border-primary-950 md:border-l-2">
                        <p className="bg-gradient-to-r from-primary-200 via-primary-200 to-white font-semibold px-3 py-1 ">Conv Factor</p>
                        <p className="px-3 py-1 truncate3 bg-white">{currentGRN?.convFactor}</p>
                    </div>
                    <div className="flex col-span-2 item-center justify-between border-b-2  border-primary-950 md:border-l-2"></div>
                </div>

                <div className="grid grid-cols-2 md:grid-cols-4 mt-5 gap-3">
                    {currentGRNRolls.map((roll, index) => {
                        return <RollCard key={index} roll={roll} />;
                    })}
                </div>
            </div>
        );
    } else {
        useEffect(() => {
            voiceAssist.say("No GRN selected, redirecting to home page", {
                onEnd: () => {
                    navigate("/");
                },
            });
        }, []);
        return (
            <div className="w-full h-full flex items-center justify-center">
                <div className="flex flex-col items-center justify-center gap-5">
                    <svg xmlns="http://www.w3.org/2000/svg" data-name="Layer 1" viewBox="0 0 647.636 632.174" className="w-[50%] h-[50%] opacity-80">
                        <path d="M411.146 142.174h-174.51a15.02 15.02 0 0 0-15 15v387.85l-2 .61-42.81 13.11a8.007 8.007 0 0 1-9.99-5.31l-127.34-415.95a8.003 8.003 0 0 1 5.31-9.99l65.97-20.2 191.25-58.54 65.97-20.2a7.99 7.99 0 0 1 9.99 5.3l32.55 106.32Z" fill="#f2f2f2" />
                        <path d="m449.226 140.174-39.23-128.14a16.994 16.994 0 0 0-21.23-11.28l-92.75 28.39-191.24 58.55-92.75 28.4a17.015 17.015 0 0 0-11.28 21.23l134.08 437.93a17.03 17.03 0 0 0 16.26 12.03 16.8 16.8 0 0 0 4.97-.75l63.58-19.46 2-.62v-2.09l-2 .61-64.17 19.65a15.015 15.015 0 0 1-18.73-9.95L2.666 136.734a14.98 14.98 0 0 1 9.95-18.73l92.75-28.4 191.24-58.54 92.75-28.4a15.2 15.2 0 0 1 4.41-.66 15.015 15.015 0 0 1 14.32 10.61l39.05 127.56.62 2h2.08Z" fill="#3f3d56" />
                        <path d="M122.68 127.82a9.02 9.02 0 0 1-8.61-6.366l-12.88-42.072a9 9 0 0 1 5.97-11.24L283.1 14.278a9.01 9.01 0 0 1 11.24 5.971l12.88 42.072a9.01 9.01 0 0 1-5.97 11.241l-175.94 53.864a9 9 0 0 1-2.63.395" fill="#285c7c" />
                        <circle cx={190.154} cy={24.955} r={20} fill="#285c7c" />
                        <circle cx={190.154} cy={24.955} r={12.665} fill="#fff" />
                        <path d="M602.636 582.174h-338a8.51 8.51 0 0 1-8.5-8.5v-405a8.51 8.51 0 0 1 8.5-8.5h338a8.51 8.51 0 0 1 8.5 8.5v405a8.51 8.51 0 0 1-8.5 8.5" fill="#e6e6e6" />
                        <path d="M447.136 140.174h-210.5a17.024 17.024 0 0 0-17 17v407.8l2-.61v-407.19a15.02 15.02 0 0 1 15-15h211.12Zm183.5 0h-394a17.024 17.024 0 0 0-17 17v458a17.024 17.024 0 0 0 17 17h394a17.024 17.024 0 0 0 17-17v-458a17.024 17.024 0 0 0-17-17m15 475a15.02 15.02 0 0 1-15 15h-394a15.02 15.02 0 0 1-15-15v-458a15.02 15.02 0 0 1 15-15h394a15.02 15.02 0 0 1 15 15Z" fill="#3f3d56" />
                        <path d="M525.636 184.174h-184a9.01 9.01 0 0 1-9-9v-44a9.01 9.01 0 0 1 9-9h184a9.01 9.01 0 0 1 9 9v44a9.01 9.01 0 0 1-9 9" fill="#285c7c" />
                        <circle cx={433.636} cy={105.174} r={20} fill="#285c7c" />
                        <circle cx={433.636} cy={105.174} r={12.182} fill="#fff" />
                    </svg>
                    <p className="text-3xl text-primary-700">No GRN selected, Please select a GRN</p>
                </div>
            </div>
        );
    }
};

export default GRNDetailPage;
