"use client";
import { Button } from "@/components/ui/button";
import React, { useEffect, useRef, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import AuthLayout from "@/components/layout/layout";
import { Icons } from "@/components/icons";
import { ArrowLeft, Plus, Upload } from "lucide-react"
import { Input } from "@/components/ui/input";
import authBanner from "@/assets/images/AuthImages/menu.png";
import { Textarea } from "@/components/ui/textarea";
import apis from "@/utils/apis";
import { useGlobalContext } from "@/context/Provider";

const Login = (props: any) => {
    const searchParams = useSearchParams();
    const category = searchParams.get("category");
    const categoryName = searchParams.get("category_name");
    const restaurantType = searchParams.get("restaurant_type");
    const router = useRouter();
    const { userInfo } = useGlobalContext();
    const [options, setOptions] = useState<any>([
        {
            id: 1,
            name: '',
            type: '',
            // itemPrice: 0,
            itemDescription: '',
            itemImage: '',
            isDefault: true
        }
    ]);
    const { Toast } = useGlobalContext();
    const fileInputRefs = useRef<{ [key: number]: HTMLInputElement | null }>({});

    const isFormValid = () => {
        return options.every((option: any) => {
            return (
                option.type &&
                option.name &&
                option.name.trim().length > 0 &&
                // option.itemPrice && 
                // parseFloat(option.itemPrice) > 0 && 
                option.itemDescription &&
                option.itemDescription.trim().length > 0 &&
                option.itemImage
            );
        });
    };

    const addOption = () => {
        setOptions([
            ...options,
            {
                id: options.length + 1,
                name: '',
                type: '',
                // itemPrice: 0,
                itemDescription: '',
                itemImage: '',
                isDefault: false
            }
        ]);
    };

    useEffect(() => {
        const resId: any = sessionStorage.getItem('resId');
        if (category) {
            getFoodList(resId, category);
        } else {
            const foodItems: any = JSON.parse(localStorage.getItem('category_foods') || '[]');
            if (foodItems?.length > 0) {
                const mappedOptions = foodItems.map((item: any, index: any) => ({
                    id: index + 1,
                    name: item.title,
                    type: item.food_type,
                    // itemPrice: parseFloat(item.price),
                    itemDescription: item.description,
                    itemImage: '',
                    isDefault: index === 0
                }));

                setOptions(mappedOptions);
            }
        }
    }, []);

    const getFoodList = async (restaurantId: any, categoryId: any) => {
        try {
            let apiRes;

            if (restaurantType === 'home-cooked-meal') {
                // For home-cooked-meal, categoryId is actually the food item's _id
                apiRes = await apis.Food.getFoodById(categoryId);

                if (apiRes?.data) {
                    const item = apiRes.data;
                    const mappedOptions = [{
                        id: 1,
                        name: item.name,
                        type: item.food_type,
                        // itemPrice: parseFloat(item.price),
                        itemDescription: item.description,
                        itemImage: item.image?.[0],
                        isDefault: true,
                        food_id: item._id,
                    }];
                    setOptions(mappedOptions);
                    return;
                }
            } else {
                // For regular restaurants, use category_id to get list of foods
                const params = new URLSearchParams({
                    restaurant_id: restaurantId,
                    category_id: categoryId
                });
                apiRes = await apis.FoodList.get(params);

                if (apiRes?.data?.length > 0) {
                    const mappedOptions = apiRes.data.map((item: any, index: any) => ({
                        id: index + 1,
                        name: item.name,
                        type: item.food_type,
                        // itemPrice: parseFloat(item.price),
                        itemDescription: item.description,
                        itemImage: item.image?.[0],
                        isDefault: index === 0,
                        food_id: item._id,
                    }));
                    setOptions(mappedOptions);
                    return;
                }
            }

            // Fallback to localStorage if API calls don't return data
            const foodItems: any = JSON.parse(localStorage.getItem('category_foods') || '[]');
            if (foodItems?.length > 0) {
                const mappedOptions = foodItems.map((item: any, index: any) => ({
                    id: index + 1,
                    name: item.title,
                    type: item.food_type,
                    // itemPrice: parseFloat(item.price),
                    itemDescription: item.description,
                    itemImage: '',
                    isDefault: index === 0
                }));

                setOptions(mappedOptions);
            }
        } catch (error) {
            // Toast.error(error);
            console.error('Error fetching food list:', error);
        }
    }

    const removeOption = (id: any) => {
        setOptions(options.filter((option: any) => option?.id !== id));
    };

    const handleSave = async () => {
        let resId: any = sessionStorage.getItem('resId');

        // Check if restaurant type is home-cooked-meal
        const isHomeCooked = restaurantType === 'home-cooked-meal';

        try {
            let apiRes;

            if (isHomeCooked) {
                // For home-cooked-meal: send each item individually to /food/{id}
                const promises = options.map(async (option: any) => {
                    const singleItemPayload = {
                        ...(category ? { category_id: category } : { category_name: categoryName }),
                        name: option.name,
                        food_type: option.type,
                        // price: parseFloat(option.itemPrice) || 0,
                        description: option.itemDescription,
                        image: option.itemImage,
                    };

                    return await apis.Food.add(singleItemPayload, resId);
                });

                const results = await Promise.all(promises);

                // Store the food item IDs for future reference
                if (results.length > 0 && results[0]?.data?._id) {
                    const foodIds = results.map(result => result.data._id);
                    sessionStorage.setItem('homecooked_food_ids', JSON.stringify(foodIds));
                }

                Toast.success("Food items added successfully!");
            } else {
                // For other restaurant types: send all items as bulk
                const items = options.map((option: any) => ({
                    ...(category ? { category_id: category } : { category_name: categoryName }),
                    name: option.name,
                    food_type: option.type,
                    // price: parseFloat(option.itemPrice) || 0,
                    description: option.itemDescription,
                    image: option.itemImage,
                    _id: option.food_id || null,
                }));

                const payLoad = { items };
                apiRes = await apis.FoodList.addFoods(resId, payLoad);

                Toast.success("Food items added successfully!");
            }
            router.replace('/auth/menu/add-catering');
        } catch (error) {
            Toast.error("Failed to add food items.");
            console.error(error);
        }
    };

    const handleFileSelect = (id: number) => {
        if (fileInputRefs.current[id]) {
            fileInputRefs.current[id]!.click();
        }
    };

    const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>, optionId: number) => {
        const file = event.target.files?.[0];
        if (!file) return;

        const maxFileSize = 5 * 1024 * 1024;
        const allowedTypes = ["image/jpeg", "image/png", "image/jpg"];

        if (!allowedTypes.includes(file.type)) return;
        if (file.size > maxFileSize) return;

        handleUploadImage(file, optionId);
    };

    const handleUploadImage = async (file: File, optionId: number) => {
        try {
            const apiRes = await apis.Common.uploadFile("file", file);
            if (!apiRes?.key) throw new Error("No image key returned");

            setOptions((prev: any) =>
                prev.map((option: any) =>
                    option.id === optionId
                        ? { ...option, itemImage: apiRes.key }
                        : option
                )
            );

            Toast.success("Image uploaded successfully!");
        } catch (error) {
            Toast.error("Failed to upload image.");
        }
    };

    const updateOption = (id: number, field: string, value: any) => {
        const updated = options.map((opt: any) =>
            opt.id === id ? { ...opt, [field]: value } : opt
        );
        setOptions(updated);
    };


    return (
        <>
            <div className="mb-4">
                <Button
                    variant="theme"
                    className="w-15 h-11"
                    onClick={() => router.back()}
                >
                    <ArrowLeft size={18} />
                    Back
                </Button>

            </div>
            <div className="space-y-6">
                <div className="space-y-4">
                    {options.map((option: any, index: number) => (
                        <div key={option.id} className="space-y-4 rounded-xl border border-gray-100 bg-white p-5 shadow-sm">
                            <div className="flex flex-wrap gap-2">
                                {/* Veg */}
                                <Button
                                    type="button"
                                    variant="outline"
                                    className={`rounded-lg border ${option.type === 'veg' ? 'border-green-500 bg-green-50 text-green-700 font-semibold' : 'border-gray-200 hover:bg-gray-50'}`}
                                    onClick={() => updateOption(option.id, 'type', 'veg')}
                                >
                                    <Icons.VegIcon />
                                    <span style={{ color: '#248853' }}>Veg</span>
                                </Button>

                                {/* Non-Veg */}
                                <Button
                                    type="button"
                                    variant="outline"
                                    className={`rounded-lg border ${option.type === 'non_veg' ? 'border-red-500 bg-red-50 text-red-700 font-semibold' : 'border-gray-200 hover:bg-gray-50'}`}
                                    onClick={() => updateOption(option.id, 'type', 'non_veg')}
                                >
                                    <Icons.NonVegIcon />
                                    <span style={{ color: '#BF2A34' }}>Non Veg</span>
                                </Button>

                                {/* Egg */}
                                <Button
                                    type="button"
                                    variant="outline"
                                    className={`rounded-lg border ${option.type === 'egg' ? 'border-[var(--primary-brand)] bg-orange-50 font-semibold' : 'border-gray-200 hover:bg-gray-50'}`}
                                    onClick={() => updateOption(option.id, 'type', 'egg')}
                                >
                                    <Icons.EggIcon />
                                    <span style={{ color: 'var(--primary-brand)' }}>Egg</span>
                                </Button>

                                {/* Jain - only for home-cooked-meal */}
                                {restaurantType === 'home-cooked-meal' && (
                                    <Button
                                        type="button"
                                        variant="outline"
                                        className={`rounded-lg border ${option.type === 'jain' ? 'border-purple-500 bg-purple-50 font-semibold' : 'border-gray-200 hover:bg-gray-50'}`}
                                        onClick={() => updateOption(option.id, 'type', 'jain')}
                                    >
                                        <Icons.JainIcon />
                                        <span style={{ color: '#6B21A8' }}>Jain</span>
                                    </Button>
                                )}
                            </div>

                            <div>
                                <label className="text-xs font-medium text-gray-600 mb-1 block">Item Name</label>
                                <Input
                                    placeholder="e.g. Catering Special Dish"
                                    className="w-full"
                                    value={option.name}
                                    onChange={(e) => updateOption(option.id, 'name', e.target.value)}
                                    maxLength={50}
                                />
                            </div>

                            <div>
                                <label className="text-xs font-medium text-gray-600 mb-1 block">Item Description</label>
                                <Textarea
                                    placeholder="Enter item description..."
                                    value={option.itemDescription}
                                    onChange={(e) => updateOption(option.id, 'itemDescription', e.target.value)}
                                    maxLength={120}
                                    rows={2}
                                    className="resize-none"
                                />
                            </div>

                            {option.itemImage ? (
                                <div className="relative flex h-[85px] items-center justify-center rounded-lg border-2 border-dashed border-gray-300 bg-gray-50/50 p-2">
                                    <img
                                        src={option.itemImage.startsWith('http') ? option.itemImage : apis.BUCKET_ROOT + option.itemImage}
                                        alt="Preview"
                                        className="h-14 w-14 rounded-lg object-cover shadow-sm"
                                    />
                                    <Button
                                        type="button"
                                        variant="ghost"
                                        size="sm"
                                        className="absolute right-2 top-2 h-7 px-2 text-xs text-red-500 hover:bg-red-50 hover:text-red-600"
                                        onClick={() => updateOption(option.id, 'itemImage', '')}
                                    >
                                        Change
                                    </Button>
                                </div>
                            ) : (
                                <div
                                    className="w-full"
                                    onClick={(e) => {
                                        e.stopPropagation();
                                    }}
                                >
                                    <div
                                        className="flex h-[80px] w-full cursor-pointer flex-col items-center justify-center gap-1 rounded-lg border-2 border-dashed border-gray-300 bg-gray-50/50 text-sm text-gray-500 hover:border-gray-400 hover:bg-gray-50 transition-colors"
                                        onClick={() => handleFileSelect(option.id)}
                                    >
                                        <div className="flex items-center gap-2">
                                            <Upload className="h-4 w-4 text-[var(--primary-brand)]" />
                                            <span className="font-medium text-gray-700">Upload item image</span>
                                        </div>
                                        <span className="text-xs text-gray-400">PNG, JPG up to 5MB</span>
                                    </div>
                                    <Input
                                        type="file"
                                        accept=".jpg,.jpeg,.png"
                                        hidden
                                        ref={(el) => (fileInputRefs.current[option.id] = el)}
                                        onChange={(e) => handleFileChange(e, option.id)}
                                        className="hidden"
                                    />
                                </div>
                            )}

                            <div className="flex justify-end pt-1">
                                {option.isDefault ? (
                                    <span className="text-xs font-semibold text-[var(--primary-brand)] bg-orange-50 px-2.5 py-1 rounded-full border border-orange-200">
                                        Default option
                                    </span>
                                ) : (
                                    <Button
                                        variant="ghost"
                                        size="sm"
                                        className="h-7 text-xs text-red-500 hover:bg-red-50 hover:text-red-600"
                                        onClick={() => removeOption(option.id)}
                                    >
                                        Remove Option
                                    </Button>
                                )}
                            </div>

                            {index !== options.length - 1 && (
                                <div className="my-4 border-b border-gray-100" />
                            )}
                        </div>
                    ))}
                </div>

                {restaurantType !== 'home-cooked-meal' && (
                    <Button
                        variant="ghost"
                        className="w-full border-2 border-dashed border-[var(--primary-brand)]/20 text-[var(--primary-brand)] hover:text-[var(--primary-brand)]/80 hover:bg-[var(--primary-brand)]/5 hover:border-[var(--primary-brand)]/40 transition-colors"
                        onClick={addOption}
                    >
                        <Plus className="mr-2 h-4 w-4" />
                        ADD MORE OPTION
                    </Button>
                )}

                <Button
                    className="h-11 w-full"
                    variant={'theme'} onClick={handleSave}
                    disabled={!isFormValid()}
                >
                    Save
                </Button>
            </div>
        </>
    );
}

export default function LoginPage(props: any) {
    return (
        <AuthLayout
            title={'Add Catering Items'}
            des={"Add catering package items and pricing options for catering services."}
            image={authBanner.src}
        >
            <Login {...props} />
        </AuthLayout>
    );
}