"use client";
import SubmitButton from "@/app/ui/shared/SubmitButton";
import { Button } from "@/components/ui/button";
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { createProductFeature } from "@/services/create-product-feature";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { deleteProductFeature } from "@/services/delete-product-feature";
import { updateProductFeature } from "@/services/update-product-feature";
import { zodResolver } from "@hookform/resolvers/zod";
import clsx from "clsx";
import { Loader2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import FallbackImage from "../../shared/FallbackImage";

export default function Color({ data, productId }) {
    const color = data && data.options[0];
    const images = data?.images || [];
    const image = images.length > 0 && images[images.length - 1];
    const fileInputRef = useRef(null);


    const t = useTranslations("vendor");
    const error = useTranslations("form-errors");
    const [isPending, setIsPending] = useState(false);
    const [file, setFile] = useState(null);

    const form = useForm({
        resolver: zodResolver(
            z.object({
                quantity: z.string({ errorMap: () => ({ message: error("required") }) }).min(1),
                price: z.string({ errorMap: () => ({ message: error("required") }) }).min(1),
                name: z.string({ errorMap: () => ({ message: error("required") }) }).min(1),
                value: z.string({ errorMap: () => ({ message: error("required") }) }).min(1),
            })
        ),
        defaultValues: {
            name: color?.name || '',
            price: color?.price || '',
            value: color?.title || '',
            quantity: color?.count || '',
            image: '',
        }
    });

    const { formState: { isSubmitting } } = form;

    // Fetch colors data on mount

    function handleFileChange(files) {
        const file = files[0];
        setFile(file);
    }

    async function onSubmit(values) {
        if (color) { // Update color feature
            const formData = new FormData();
            formData.append('name', values.name);
            formData.append('value', values.value);
            formData.append('count', values.quantity);
            formData.append('price', values.price);
            if (file) {
                formData.append('image', file);
            }
            const { message, error } = await updateProductFeature(data.id, formData)
            if (error) {
                toastError(message);
                return;
            }
            toastSuccess(message);
            return;
        } /////

        // Create new color feature 
        const formData = new FormData();
        formData.append('feature[0][type]', 'color');
        formData.append('feature[0][name]', values.name);
        formData.append('feature[0][value]', values.value);
        formData.append('feature[0][quantity]', values.quantity);
        formData.append('feature[0][price]', values.price);
        if (file) {
            formData.append('feature_image', file);
        }

        const { message, error } = await createProductFeature(productId, formData);
        if (error) {
            toastError(message);
            return;
        }
        form.reset();
        setFile(null);
        toastSuccess(message);
    }


    async function deleteFeature() {
        setIsPending(true);
        const { message, error } = await deleteProductFeature(data.id);
        setIsPending(false);
        if (error) {
            toastError(message);
            return;
        }
        toastSuccess(message);
    }

    return (
        <Form {...form}>
            <form
                method="post"
                onSubmit={form.handleSubmit(onSubmit)}
                className="grid grid-cols-2 lg:grid-cols-4 md:w-3/4 gap-4 mt-4 flex-wrap"
            >
                <FormField
                    name="value"
                    control={form.control}
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>{t("color")}</FormLabel>
                            <FormControl>
                                <Input
                                    {...field}
                                    type="color"
                                    className="w-32"
                                />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />
                <FormField
                    name="name"
                    control={form.control}
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>{t("title")}</FormLabel>
                            <FormControl>
                                <Input
                                    {...field}
                                    placeholder={t("title")}
                                />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />
                {/* Added Price */}
                <FormField
                    name="price"
                    control={form.control}
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>{t("addedPrice")}</FormLabel>
                            <FormControl>
                                <Input
                                    type="number"
                                    {...field}
                                    placeholder={t("addedPrice")}
                                />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />
                {/* Available Quantity */}
                <FormField
                    name="quantity"
                    control={form.control}
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>{t("availableQuantity")}</FormLabel>
                            <FormControl>
                                <Input
                                    type="number"
                                    {...field}
                                    placeholder={t("availableQuantity")}
                                />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />
                <Input
                    type="file"
                    ref={fileInputRef}
                    onChange={(e) => handleFileChange(e.target.files)}
                    accept="image/*"
                    className={clsx("w-32 mt-1", { 'hidden': image })}
                />
                {/* File */}
                {image &&
                    <div className="relative">
                        <FallbackImage
                            src={image.url}
                            alt={`product image ${color?.name}`}
                            className="rounded object-cover h-14"
                            width={130}
                            height={20}
                        />
                        <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            className="absolute top-0 right-0 transform translate-x-1/2 -translate-y-1/2 w-6 h-6 p-0 rounded-full"
                            onClick={() => { fileInputRef.current?.click() }}
                        >
                            ↺
                        </Button>
                    </div>
                }
                {/* Submit buttons */}
                {
                    color ?
                        <div className="flex gap-4">
                            <SubmitButton
                                className="bg-amber-500 hover:bg-amber-500/90"
                                isIcon={false}
                                text={t('update')}
                                loading={isSubmitting}
                            />
                            <Button type="button" onClick={deleteFeature} className="bg-red-500 hover:bg-red-500/90">
                                {
                                    isPending ? <Loader2 className="animate-spin" />
                                        :
                                        t('delete')
                                }
                            </Button>
                        </div>
                        :
                        <SubmitButton
                            className="w-28 self-center"
                            isIcon={false}
                            text={t("save")}
                            loading={isSubmitting}
                        />
                }
            </form>
        </Form>
    );
}
