'use client';

import * as React from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useForm, Controller } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import DashboardLayout from '@/app/dashboard/layout';
import {
    Accordion,
    AccordionContent,
    AccordionItem,
    AccordionTrigger,
} from '@/components/ui/accordion';
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { Minus, Plus } from 'lucide-react';
import apis, { BUCKET_ROOT } from '@/utils/apis';
import { useGlobalContext } from '@/context/Provider';
import Loader from '@/components/common/loader';
import { Switch } from "@/components/ui/switch";

const formSchema = z.object({
    plate_name: z.string().min(2, 'Enter plate name'),
    description: z.string().optional(),
    plate_price: z.coerce.number().min(1, 'Enter valid plate price'),
    plate_price_child: z.coerce.number().optional(),
    categories: z.record(z.string(), z.number().min(0).max(100)).optional(),
    status: z.enum(["active", "not_active"]).default("active"),
});

type FormValues = z.infer<typeof formSchema>;

interface FoodItem {
    id: string;
    name: string;
}

interface Category {
    _id: string;
    category_name: string;
    category_image?: string;
    food: FoodItem[];
}

const EditPlate: React.FC = () => {
    const { id } = useParams();
    const planId = Array.isArray(id) ? id[0] : id;
    const [categories, setCategories] = React.useState<Category[]>([]);
    const [loading, setLoading] = React.useState(false);
    const [initialCategoryIds, setInitialCategoryIds] = React.useState<string[]>([]);
    const { Toast, userInfo } = useGlobalContext();
    const router = useRouter();

    const form = useForm<FormValues>({
        resolver: zodResolver(formSchema),
        defaultValues: {
            categories: {},
        },
    });

    React.useEffect(() => {
        const fetchData = async () => {
            try {
                const restaurantId =
                    userInfo?.restaurant_id?._id || sessionStorage.getItem('resId');
                if (!restaurantId || !planId) return;

                setLoading(true);

                // Fetch all categories
                const categoryResponse = await apis.Catering.getCategoryList(restaurantId);
                const categoryData = categoryResponse?.data || [];

                const initialCategories: Record<string, number> = {};
                categoryData.forEach((cat: Category) => {
                    initialCategories[cat._id] = 0;
                });
                setCategories(categoryData);
                form.setValue('categories', initialCategories);

                // Fetch existing plan details
                const planResponse = await apis.Catering.getPlanDetailById(planId);
                const plan = planResponse?.data;

                if (plan) {
                    form.setValue('plate_name', plan.name || '');
                    form.setValue('description', plan.discription || '');
                    form.setValue('plate_price', plan.price?.toString() || '');
                    form.setValue('plate_price_child', plan.kid_price?.toString() || '');
                    form.setValue('status', plan.status || 'active');

                    const categoryCounts: Record<string, number> = {};
                    const existingCategoryIds: string[] = [];

                    plan.plan_details.forEach((detail: any) => {
                        const catId = detail.category_id?._id;
                        existingCategoryIds.push(catId);
                        categoryCounts[catId] = detail.count || 0;
                    });

                    form.setValue('categories', {
                        ...initialCategories,
                        ...categoryCounts,
                    });

                    setInitialCategoryIds(existingCategoryIds); // ✅ Store for later use
                }
            } catch (error) {
                console.error('Error fetching plan:', error);
                Toast.error(error);
            } finally {
                setLoading(false);
            }
        };

        fetchData();
    }, [userInfo, planId]);

    const onSubmit = async (values: FormValues) => {
        try {
            setLoading(true);

            // ✅ Only include categories with count > 0
            const items = Object.entries(values.categories || {})
                .filter(([categoryId, quantity]) => {
                    // ✅ Include if:
                    // - User edited an existing category (in initial list)
                    // - OR User newly added one (quantity > 0)
                    return initialCategoryIds.includes(categoryId) || quantity > 0;
                })
                .map(([categoryId, quantity]) => ({
                    category_id: categoryId,
                    count: quantity,
                }));


            const payload = {
                name: values.plate_name,
                price: values.plate_price,
                kid_price: values.plate_price_child || 0,
                discription: values.description || '',
                status: values.status,
                plan_details: items,
            };

            const response = await apis.Catering.updateCateringService(planId, payload);

            if (response?.message) {
                Toast.success('Catering plan updated successfully!');
                router.push('/catering');
            }
        } catch (error) {
            console.error('Error updating plan:', error);
            Toast.error(error);
        } finally {
            setLoading(false);
        }
    };


    const handleIncrement = (categoryId: string) => {
        const currentValue = form.getValues(`categories.${categoryId}`) || 0;
        const category = categories.find((cat) => cat._id === categoryId);
        const maxCount = category?.food?.length || 0;

        if (currentValue < maxCount) {
            form.setValue(`categories.${categoryId}`, currentValue + 1);
        }
    };


    const handleDecrement = (categoryId: string) => {
        const currentValue = form.getValues(`categories.${categoryId}`) || 0;
        if (currentValue > 0) {
            form.setValue(`categories.${categoryId}`, currentValue - 1);
        }
    };

    if (loading) {
        return (
            <div className="w-full max-w-5xl mx-auto mt-8 bg-white rounded-lg shadow-sm border p-6">
                <div className="flex justify-center items-center h-64">
                    <Loader loading={loading} />
                </div>
            </div>
        );
    }

    return (
        <div className="w-full max-w-5xl mx-auto mt-8 bg-white rounded-lg shadow-sm border p-6">
            <h2 className="text-xl font-semibold text-gray-900 mb-4">Edit Plate</h2>

            <Form {...form}>
                <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
                    {/* Basic Info */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <FormField
                            control={form.control}
                            name="plate_name"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Plate Name</FormLabel>
                                    <FormControl>
                                        <Input placeholder="Enter name" {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="description"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Description</FormLabel>
                                    <FormControl>
                                        <Input placeholder="Description" {...field} />
                                    </FormControl>
                                </FormItem>
                            )}
                        />
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <FormField
                            control={form.control}
                            name="plate_price"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Plate Price</FormLabel>
                                    <FormControl>
                                        <Input
                                            type="number"
                                            step="0.01"
                                            min="0"
                                            placeholder="Enter price"
                                            {...field}
                                            onChange={(e) => field.onChange(e.target.value ? Number(e.target.value) : 0)}
                                        />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="plate_price_child"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Plate Price (under 12 yrs)</FormLabel>
                                    <FormControl>
                                        <Input
                                            type="number"
                                            step="0.01"
                                            min="0"
                                            placeholder="Optional"
                                            {...field}
                                            onChange={(e) => field.onChange(e.target.value ? Number(e.target.value) : 0)}
                                        />
                                    </FormControl>
                                </FormItem>
                            )}
                        />
                    </div>

                    <Separator />

                    {/* Accordion with category counts */}
                    {categories.length > 0 ? (
                        <Accordion type="multiple" className="space-y-3">
                            {categories.map((category) => (
                                <AccordionItem
                                    key={category._id}
                                    value={category._id}
                                    className="border rounded-lg"
                                >
                                    <div className="flex items-center justify-between px-4 py-2">
                                        <AccordionTrigger className="flex items-center gap-3 flex-1 hover:no-underline">
                                            {category.category_image && (
                                                <img
                                                    src={`${BUCKET_ROOT}${category.category_image}`}
                                                    alt={category.category_name}
                                                    className="h-8 w-8 rounded-full object-cover"
                                                />
                                            )}
                                            <span className="text-left font-medium">{category.category_name}</span>
                                        </AccordionTrigger>

                                        <Controller
                                            control={form.control}
                                            name={`categories.${category._id}`}
                                            render={({ field }) => (
                                                <div
                                                    className="flex items-center gap-2"
                                                    onClick={(e) => e.stopPropagation()}
                                                >
                                                    <Button
                                                        type="button"
                                                        variant="outline"
                                                        size="icon"
                                                        className="h-8 w-8"
                                                        onClick={() => handleDecrement(category._id)}
                                                    >
                                                        <Minus className="h-4 w-4" />
                                                    </Button>
                                                    <span className="w-6 text-center font-medium">
                                                        {field.value || 0}
                                                    </span>
                                                    <Button
                                                        type="button"
                                                        variant="outline"
                                                        size="icon"
                                                        className="h-8 w-8"
                                                        onClick={() => handleIncrement(category._id)}
                                                    >
                                                        <Plus className="h-4 w-4" />
                                                    </Button>
                                                </div>
                                            )}
                                        />
                                    </div>

                                    <AccordionContent>
                                        <div className="px-4 pb-4 space-y-2">
                                            {category.food && category.food.length > 0 ? (
                                                category.food.map((item) => (
                                                    <div
                                                        key={item.id}
                                                        className="flex items-start gap-2 py-1 text-sm text-gray-700"
                                                    >
                                                        <span className="text-gray-500 text-base leading-5">•</span>
                                                        <span>{item.name}</span>
                                                    </div>
                                                ))
                                            ) : (
                                                <p className="text-gray-500 text-sm">No items available</p>
                                            )}
                                        </div>
                                    </AccordionContent>
                                </AccordionItem>
                            ))}
                        </Accordion>
                    ) : (
                        <p className="text-gray-500 text-center py-8">No categories available</p>
                    )}

                    {/* Save Button */}
                    <div className="flex justify-end mt-4">
                        <Button
                            type="submit"
                            className="flex items-center font-medium gap-2 bg-[var(--primary-brand)] text-white px-4 py-2 rounded-lg text-sm hover:bg-[var(--primary-brand)] focus:bg-[var(--primary-brand)] active:bg-[var(--primary-brand)]"
                        >
                            Update Plate
                        </Button>
                    </div>
                </form>
            </Form>
        </div>
    );
};

export default function EditPlatePage() {
    return (
        <DashboardLayout>
            <div className="h-full overflow-y-auto p-4">
                <EditPlate />
            </div>
        </DashboardLayout>
    );
}
