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 { useForm } from "@tanstack/react-form";
import axios from "axios";
import { format } from "date-fns";
import { useState } from "react";
import { toast } from "sonner";

export default function ExportInventoryData() {
    const [open, setOpen] = useState(false);
    const [saving, setSaving] = useState(false);

    const form = useForm({
        defaultValues: {
            age: "",
        },
        onSubmit: async ({ value }) => {
            setSaving(true);
            try {
                const res = await axios.get(
                    `/api/logistics/getcyclecount?age=${value.age}`,
                    {
                        responseType: "blob",
                    }
                );

                const blob = new Blob([res.data], {
                    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                });

                const link = document.createElement("a");
                link.href = window.URL.createObjectURL(blob);
                link.download = `CycleCount-${format(new Date(Date.now()), "M-d-yyyy")}.xlsx`; // You can make this dynamic
                document.body.appendChild(link);
                link.click();

                // Clean up
                document.body.removeChild(link);
                window.URL.revokeObjectURL(link.href);
                toast.success(`File Downloaded`);
                setSaving(false);
                setOpen(false);
                form.reset();
            } catch (error) {
                console.log(error);
                console.log(`There was an error getting cycle counts.`);
            }
        },
    });

    return (
        <div>
            <Dialog
                open={open}
                onOpenChange={(isOpen) => {
                    if (!open) {
                        form.reset();
                    }
                    setOpen(isOpen);
                    // toast.message("Model was something", {
                    //     description: isOpen ? "Modal is open" : "Modal is closed",
                    // });
                }}
            >
                <DialogTrigger asChild>
                    <Button variant="outline">Export Inventory Check</Button>
                </DialogTrigger>
                <DialogContent className="sm:max-w-[425px]">
                    <DialogHeader>
                        <DialogTitle>Export Inventory lane check</DialogTitle>
                        <DialogDescription>
                            Exports all lanes based on the age you enter, except
                            empty lanes.
                        </DialogDescription>
                    </DialogHeader>
                    <form
                        onSubmit={(e) => {
                            e.preventDefault();
                            e.stopPropagation();
                        }}
                    >
                        <div>
                            <>
                                <form.Field
                                    name="age"
                                    // validators={{
                                    //     // We can choose between form-wide and field-specific validators
                                    //     onChange: ({ value }) =>
                                    //         value.length > 3
                                    //             ? undefined
                                    //             : "Username must be longer than 3 letters",
                                    // }}
                                    children={(field) => {
                                        return (
                                            <div className="m-2 min-w-48 max-w-96 p-2 flex flex-row">
                                                <Label htmlFor="active">
                                                    Age
                                                </Label>
                                                <Input
                                                    className="ml-2"
                                                    name={field.name}
                                                    onBlur={field.handleBlur}
                                                    type="number"
                                                    onChange={(e) =>
                                                        field.handleChange(
                                                            e.target.value
                                                        )
                                                    }
                                                />
                                            </div>
                                        );
                                    }}
                                />
                            </>
                        </div>

                        <DialogFooter>
                            <div className="flex justify-end mt-2">
                                <Button onClick={() => setOpen(false)}>
                                    Close
                                </Button>
                                <Button
                                    type="submit"
                                    disabled={saving}
                                    onClick={form.handleSubmit}
                                >
                                    {saving ? (
                                        <>
                                            <span>Saving....</span>
                                        </>
                                    ) : (
                                        <span>Save setting</span>
                                    )}
                                </Button>
                            </div>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>
        </div>
    );
}
