"use client"

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

import {
    Form,
} from "@/components/ui/form"
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from "@/components/ui/card"
import { 
    Tabs, 
    TabsContent, 
    TabsList, 
    TabsTrigger 
} from "@/components/ui/tabs"
import { Button } from '@/components/ui/button'
import { AlertCircleIcon, ArrowLeft, Save } from 'lucide-react'
import MainSection from './main-section'
import AmenitiesSection from './amenities-section'
import AdditionalSection from './additional-section'
import Link from 'next/link'
import { addVilla, updateVilla } from '@/actions/ttd'
import { toast } from 'sonner'
import { useRouter } from 'next/navigation'
import GallerySection from './gallery-section'

const ACCEPTED_IMAGE_TYPES = ["image/jpeg", "image/jpg", "image/png", "image/webp"];

const formSchema = z.object({
    area: z.string().min(1,"Area cannot empty."),
    villa: z.string().min(1,"Villa cannot empty."),
    propertyId: z.string().min(1,"Villa cannot empty."),
    roomId: z.string().min(1,"Villa cannot empty."),
    name: z.string().min(1,"Villa cannot empty."),
    description: z.string().min(1,"Description cannot empty."),
    offerId: z.string().min(1,"Offer Id cannot empty."),
    image: typeof window !== "undefined" 
    ? z
        .union([
            z.instanceof(File).nullable().refine(
                (file) => file == null || ACCEPTED_IMAGE_TYPES.includes(file.type),
                { message: "Invalid file type" }
            ),
            z.null().optional(),
        ])
    : z.any().nullable(),
    gmaps: z.string().min(1,"Google maps cannot empty."),
    street: z.string().min(1,"Street cannot empty."),
    city: z.string().min(1,"City cannot empty."),
    postCode: z.string().min(1,"Postal Code cannot empty."),
    latitude: z.string().min(1,"Latittude cannot empty."),
    longitude: z.string().min(1,"Longitude cannot empty."),
    bedrooms: z.string().min(1,"Bedrooms cannot empty."),
    bathrooms: z.string().min(1,"Bathroom cannot empty."),
    maxGuest: z.string().min(1,"Max Guest cannot empty."),
    airport: z.boolean().default(false),
    aircond: z.boolean().default(false),
    kitchen: z.boolean().default(false),
    smokeDetector: z.boolean().default(false),
    internet: z.boolean().default(false),
    workdesk: z.boolean().default(false),
    essentials: z.boolean().default(false),
    hairdryer: z.boolean().default(false),
    hangers: z.boolean().default(false),
    shampoo: z.boolean().default(false),
    pool: z.boolean().default(false),
    parking: z.boolean().default(false),
    backyard: z.boolean().default(false),
    tv: z.boolean().default(false),
    gym: z.boolean().default(false),
    spa: z.boolean().default(false),
    titleTag: z.string().min(1,"Meta title cannot empty."),
    metaDesc: z.string().min(1,"Meta description cannot empty."),
    status: z.boolean().default(false),
})

interface Props {
    error: boolean;
    data: any;
    areas: any[];
    villas: any[];
}

const EditForm = ({ error, data, areas, villas } : Props) => {
    const router = useRouter();
    const {setLoading} = useLoading();

    const id = villas.find(v => v.roomId === data.roomId)._id

    const form = useForm({
        resolver: zodResolver(formSchema),
        defaultValues: {
            area: data?.area || "",
            villa: id || "",
            propertyId: String(data?.propertyId || ""),
            roomId: String(data?.roomId || ""),
            name: data?.name || "",
            description: data?.description || "",
            offerId: String(data?.offerId || "1"),
            gmaps: data?.address?.gmaps ||"",
            street: data?.address?.address || "",
            city: data?.address?.city || "",
            postCode: data?.address?.postCode || "80361",
            latitude: String(data?.address?.latitude || "0"),
            longitude: String(data?.address?.longitude ||  "0"),
            bedrooms: String(data?.bedrooms || "0"),
            bathrooms: String(data?.bathrooms || "0"),
            maxGuest: String(data?.maxGuests || "0"),
            airport: data?.amenities?.airport || false,
            aircond: data?.amenities?.aircond || false,
            kitchen: data?.amenities?.kitchen || false,
            smokeDetector: data?.amenities?.smokeDetector || false,
            internet: data?.amenities?.internet || false,
            workdesk: data?.amenities?.workdesk || false,
            essentials: data?.amenities?.essentials || false,
            hairdryer: data?.amenities?.hairdryer || false,
            hangers: data?.amenities?.hangers || false,
            shampoo: data?.amenities?.shampoo || false,
            pool: data?.amenities?.pool || false,
            parking: data?.amenities?.parking || false,
            backyard: data?.amenities?.backyard || false,
            tv: data?.amenities?.tv || false,
            gym: data?.amenities?.gym || false,
            spa: data?.amenities?.spa || false,
            titleTag: data.titleTag || "",
            metaDesc: data.metaDesc || "",
            image: null
        }
    })

    React.useEffect(() => {
        setLoading(false)
    },[areas, villas, data])

    const onSubmit = async (values: z.infer<typeof formSchema>) => {
        setLoading(true);
        const formData = new FormData();

        formData.append('area', values.area);
        formData.append('propertyId', values.propertyId);
        formData.append('roomId', values.roomId);
        formData.append('name', values.name);      
        formData.append('description', values.description);
        formData.append('offerId', values.offerId);
        formData.append('gmaps', values.gmaps);
        formData.append('address', values.street);
        formData.append('city', values.city);
        formData.append('postCode', values.postCode);
        formData.append('latitude', values.latitude);
        formData.append('longitude', values.longitude);
        formData.append('bedrooms', values.bedrooms);
        formData.append('bathrooms', values.bathrooms);
        formData.append('maxGuest', values.maxGuest);
        formData.append('airport', values.airport ? "true" : "false");
        formData.append('aircond', values.aircond ? "true" : "false");
        formData.append('kitchen', values.kitchen ? "true" : "false");
        formData.append('smokeDetector', values.smokeDetector ? "true" : "false");
        formData.append('internet', values.internet ? "true" : "false");
        formData.append('workdesk', values.workdesk ? "true" : "false");
        formData.append('essentials', values.essentials ? "true" : "false");
        formData.append('hairdryer', values.hairdryer ? "true" : "false");
        formData.append('hangers', values.hangers ? "true" : "false");
        formData.append('shampoo', values.shampoo ? "true" : "false");
        formData.append('pool', values.pool ? "true" : "false");
        formData.append('parking', values.parking ? "true" : "false");
        formData.append('backyard', values.backyard ? "true" : "false");
        formData.append('tv', values.tv ? "true" : "false");
        formData.append('gym', values.gym ? "true" : "false");
        formData.append('spa', values.spa ? "true" : "false");
        formData.append('titleTag', values.titleTag);
        formData.append('metaDesc', values.metaDesc);

        if (values?.image) {
            formData.append('image', values.image);
        }

        const response = await updateVilla(data._id, formData)
        if(response.success){
            toast.success(response.message)
            router.push('/dashboard/ttd/villas')
        }else{
            setLoading(false);
            toast.error( response.message);
        }
    }
    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>
                    <div className='flex items-center justify-between'>
                        <div className='space-y-1.5'>
                            <CardTitle>Edit Villa Details</CardTitle>
                            <CardDescription>Modify villa information to keep your Tropical Door listings accurate and up to date.</CardDescription>
                        </div>
                        <div className='flex items-center gap-3'>
                            <Button variant="black" asChild>
                                <Link href="/dashboard/ttd/villas">
                                    <ArrowLeft />
                                    <span>Back to Villas</span>
                                </Link>
                            </Button>
                            <Button variant="blue" onClick={form.handleSubmit(onSubmit)}>
                                <Save />
                                <span>Save</span>
                            </Button>
                        </div>
                    </div>
                </CardHeader>
                <CardContent className='space-y-6'>
                    <Tabs defaultValue="main" className="w-full gap-6">
                        <TabsList className='w-full bg-gundam-blue'>
                            <TabsTrigger value="main" className='data-[state=inactive]:text-white'>Main</TabsTrigger>
                            <TabsTrigger value="amenities" className='data-[state=inactive]:text-white'>Amenities</TabsTrigger>
                            <TabsTrigger value="gallery" className='data-[state=inactive]:text-white'>Gallery</TabsTrigger>
                            <TabsTrigger value="additional" className='data-[state=inactive]:text-white'>Additional</TabsTrigger>
                        </TabsList>
                        <Form {...form}>
                            <form>
                                <TabsContent value="main">
                                    <MainSection 
                                        data={data}
                                        form={form}
                                        areas={areas}
                                        villas={villas}
                                    />
                                </TabsContent>
                                <TabsContent value="amenities">
                                    <AmenitiesSection 
                                        form={form}
                                    />
                                </TabsContent>
                                <TabsContent value="gallery">
                                    <GallerySection 
                                        data={data}
                                    />
                                </TabsContent>
                                <TabsContent value="additional">
                                    <AdditionalSection 
                                        form={form}
                                        areas={areas}
                                    />
                                </TabsContent>
                            </form>
                        </Form>
                    </Tabs>
                </CardContent>
            </Card>
        </div>
    )
}

export default EditForm