import { Button } from "@/components/ui/button";
import {
    Dialog,
    DialogContent,
    // DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
    Select,
    SelectContent,
    SelectGroup,
    SelectItem,
    SelectLabel,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { useSettingStore } from "@/lib/store/useSettings";
import axios from "axios";
import { Tag } from "lucide-react";
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { toast } from "sonner";

const printReason = [
    { key: "printerIssue", label: "Printer Related" },
    { key: "missingRfidTag", label: "Missing or incorrect tag" },
    { key: "rfidMissScan", label: "Missed Scan from RFID reader" },
    { key: "strapper", label: "Strapper Error" },
    { key: "manualCheck", label: "20th pallet check" },
    { key: "outOfSync", label: "Labeler Out of Sync" },
];

export default function ManualPrintForm() {
    const token = localStorage.getItem("auth_token");
    const { settings } = useSettingStore();
    const [open, setOpen] = useState(false);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const server = settings.filter((n) => n.name === "server")[0]?.value;
    // const serverPort = settings.filter((n) => n.name === "serverPort")[0]?.value;
    // const serverUrl = `http://${server}:${serverPort}`;

    // what is the dyco set to? rfid or dyco
    const dyco = settings.filter((n) => n.name === "dycoPrint");
    const {
        register,
        handleSubmit,
        //watch,
        formState: { errors },
        reset,
        control,
    } = useForm();

    const handleManualPrintLog = async (logData: any) => {
        // toast.success(`A new label was sent to printer: ${lot.PrinterName} for line ${lot.MachineDescription} `);
        const logdataUrl = `/api/ocp/manuallabellog`;
        setIsSubmitting(true);
        axios
            .post(logdataUrl, logData, {
                headers: { Authorization: `Bearer ${token}` },
            })
            .then((d) => {
                console.log(d);
                if (d.data.success) {
                    toast.success(d.data.message);
                } else {
                    toast.error(d.data.message);
                }
                reset();
                setOpen(false);
                setIsSubmitting(false);
            })
            .catch((e) => {
                if (e.response.status === 500) {
                    toast.error(`Internal Server error please try again.`);
                    setIsSubmitting(false);
                    return { sucess: false };
                }

                if (e.response.status === 401) {
                    //console.log(e.response);
                    toast.error(`You are not authorized to do this.`);
                    setIsSubmitting(false);
                    return { sucess: false };
                }
            });
    };

    const onSubmit = (data: any) => {
        //console.log(data);

        handleManualPrintLog(data);
    };

    const closeForm = () => {
        reset();
        setOpen(false);
    };
    return (
        <Dialog
            open={open}
            onOpenChange={(isOpen) => {
                if (!open) {
                    reset();
                }
                setOpen(isOpen);
                // toast.message("Model was something", {
                //     description: isOpen ? "Modal is open" : "Modal is closed",
                // });
            }}
        >
            <DialogTrigger asChild>
                <Button variant="outline" size="icon">
                    <Tag className="h-[16px] w-[16px]" />
                </Button>
            </DialogTrigger>
            <DialogContent className="sm:max-w-[425px]">
                <DialogHeader>
                    <DialogTitle>Manual Print form</DialogTitle>
                    {/* <DialogDescription>
                        Make changes to your profile here. Click save when
                        you're done.
                    </DialogDescription> */}
                </DialogHeader>
                <form onSubmit={handleSubmit(onSubmit)}>
                    <p>
                        To manually print a label you must complete all the
                        required fields below.
                        <br />
                        If you clicked this in error just click close
                    </p>
                    <hr className="mt-2 mb-2" />
                    {server == "usday1vms006" ? (
                        <Controller
                            control={control}
                            name="printReason"
                            defaultValue={""}
                            render={({
                                field: { onChange },
                                fieldState: {},
                                //formState,
                            }) => (
                                <Select onValueChange={onChange}>
                                    <SelectTrigger className="w-[180px]">
                                        <SelectValue placeholder="Select Reason" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectGroup>
                                            <SelectLabel>
                                                Print Reasons
                                            </SelectLabel>
                                            {printReason.map(
                                                (printReason: any) => (
                                                    <SelectItem
                                                        value={printReason.key}
                                                    >
                                                        {printReason.label}
                                                    </SelectItem>
                                                )
                                            )}
                                        </SelectGroup>
                                    </SelectContent>
                                </Select>
                            )}
                        />
                    ) : (
                        <div className="m-2">
                            <Label htmlFor="printRason" className="m-1">
                                Why are you manually printing?
                            </Label>
                            <Input
                                type="text"
                                className={
                                    errors.printReason ? "border-red-500" : ""
                                }
                                aria-invalid={!!errors.printReason}
                                {...register("printReason", {
                                    required: true,
                                    minLength: {
                                        value: 5,
                                        message:
                                            "To short of a reason please try again!",
                                    },
                                })}
                            />
                        </div>
                    )}
                    <div className="m-2">
                        <Label htmlFor="line" className="m-1">
                            "What is the line number you are printing?"
                        </Label>
                        <Input
                            //variant="underlined"
                            type="number"
                            className={errors.line ? "border-red-500" : ""}
                            aria-invalid={!!errors.line}
                            {...register("line", { required: true })}
                        />
                    </div>

                    <div className="m-2">
                        <Label htmlFor="initials" className="m-1">
                            Enter intials
                        </Label>
                        <Input
                            //variant="underlined"
                            //label="Enter intials"

                            {...register("initials", { required: true })}
                        />
                    </div>
                    <hr />
                    {dyco[0].value === "0" && (
                        <div>
                            <p>Enter the missing tag number.</p>
                            <hr />
                            <Label htmlFor="rfidTag" className="m-1">
                                Enter the tag number only Example
                                ALPLA000002541. only enter 2541
                            </Label>
                            <Input
                                type="text"
                                className={
                                    errors.printReason ? "border-red-500" : ""
                                }
                                aria-invalid={!!errors.printReason}
                                {...register("rfidTag", {
                                    required: true,
                                    minLength: {
                                        value: 1,
                                        message: "Tag number is to short!",
                                    },
                                })}
                            />
                        </div>
                    )}
                    <div className="m-2">
                        <Textarea
                            //label="Comments"
                            placeholder="add more info as needed."
                            {...register("additionalComments")}
                        />
                    </div>

                    <DialogFooter>
                        <div className="mt-3">
                            <Button
                                color="danger"
                                variant="default"
                                onClick={closeForm}
                            >
                                Close
                            </Button>
                            <Button
                                color="primary"
                                type="submit"
                                disabled={isSubmitting}
                            >
                                Print
                            </Button>
                        </div>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    );
}
