"use client"

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

import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from "@/components/ui/card"
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form"
import { Button } from '@/components/ui/button';
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Separator } from "@/components/ui/separator";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { AlertCircleIcon, ArrowLeft } from 'lucide-react';
import { toast } from 'sonner';
import Link from 'next/link';
import { useLoading } from '@/lib/useLoading';
import { useRouter } from 'next/navigation';
import { updateProperties } from '@/actions/bmv';

const timezone = "Asia/Makassar";

const formSchema = z.object({
    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(),
    facebook: z.string().optional(),
    instagram: z.string().optional(),
    website: z.string().optional(),
    bedroom: z.string(),
    bathroom: z.string(),
    guest: z.string(),
    price: z.string().optional(),
    offerId: z.string(),
    gaSecret: z.string().optional(),
    gaMeasurement: z.string().optional(),
    checkInStart: z.string().optional(),
    checkInEnd: z.string().optional(),
    checkOutEnd: z.string().optional(),
})

interface Props {
    error: boolean;
    villa: any;
}
const EditVillas = ({error, villa} : Props) => {
    const router = useRouter();
    const { setLoading } = useLoading();

    const form = useForm({
        resolver: zodResolver(formSchema),
        defaultValues: {
            propertyId: String(villa?.propertyId) || "",
            roomId: String(villa?.roomId) || "",
            name: villa?.name || "",
            facebook: villa?.facebook || "#",
            instagram: villa?.instagram || "#",
            website: villa?.website || "#",
            address: villa?.address || "",
            city: villa?.city || "",
            latitude: String(villa?.latitude) || "0",
            longitude: String(villa?.longitude) || "0",
            guest: String(villa?.guest) || "0",
            bedroom: String(villa?.bedroom) || "0",
            bathroom: String(villa?.bathroom) || "0",
            price: String(villa?.dailyPriceUSD) || "0",
            offerId: String(villa?.offerId) || "1",
            gaSecret: villa?.gaSecret || "",
            gaMeasurement: villa?.gaMeasurement || "",
            checkInStart: villa?.checkInStart || "14:00",
            checkInEnd: villa?.checkInEnd || "24:00",
            checkOutEnd: villa?.checkOutEnd || "12:00",
        }
    })

    const handleSubmit = async (values: z.infer<typeof formSchema>) => {
        setLoading(true)
        const body = {
            name: values.name,
            guest: values.guest,
            bedroom: values.bedroom,
            bathroom: values.bathroom,
            address: values.address,
            city: values.city,
            latitude: values.latitude,
            longitude: values.longitude,
            facebook : values.facebook,
            instagram: values.instagram,
            website: values.website,
            gaSecret : values.gaSecret,
            gaMeasurement: values.gaMeasurement,
            offerId: values.offerId,
            checkInStart: values.checkInStart,
            checkInEnd: values.checkInEnd,
            checkOutEnd: values.checkOutEnd,
        }

        const response = await updateProperties(villa._id, body)
        if(response.success){
            toast.success(response.message)
            form.reset();
            router.push("/dashboard/bmv/villas")
        }else{
            toast.error(response.message)
            setLoading(false);
        }
    }
    return (
        <div className='space-y-6'>
            {error && (
                <div className='bg-gundam-red w-full flex items-center py-3 lg:px-14 px-6 gap-6 text-white rounded-lg'>
                    <AlertCircleIcon size={32}/>
                    <div>
                        <p className='font-bold'>Failed</p>
                        <p>Unsuccessfull fetching data for this villa</p>
                    </div>
                </div>
            )}
            <Card>
                <CardHeader className='sr-only'>
                    <CardTitle>Add New Property</CardTitle>
                    <CardDescription>Fill in the details below to register a new property in the system.</CardDescription>
                </CardHeader>
                <CardContent className='space-y-6'>
                    <div className="flex items-center justify-between px-6">
                        <div className='flex items-center gap-6'>
                            <Link href="/dashboard/bmv/villas"><ArrowLeft /></Link>
                            <h2 className="text-lg font-semibold leading-tight text-gray-800 capitalize">
                                Edit {villa?.name || "Villa"}
                            </h2>
                        </div>
                        <div className="flex items-center gap-2">
                            <p className="text-sm text-muted-foreground">Last update <strong>{moment(villa.updatedAt).tz(timezone).fromNow()}</strong> {`( ${moment(villa.updatedAt).tz(timezone).format("DD MMMM YYYY")} )`}</p>
                            <Button variant="blue" onClick={form.handleSubmit(handleSubmit)}>
                                Update
                            </Button>
                        </div>
                    </div>
                    <Separator />
                    <Form {...form}>
                        <form className="space-y-8">
                            <div className='grid md:grid-cols-3 md:divide-x divide-x-0 gap-3 '>
                                <div className='space-y-6 px-6'>
                                    <h3 className="font-bold">General Info</h3>
                                    <Separator />
                                    <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" readOnly disabled/>
                                                </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" readOnly disabled/>
                                                </FormControl>
                                                <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="facebook"
                                        render={({ field }) => (
                                            <FormItem>
                                                <div className='flex items-center gap-2'>
                                                    <FormLabel>Facebook</FormLabel>
                                                </div>
                                                <FormControl>
                                                    <Input {...field} placeholder="Facebook"/>
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                    <FormField
                                        control={form.control}
                                        name="instagram"
                                        render={({ field }) => (
                                            <FormItem>
                                                <div className='flex items-center gap-2'>
                                                    <FormLabel>Instagram</FormLabel>
                                                </div>
                                                <FormControl>
                                                    <Input {...field} placeholder="Instagram"/>
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                    <FormField
                                        control={form.control}
                                        name="website"
                                        render={({ field }) => (
                                            <FormItem>
                                                <div className='flex items-center gap-2'>
                                                    <FormLabel>Website</FormLabel>
                                                </div>
                                                <FormControl>
                                                    <Input {...field} placeholder="Website"/>
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                    <FormField
                                        control={form.control}
                                        name="gaSecret"
                                        render={({ field }) => (
                                            <FormItem>
                                                <div className='flex items-center gap-2'>
                                                    <FormLabel>GA Secret</FormLabel>
                                                </div>
                                                <FormControl>
                                                    <Input {...field} placeholder="GA Secret"/>
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                    <FormField
                                        control={form.control}
                                        name="gaMeasurement"
                                        render={({ field }) => (
                                            <FormItem>
                                                <div className='flex items-center gap-2'>
                                                    <FormLabel>GA Measurement</FormLabel>
                                                </div>
                                                <FormControl>
                                                    <Input {...field} placeholder="GA Measurement"/>
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                </div>
                                <div className='space-y-6 px-6'>
                                    <h3 className="font-bold">Address Info</h3>
                                    <Separator />
                                    <FormField
                                        control={form.control}
                                        name="address"
                                        render={({ field }) => (
                                            <FormItem>
                                                <div className='flex items-center gap-2'>
                                                    <FormLabel>Address</FormLabel>
                                                </div>
                                                <FormControl>
                                                    <Textarea {...field} placeholder="Address"/>
                                                </FormControl>
                                            </FormItem>
                                        )}
                                    />
                                    <FormField
                                        control={form.control}
                                        name="city"
                                        render={({ field }) => (
                                            <FormItem>
                                                <div className='flex items-center gap-2'>
                                                    <FormLabel>City</FormLabel>
                                                </div>
                                                <FormControl>
                                                    <Input {...field} placeholder="City"/>
                                                </FormControl>
                                            </FormItem>
                                        )}
                                    />
                                    <FormField
                                        control={form.control}
                                        name="latitude"
                                        render={({ field }) => (
                                            <FormItem>
                                                <div className='flex items-center gap-2'>
                                                    <FormLabel>Latitude</FormLabel>
                                                </div>
                                                <FormControl>
                                                    <Input {...field} placeholder="Latitude"/>
                                                </FormControl>
                                            </FormItem>
                                        )}
                                    />
                                    <FormField
                                        control={form.control}
                                        name="longitude"
                                        render={({ field }) => (
                                            <FormItem>
                                                <div className='flex items-center gap-2'>
                                                    <FormLabel>Longitude</FormLabel>
                                                </div>
                                                <FormControl>
                                                    <Input {...field} placeholder="Longitude"/>
                                                </FormControl>
                                            </FormItem>
                                        )}
                                    />
                                    
                                </div>
                                <div className='space-y-6 px-6'>
                                    <h3 className="font-bold">Additional Info</h3>
                                    <Separator />
                                    <div className='grid grid-cols-3 gap-6'>
                                        <FormField
                                            control={form.control}
                                            name="guest"
                                            render={({ field }) => (
                                                <FormItem>
                                                    <div className='flex items-center gap-2'>
                                                        <FormLabel>Max Guest</FormLabel>
                                                    </div>
                                                    <FormControl>
                                                        <Input {...field} placeholder="Max Guest"/>
                                                    </FormControl>
                                                </FormItem>
                                            )}
                                        />
                                        <FormField
                                            control={form.control}
                                            name="bedroom"
                                            render={({ field }) => (
                                                <FormItem>
                                                    <div className='flex items-center gap-2'>
                                                        <FormLabel>Bedroom</FormLabel>
                                                    </div>
                                                    <FormControl>
                                                        <Input {...field} placeholder="Bedroom"/>
                                                    </FormControl>
                                                </FormItem>
                                            )}
                                        />
                                        <FormField
                                            control={form.control}
                                            name="bathroom"
                                            render={({ field }) => (
                                                <FormItem>
                                                    <div className='flex items-center gap-2'>
                                                        <FormLabel>Bathroom</FormLabel>
                                                    </div>
                                                    <FormControl>
                                                        <Input {...field} placeholder="Bathroom"/>
                                                    </FormControl>
                                                </FormItem>
                                            )}
                                        />
                                    </div>
                                    <div className='grid grid-cols-2 gap-6'>
                                        <FormField
                                            control={form.control}
                                            name="offerId"
                                            render={({ field }) => (
                                                <FormItem>
                                                    <div className='flex items-center gap-2'>
                                                        <FormLabel>Offer ID</FormLabel>
                                                    </div>
                                                    <FormControl>
                                                        <Input {...field} placeholder="Offer ID"/>
                                                    </FormControl>
                                                </FormItem>
                                            )}
                                        />
                                        <FormField
                                            control={form.control}
                                            name="price"
                                            render={({ field }) => (
                                                <FormItem>
                                                    <div className='flex items-center gap-2'>
                                                        <FormLabel>Price</FormLabel>
                                                    </div>
                                                    <FormControl>
                                                        <Input {...field} placeholder="Price" readOnly disabled/>
                                                    </FormControl>
                                                </FormItem>
                                            )}
                                        />
                                    </div>
                                    <Separator />
                                    <FormField
                                        control={form.control}
                                        name="checkInStart"
                                        render={({ field }) => (
                                            <FormItem>
                                                <div className='flex items-center gap-2'>
                                                    <FormLabel>Check-in Start Time</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 Time</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 Time</FormLabel>
                                                </div>
                                                <FormControl>
                                                    <Input {...field} placeholder="Enter Check-out End Time"/>
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                </div>
                            </div>
                        </form>
                    </Form>
                </CardContent>
            </Card>
        </div>
    )
}

export default EditVillas