"use client"

import React from 'react'
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"

import { cn } from "@/lib/utils"
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form"
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from "@/components/ui/card"
import {
    Command,
    CommandEmpty,
    CommandInput,
    CommandItem,
    CommandList,
} from "@/components/ui/command"
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from "@/components/ui/popover"
import { Button } from '@/components/ui/button';
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { toast } from 'sonner'
import { ArrowLeft, ArrowUpDown } from 'lucide-react'
import Link from 'next/link'
import { addProperties } from '@/actions/bmv'
import { useRouter } from 'next/navigation'
import { useLoading } from '@/lib/useLoading'

const formSchema = z.object({
    villa: z.string().min(1,"villa cannot empty."),
    propertyId: z.string().min(1,"propertyId cannot empty."),
    roomId: z.string().min(1,"roomId cannot empty."),
    name: z.string().min(1,"name cannot empty."),
    address: z.string().min(1,"Address cannot empty."),
    city: z.string().min(1,"City cannot empty."),
    latitude: z.string().optional(),
    longitude: z.string().optional(),
    checkInStart: z.string().optional(),
    checkInEnd: z.string().optional(),
    checkOutEnd: z.string().optional(),
})

interface Props {
    villas: any[];
}
const AddVillas = ({villas}: Props) => {
    const router = useRouter();
    const [dropdown, setDropdown] = React.useState(false)
    const { loading, setLoading } = useLoading();

    const form = useForm({
        resolver: zodResolver(formSchema),
        defaultValues: {
            villa: "",
            propertyId: "",
            roomId: "",
            name: "",
            address: "",
            city: "",
            latitude: "",
            longitude: "",
            checkInStart: "14:00",
            checkInEnd: "24:00",
            checkOutEnd: "12:00",
        }
    })

    React.useEffect(() => {
        if(loading){
            setLoading(false)
        }
    },[loading])
    
    const onSubmit = async (values: z.infer<typeof formSchema>) => {
        setLoading(true)
        const body = {
            propertyId: Number(values.propertyId),
            roomId: Number(values.roomId),
            name: values.name,
            address: values.address,
            city: values.city,
            latitude: Number(values.latitude),
            longitude: Number(values.longitude),
            checkInStart: values.checkInStart,
            checkInEnd : values.checkInEnd,
            checkOutEnd : values.checkOutEnd
        }
        const response = await addProperties(body)
        if(response.success){
            toast.success(response.message)
            form.reset();
            router.push("/dashboard/bmv/villas")
        }else{
            toast.error(response.message)
            setLoading(false)
        }
    }
    return (
        <Card>
            <CardHeader>
                <div className='flex items-center justify-between'>
                    <div className='space-y-1.5'>
                        <CardTitle>Add New Property</CardTitle>
                        <CardDescription>Fill in the details below to register a new property in the system.</CardDescription>
                    </div>
                    <Button asChild>
                        <Link href="/dashboard/bmv/villas">
                            <ArrowLeft />
                            <span>Back</span>
                        </Link>
                    </Button>
                </div>
            </CardHeader>
            <CardContent>
                <div className='space-y-6'>
                    <Form {...form}>
                        <form onSubmit={form.handleSubmit(onSubmit)} className='space-y-6'>
                            <div className='grid lg:grid-cols-2 gap-6 lg:max-w-1/2'>

                                <FormField
                                    control={form.control}
                                    name="villa"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel className="max-w-2xs">VILLA</FormLabel>
                                            <Popover open={dropdown} onOpenChange={setDropdown}>
                                                <PopoverTrigger asChild>
                                                    <FormControl>
                                                        <Button
                                                        variant="outline"
                                                        role="combobox"
                                                        className={cn(
                                                            "justify-between",
                                                            !field.value && "text-muted-foreground"
                                                        )}
                                                        >
                                                        {field.value ?
                                                            villas.find(
                                                                    (v: any) => String(v.propertyId) === field.value
                                                                )?.name
                                                                : "Select villas"}
                                                        <ArrowUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                                                        </Button>
                                                    </FormControl>
                                                </PopoverTrigger>
                                                <PopoverContent className="max-w-2xs p-0">
                                                <Command className="gap-3 py-2">
                                                    <CommandInput placeholder="Search villas.."/>
                                                    <CommandEmpty>No villa found.</CommandEmpty>
                                                    <CommandList>
                                                        {villas.map((v: any) => (
                                                            <CommandItem
                                                                key={v.roomId}
                                                                value={v.propertyId}
                                                                onSelect={() => {
                                                                    form.setValue("villa", String(v.propertyId));
                                                                    form.setValue("propertyId", String(v.propertyId));
                                                                    form.setValue("roomId", String(v.roomId));
                                                                    form.setValue("name", v.name);
                                                                    form.setValue("address", v.address);
                                                                    form.setValue("city", v.city);
                                                                    form.setValue("latitude", String(v.latitude));
                                                                    form.setValue("longitude", String(v.longitude));
                                                                    form.setValue("checkInStart", String(v.checkInStart));
                                                                    form.setValue("checkInEnd", String(v.checkInEnd));
                                                                    form.setValue("checkOutEnd", String(v.checkOutEnd));
                                                                    setDropdown(false)
                                                                }}
                                                                className="px-3 rounded-none cursor-pointer"
                                                                >
                                                                {v.name}
                                                            </CommandItem>
                                                        ))}
                                                    </CommandList>
                                                </Command>
                                                </PopoverContent>
                                            </Popover>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                                <FormField
                                    control={form.control}
                                    name="name"
                                    render={({ field }) => (
                                        <FormItem>
                                            <div className='flex items-center gap-2'>
                                                <FormLabel>VILLA NAME</FormLabel>
                                            </div>
                                            <FormControl>
                                                <Input {...field} placeholder="Villa Name"/>
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                                <FormField
                                    control={form.control}
                                    name="roomId"
                                    render={({ field }) => (
                                        <FormItem>
                                            <div className='flex items-center gap-2'>
                                                <FormLabel>ROOM ID</FormLabel>
                                            </div>
                                            <FormControl>
                                                <Input {...field} placeholder="Room ID"/>
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                                <FormField
                                    control={form.control}
                                    name="propertyId"
                                    render={({ field }) => (
                                        <FormItem>
                                            <div className='flex items-center gap-2'>
                                                <FormLabel>PROPERTY ID</FormLabel>
                                            </div>
                                            <FormControl>
                                                <Input {...field} placeholder="Property ID"/>
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                                <FormField
                                    control={form.control}
                                    name="address"
                                    render={({ field }) => (
                                        <FormItem>
                                            <div className='flex items-center gap-2'>
                                                <FormLabel>VILLA ADDRESS</FormLabel>
                                            </div>
                                            <FormControl>
                                                <Textarea {...field} placeholder="Address"/>
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                                <FormField
                                    control={form.control}
                                    name="city"
                                    render={({ field }) => (
                                        <FormItem>
                                            <div className='flex items-center gap-2'>
                                                <FormLabel>VILLA CITY</FormLabel>
                                            </div>
                                            <FormControl>
                                                <Textarea {...field} placeholder="City"/>
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                                <FormField
                                    control={form.control}
                                    name="latitude"
                                    render={({ field }) => (
                                        <FormItem>
                                            <div className='flex items-center gap-2'>
                                                <FormLabel>VILLA LATITUDE</FormLabel>
                                            </div>
                                            <FormControl>
                                                <Input {...field} placeholder="Latitude"/>
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                                <FormField
                                    control={form.control}
                                    name="longitude"
                                    render={({ field }) => (
                                        <FormItem>
                                            <div className='flex items-center gap-2'>
                                                <FormLabel>VILLA LONGITUDE</FormLabel>
                                            </div>
                                            <FormControl>
                                                <Input {...field} placeholder="Longitude"/>
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                                <FormField
                                    control={form.control}
                                    name="checkInStart"
                                    render={({ field }) => (
                                        <FormItem>
                                            <div className='flex items-center gap-2'>
                                                <FormLabel>CHECK IN START</FormLabel>
                                            </div>
                                            <FormControl>
                                                <Input {...field} placeholder="Enter Check-in Start Time"/>
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                                <FormField
                                    control={form.control}
                                    name="checkInEnd"
                                    render={({ field }) => (
                                        <FormItem>
                                            <div className='flex items-center gap-2'>
                                                <FormLabel>CHECK IN END</FormLabel>
                                            </div>
                                            <FormControl>
                                                <Input {...field} placeholder="Enter Check-in End Time"/>
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                                <FormField
                                    control={form.control}
                                    name="checkOutEnd"
                                    render={({ field }) => (
                                        <FormItem>
                                            <div className='flex items-center gap-2'>
                                                <FormLabel>CHECK OUT END</FormLabel>
                                            </div>
                                            <FormControl>
                                                <Input {...field} placeholder="Enter Check-out End Time"/>
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                            </div>
                            <Button type="submit" variant="blue">
                                SAVE
                            </Button>
                        </form>
                    </Form>
                </div>
            </CardContent>
        </Card>
    )
}

export default AddVillas