"use client"

import React from 'react'
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form"
import { toast } from 'sonner'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { useLoading } from '@/lib/useLoading'
import { editArea } from '@/actions/ttd'

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

const formSchema = z.object({
    name: z.string().min(1,"room cannot empty."),
    description: z.string().min(1,"room cannot empty."),
    titleTag: z.string().min(6 ,"minimum 6 character."),
    metaDesc: z.string().min(6 ,"minimum 6 character."),
    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(),
})

interface Props {
    data: any,
    onAction: () => void,
    onReset: () => void,
}

const EditForm = ({data, onAction, onReset}: Props) => {
    const { setLoading } = useLoading()
    const [image, setImage] = React.useState(data.image ? `https://imagedelivery.net/wO6ihUlg1M7aee1mES2PLg/${data.image}/public` : "")
    const form = useForm({
        resolver: zodResolver(formSchema),
        defaultValues: {
            name: data?.name || "",
            description: data?.description || "",
            titleTag: data?.titleTag || "",
            metaDesc: data?.metaDesc || "",
            image: null,
        }
    })

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

        if (values.image) {
            formData.append('image', values.image);
        }
        formData.append("name", values.name);
        formData.append("description", values.description);
        formData.append("titleTag", values.titleTag);
        formData.append("metaDesc", values.metaDesc);

        const response = await editArea(data._id, formData)
        if(response.success){
            toast.success(response.message)
            form.reset();
            setImage("")
            onReset();
            onAction();
        }else{
            toast.error(response.message)
        }
        setLoading(false)
    }
    return (
        <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className='space-y-6'>
                <FormField
                    control={form.control}
                    name="name"
                    render={({ field }) => (
                        <FormItem>
                            <div className='flex items-center gap-2'>
                                <FormLabel>AREA NAME</FormLabel>
                            </div>
                            <FormControl>
                                <Input {...field} placeholder="Enter area name"/>
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />
                <FormField
                    control={form.control}
                    name="description"
                    render={({ field }) => (
                        <FormItem>
                            <div className='flex items-center gap-2'>
                                <FormLabel>DESCRIPTION</FormLabel>
                            </div>
                            <FormControl>
                                <Textarea {...field} placeholder="Enter description"/>
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />
                <FormField
                    control={form.control}
                    name="titleTag"
                    render={({ field }) => (
                        <FormItem>
                            <div className='flex items-center gap-2'>
                                <FormLabel>TITLE TAG</FormLabel>
                            </div>
                            <FormControl>
                                <Textarea {...field} placeholder="Enter title tag"/>
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />
                <FormField
                    control={form.control}
                    name="metaDesc"
                    render={({ field }) => (
                        <FormItem>
                            <div className='flex items-center gap-2'>
                                <FormLabel>META DESCRIPTION</FormLabel>
                            </div>
                            <FormControl>
                                <Textarea {...field} placeholder="Enter meta description"/>
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />
                <FormField
                    control={form.control}
                    name="image"
                    render={({ field: { value, onChange, ...fieldProps } }) => (
                        <FormItem>
                            <FormLabel>
                                <div className='space-y-2 w-full'>
                                    <div className='flex items-center gap-2'>
                                        <p className='font-medium'>AREA IMAGE</p>
                                    </div>
                                    <Avatar className="w-full h-48 border drop-shadow-lg rounded-lg items-center justify-center">
                                        {image ? (
                                            <AvatarImage src={image} className="object-cover rounded-lg" />
                                        ) : (
                                            <AvatarFallback className="rounded-lg">IMG</AvatarFallback>
                                        )}
                                    </Avatar>
                                </div>
                            </FormLabel>
                            <FormControl>
                                <Input
                                    className="hidden"
                                    {...fieldProps}
                                    placeholder="Picture"
                                    type="file"
                                    accept="image/*, application/pdf"
                                    onChange={(event) => {
                                        const files = event.target.files;
                                        if (files && files.length > 0) {
                                            const displayUrl = URL.createObjectURL(files[0]);
                                            const selectedFile = files[0];
                                            form.setValue("image", selectedFile)
                                            setImage(displayUrl)
                                        }
                                    }}
                                />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />
                <div className='flex items-center justify-between'>
                    <Button 
                        type="button" 
                        variant="red"
                        onClick={() => {
                            form.reset();
                            onReset();
                        }}
                    >
                        Cancel
                    </Button>
                    <Button type="submit" variant="blue">
                        Update
                    </Button>
                </div>
            </form>
        </Form>
    )
}

export default EditForm