import { Button } from "@/components/ui/button";
import {
    Dialog,
    DialogClose,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from "@/components/ui/dialog";

import { useAppForm } from "@/utils/formStuff";
import { getMachineConnected } from "@/utils/querys/logistics/machineConnected";
import { getMachineNotConnected } from "@/utils/querys/logistics/notConnected";
import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import { useState } from "react";
import { toast } from "sonner";

export function AttachSilo(props: any) {
    const [open, setOpen] = useState(false);
    const { data, isError, isLoading, refetch } = useQuery(
        getMachineNotConnected({
            siloID: props.silo.LocationID,
            connectionType: "detached",
        })
    );
    const { refetch: attached } = useQuery(
        getMachineConnected({
            siloID: props.silo.LocationID,
            connectionType: "connected",
        })
    );

    const form = useAppForm({
        defaultValues: {
            laneId: props.silo.LocationID,
            productionLotId: "",
            machineId: "",
        },
        onSubmit: async ({ value }) => {
            try {
                const res = await axios.post(
                    "/api/logistics/attachsilo",
                    value
                );

                if (res.data.success) {
                    toast.success(res.data.message);
                    refetch();
                    attached();
                    form.reset();
                    setOpen(!open);
                } else {
                    console.log(res.data);
                    toast.error(res.data.message);
                    refetch();
                    form.reset();
                    setOpen(!open);
                }
            } catch (error) {
                console.log(error);
                toast.error(
                    "There was an error attaching the silo please try again, if persist please enter a helpdesk ticket."
                );
            }
        },
    });

    if (isError)
        return (
            <div>
                <p>There was an error loading data</p>
            </div>
        );

    if (isLoading)
        return (
            <div>
                <p>Loading....</p>
            </div>
        );

    // convert the array that comes over to label and value
    const tranMachine = data.map((i: any) => ({
        value: i.machineId.toString(),
        label: i.name,
    }));

    return (
        <Dialog open={open}>
            <DialogTrigger asChild>
                <Button variant="outline" onClick={() => setOpen(!open)}>
                    Attach Silo
                </Button>
            </DialogTrigger>

            <DialogContent className="sm:max-w-[425px]">
                <form
                    onSubmit={(e) => {
                        e.preventDefault();
                        form.handleSubmit();
                    }}
                >
                    <DialogHeader>
                        <DialogTitle>
                            Attach silo for: {props.silo.Description}
                        </DialogTitle>
                        <DialogDescription>
                            Enter the new lotnumber, select the machine you
                            would like to attach.
                        </DialogDescription>
                    </DialogHeader>
                    <div>
                        <p className="text-sm">
                            NOTE: If the machine you are trying to attach is not
                            showing in the drop down this means it is already
                            attached to this silo.
                        </p>
                    </div>
                    <div className="mt-3">
                        <form.AppField
                            name="productionLotId"
                            children={(field) => (
                                <field.InputField
                                    label="Lot Number"
                                    inputType="number"
                                    required={true}
                                />
                            )}
                        />
                    </div>
                    <div className="mt-2">
                        <form.AppField
                            name="machineId"
                            children={(field) => (
                                <field.SelectField
                                    label="Select Machine"
                                    options={tranMachine}
                                />
                            )}
                        />
                    </div>

                    <DialogFooter className="mt-2">
                        <DialogClose asChild>
                            <Button
                                variant="outline"
                                onClick={() => setOpen(!open)}
                            >
                                Cancel
                            </Button>
                        </DialogClose>
                        <form.AppForm>
                            <form.SubmitButton>Attach</form.SubmitButton>
                        </form.AppForm>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    );
}
