import { useForm } from "@inertiajs/react";
import { useEffect, useState } from "react";
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Spinner } from "@/components/ui/spinner";
import { PenSquare, Save } from "lucide-react";
import { toast } from "sonner";
import { CurrencyType } from "@/types/dashboard/currency";
import InputField from "@/components/core/InputField";

type DataProp = {
    id: number,
    price: string | null,

}


type Props = {
    id: number,
    room_number: string,
    price: string | null,
    currency: string,
    className?: string,
    room?: boolean
};


export default function PriceUpdater({ id, room_number, price, currency, room, className }: Props) {

    const [open, setOpen] = useState(false)

    const { data, setData, post, put, processing, errors } = useForm<DataProp>({
        id: 0,
        price: null
    });

    const submit = () => {
        put(`/dashboard/price-settings/${room ? 'room' : 'category'}/${id}`, {
            onSuccess: () => {
                toast.success("Price was updated.");
                handleClose();
            },
            onError: () => toast.error('Something went wrong'),
        })
    };


    const handleClose = () => {
        setOpen(false);
    };


    useEffect(() => {
        setData({ id, price })
    }, [id, room_number, price])

    return <Dialog open={open} onOpenChange={setOpen}>
        <DialogTrigger asChild>
            <Button variant="ghost" size="sm" className={className}><PenSquare className="w-4 h-4" /> Edit </Button>
        </DialogTrigger>

        <DialogContent>
            <DialogHeader>
                <DialogTitle>Update Room Price ({room_number})</DialogTitle>
                <DialogDescription>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Ab sit voluptatibus modi nulla, aliquid</DialogDescription>
            </DialogHeader>

            <div className="space-y-6">
                <InputField label='Room Price' type="number" value={Number(data.price) || ''} startAddon={currency} onChange={value => setData('price', value)} disabled={processing} error={errors.price} />
            </div>

            <DialogFooter>
                <Button variant="outline" onClick={handleClose}>  Close  </Button>

                <Button onClick={submit} disabled={processing}>
                    {processing ? (<>  <Spinner /> Saving...   </>) : (<>   <Save /> Save   </>)}
                </Button>
            </DialogFooter>
        </DialogContent>
    </Dialog>
}
