'use client';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
// import { FileInput } from '@/components/ui/file-input';
import { ChevronDown, ChevronRight, ChevronUp, Pencil, Percent, Plus, Tag, Trash2 } from 'lucide-react';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { MultiImages } from '@/components/common/MultipleDropzone';
import apis, { BUCKET_ROOT } from '@/utils/apis';
// import QuantityDialog from '@/app/auth/restaurant/itemdetails/variantsmodals/QuantityModal';
import { useEffect, useState, useRef, forwardRef, useImperativeHandle } from 'react';
// import SizeDialog from '@/app/auth/restaurant/itemdetails/variantsmodals/SizeModal';
// import PiecesDialog from '@/app/auth/restaurant/itemdetails/variantsmodals/PiecesModal';
import AddonDialog from './customizatiomodal/Addon';
import ToppingsDialog from './customizatiomodal/Toppings';
import CustomAddOn from './customizatiomodal/CustomAddOn';
import AddMoreDialog from './customizatiomodal/AddMore';
import { Icons } from '@/components/icons';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { useRouter } from 'next/navigation';
import QuantityDialog from './variantsmodals/QuantityModal';
import PiecesDialog from './variantsmodals/PiecesModal';
import SizeDialog from './variantsmodals/SizeModal';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { Checkbox } from '@/components/ui/checkbox';
import { useGlobalContext } from '@/context/Provider';
import { cn, currency, formatDateStringToUTC } from '@/lib/utils';

export interface EditItemRef {
  validate: () => Promise<boolean>;
}

interface ItemTiming {
  day: string;
  start_time: string;
  end_time: string;
}

let itemTiming: ItemTiming[] = [];

const menuItemSchema = z.object({
  food_type: z.string().optional(),

  // Basic Details
  // category_id: z.string().min(2, ''),
  name: z.string().min(2, 'Item name must be at least 2 characters'),
  price: z.coerce.number().positive('Price must be positive'),
  itemDescription: z
    .string()
    .min(10, 'Description must be at least 10 characters'),
  image: z.array(z.record(z.any())).min(3, 'At least 3 images are required'),

  // Item Discount
  is_discount_active: z.boolean().optional(),
  discount_type: z.enum(['percentage', 'fixed']).optional(),
  discount_value: z.coerce.number().min(0).optional(),
  discounted_price: z.coerce.number().optional(),
  discount_start_date: z.string().optional(),
  discount_end_date: z.string().optional(),

  // Variants
  variants: z.object({
    quantity: z.array(z.record(z.any())).optional(),

    size: z.array(z.record(z.any())).optional(),

    pieces: z.array(z.record(z.any())).optional()
  }),

  // Customization
  customization: z.record(z.array(z.any())).optional(),

  // Timing
  timing: z.array(z.record(z.any())).optional(),
  availability: z.enum(['all_time', 'same_time', 'different_time']).optional(),
  availability_status: z.enum(['in_stock', 'out_of_stock', 'hidden']).optional(),
  is_recommend: z.boolean().optional()
}).superRefine((data, ctx) => {
  if (data.is_discount_active) {
    if (data.discount_value === undefined || data.discount_value === null || isNaN(Number(data.discount_value)) || Number(data.discount_value) <= 0) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: 'Please enter a valid discount value greater than 0',
        path: ['discount_value']
      });
    }

    const todayStr = new Date().toISOString().split('T')[0];

    const getNormDate = (str?: string) => {
      if (!str) return '';
      return str.includes('T') ? str.split('T')[0] : str;
    };

    const startNorm = getNormDate(data.discount_start_date);
    const endNorm = getNormDate(data.discount_end_date);

    if (endNorm && endNorm < todayStr) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: 'End date cannot be in the past',
        path: ['discount_end_date']
      });
    }

    if (startNorm && endNorm && endNorm < startNorm) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: 'End date cannot be earlier than start date',
        path: ['discount_end_date']
      });
    }
  }
});

const generateTimeSlots = () => {
  const slots = [];
  for (let hour = 0; hour < 24; hour++) {
    for (let minute = 0; minute < 60; minute += 30) {
      const time = `${hour.toString().padStart(2, '0')}:${minute
        .toString()
        .padStart(2, '0')}`;
      slots.push(time);
    }
  }
  return slots;
};
interface TimeSlotUpdate {
  day: string;
  index: number;
  field: 'startTime' | 'endTime';
  value: string;
}
interface TimeSlot {
  startTime: string;
  endTime: string;
}

interface DaySettings {
  enabled: boolean;
  slots: TimeSlot[];
}

interface DaySettingsState {
  [key: string]: DaySettings;
}
type MenuItemFormValues = z.infer<typeof menuItemSchema>;

const EditItem = forwardRef<EditItemRef, { data: any; onFormUpdate: any }>(
  function EditItem({ data, onFormUpdate }, ref) {
  const daysOfWeek = [
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday',
    'Sunday'
  ];
  const timeSlots = generateTimeSlots();
  const [foodId, setFoodId] = useState('');
  const [catId, setCatId] = useState('');
  const [isOpen, setIsOpen] = useState(false);
  const [itemTime, setItemTime] = useState<any>(null);
  const lastPayloadRef = useRef<string>('');
  const isFirstRender = useRef(true);
  const getLocalTimeFromUTC = (utcString: string | undefined) => {
    if (!utcString) return undefined;
    const date = new Date(utcString);
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
  };

  const [slot, setSlot] = useState<{
    start: string | undefined;
    end: string | undefined;
  }>({
    start: getLocalTimeFromUTC(data?.item_timing?.[0]?.start_time),
    end: getLocalTimeFromUTC(data?.item_timing?.[0]?.end_time)
  });
  const { Toast, userInfo } = useGlobalContext();

  useImperativeHandle(ref, () => ({
    validate: async () => {
      if (isFoodCategory && !form.getValues('food_type')) {
        form.setError('food_type', {
          type: 'manual',
          message: 'Please select a sub category (Veg / Non Veg / Egg)'
        });
        Toast.error('Please select a sub category (Veg / Non Veg / Egg)');
        return false;
      }
      const valid = await form.trigger();
      if (!valid) {
        const errors = form.formState.errors;
        const getFirstErrorMessage = (errObj: any): string | null => {
          if (!errObj) return null;
          if (typeof errObj.message === 'string' && errObj.message) {
            return errObj.message;
          }
          for (const key of Object.keys(errObj)) {
            const childMsg = getFirstErrorMessage(errObj[key]);
            if (childMsg) return childMsg;
          }
          return null;
        };

        const firstErrorMsg =
          getFirstErrorMessage(errors) ||
          'Please fix form errors before saving.';
        Toast.error(firstErrorMsg);
      }
      return valid;
    }
  }));
  const [showModal, setShowModal] = useState<Record<string, boolean>>({
    quantity: false,
    size: false,
    pieces: false,
    addon: false,
    toppings: false,
    addmore: false
  });
  const [editingVariantKey, setEditingVariantKey] = useState<string | null>(
    null
  );
  const [editAddonData, setEditAddonData] = useState([]) as any;
  const [editAddonData1, setEditAddonData1] = useState([]) as any;
  const [expandedDays, setExpandedDays] = useState(['Monday']);
  const [daySettings, setDaySettings] = useState<DaySettingsState>(() => {
    // Create initial settings with all days disabled and default times
    const createDefaultSettings = () =>
      daysOfWeek.reduce(
        (acc, day) => ({
          ...acc,
          [day]: {
            enabled: false,
            slots: [{ startTime: '09:00', endTime: '22:00' }]
          }
        }),
        {} as DaySettingsState
      );

    // Initialize with default values first
    const defaultSettings = createDefaultSettings();

    return defaultSettings;
  });

  const isFoodCategory =
    userInfo?.restaurant_id?.type === 'food';
  // Update day settings when data is loaded
  useEffect(() => {
    if (data?.item_timing?.length > 0 && data?._id !== foodId) {
      setDaySettings((prevSettings) => {
        const newSettings = { ...prevSettings };
        let hasEnabledDays = false;

        data.item_timing.forEach((timing: any) => {
          const day = timing.day;
          if (day && newSettings[day]) {
            newSettings[day] = {
              enabled: true,
              slots: [
                {
                  startTime: getLocalTimeFromUTC(timing.start_time) || '09:00',
                  endTime: getLocalTimeFromUTC(timing.end_time) || '22:00'
                }
              ]
            };
            hasEnabledDays = true;
          }
        });

        // If no days were enabled (shouldn't happen with your data), enable Monday
        if (!hasEnabledDays) {
          newSettings['Monday'].enabled = true;
        }

        return newSettings;
      });
    } else if (data && data?._id !== foodId) {
      // If no timing data, enable Monday by default
      setDaySettings((prev) => ({
        ...prev,
        Monday: {
          ...prev.Monday,
          enabled: true
        }
      }));
    }
  }, [data?.item_timing, data?._id, foodId]);
  const [copyToAll, setCopyToAll] = useState(false);

  const toggleDay = (day: string): void => {
    setExpandedDays((prev: string[]) =>
      prev.includes(day)
        ? prev.filter((d: string) => d !== day)
        : [...prev, day]
    );
  };
  const form = useForm<MenuItemFormValues>({
    resolver: zodResolver(menuItemSchema),
    mode: 'onChange',
    defaultValues: {
      // category_id: "",
      food_type: undefined,
      name: '',
      image: [],
      price: undefined,
      itemDescription: '',
      variants: {
        quantity: [],
        size: [],
        pieces: []
      },
      customization: {
        addons: [],
        toppings: [],
      },
      availability: undefined,
      availability_status: 'in_stock',
      is_recommend: false,
      timing: []
    }
  });
  const onSubmit = async (data: MenuItemFormValues) => {
    // Handle form submission
  };

  console.log('--- EditItem Render ---', { foodId, dataId: data?._id, formAvailability: form?.watch('availability') });

  useEffect(() => {
    console.log('availability useEffect triggered', form.watch('availability'));
    if (form.getValues('availability') === 'different_time') {
      console.log('setIsOpen(true) called');
      setIsOpen(true);
    }
  }, [form.watch('availability')]);

  const watchedPrice = form.watch('price');
  const watchedDiscountActive = form.watch('is_discount_active');
  const watchedDiscountType = form.watch('discount_type');
  const watchedDiscountValue = form.watch('discount_value');

  useEffect(() => {
    const priceNum = Number(watchedPrice);
    const discValNum = Number(watchedDiscountValue);
    const isDiscountActive = Boolean(watchedDiscountActive);
    const discType = watchedDiscountType || 'percentage';

    if (!isDiscountActive || isNaN(priceNum) || priceNum <= 0 || isNaN(discValNum) || discValNum <= 0) {
      if (form.getValues('discounted_price') !== undefined) {
        form.setValue('discounted_price', undefined);
      }
      return;
    }

    let calcDiscounted = priceNum;
    if (discType === 'percentage') {
      const validPercent = Math.min(100, Math.max(0, discValNum));
      calcDiscounted = Math.max(0, priceNum - (priceNum * (validPercent / 100)));
    } else {
      calcDiscounted = Math.max(0, priceNum - discValNum);
    }

    const finalVal = Number(calcDiscounted.toFixed(2));
    if (form.getValues('discounted_price') !== finalVal) {
      form.setValue('discounted_price', finalVal);
    }
  }, [watchedPrice, watchedDiscountActive, watchedDiscountType, watchedDiscountValue, form]);

  useEffect(() => {
    console.log('reset useEffect triggered', { dataId: data?._id, foodId });
    if (data && data?._id !== foodId) {
      console.log('resetting form with data', data?._id);
      setFoodId(data?._id);
      setCatId(data?.category_id);
      form.reset({
        food_type: data.food_type,
        name: data.name,
        image:
          data?.image?.map((image: any) => {
            const str = String(image || '');
            const isUrl =
              str.startsWith('http://') || str.startsWith('https://');
            const key = isUrl ? str.split('/').pop() || str : str; // extract key if URL
            return {
              url: key, // keep key for payload
              name: key,
              id: key,
              fullUrl: isUrl ? str : BUCKET_ROOT + key // preview URL
            };
          }) || [],
        price: data.price,
        itemDescription: data.description,
        is_discount_active: Boolean(data.discounted_price || data.is_discount_active),
        discount_type: data.discount_type || 'percentage',
        discount_value: data.discount_value !== undefined
          ? data.discount_value
          : data.discounted_price && data.price
            ? (data.discount_type === 'fixed'
              ? Number((data.price - data.discounted_price).toFixed(2))
              : Math.round(((data.price - data.discounted_price) / data.price) * 100))
            : undefined,
        discounted_price: data.discounted_price,
        discount_start_date: data.discount_start_date ? new Date(data.discount_start_date).toISOString().split('T')[0] : '',
        discount_end_date: data.discount_end_date ? new Date(data.discount_end_date).toISOString().split('T')[0] : '',
        variants: {
          quantity: data?.quantity || [],
          size: data?.size || [],
          pieces: data?.pieces || []
        },
        customization: {
          addons: data?.add_ons?.map((item: any, index: number) => ({
            id: index + 1,
            name: item.title || item.name,
            title: item.title || item.name,
            price: Number(item.additional_price ?? item.price ?? 0),
            additional_price: Number(item.additional_price ?? item.price ?? 0),
            min_selection: Number(item.min_selection ?? 0),
            max_selection: Number(item.max_selection ?? 1),
            isCompulsory: item.customer_selection === "compulsory",
          })) || [],
          toppings: data?.toppings?.map((item: any, index: number) => ({
            id: index + 1,
            name: item.title || item.name,
            title: item.title || item.name,
            price: Number(item.additional_price ?? item.price ?? 0),
            additional_price: Number(item.additional_price ?? item.price ?? 0),
            min_selection: Number(item.min_selection ?? 0),
            max_selection: Number(item.max_selection ?? 1),
            isCompulsory: item.customer_selection === "compulsory",
          })) || [],
          custom_groups: Array.isArray(data?.other_add_ons)
            ? data.other_add_ons.map((group: any) => ({
                title: group.title,
                description: group.description || '',
                min_selection: Number(group.min_selection ?? 0),
                max_selection: Number(group.max_selection ?? 1),
                options: (group.options || []).map((opt: any, idx: number) => ({
                  id: opt.id || idx + 1,
                  title: opt.title || opt.name,
                  additional_price: Number(opt.additional_price ?? opt.price ?? 0),
                  min_selection: Number(opt.min_selection ?? group.min_selection ?? 0),
                  max_selection: Number(opt.max_selection ?? group.max_selection ?? 1)
                }))
              }))
            : []
        },
        availability_status: (data?.availability_status === 'hidden' || data?.is_hidden === true || data?.is_hidden === 'true')
          ? 'hidden'
          : (data?.availability_status === 'out_of_stock' || data?.availability_status === 'in_stock')
          ? data.availability_status
          : data?.is_available === false
          ? 'out_of_stock'
          : 'in_stock',
        availability: data.availability_type,
        is_recommend: Boolean(data?.is_recommend)
      });
      setTimeout(() => {
        form.trigger(['discount_start_date', 'discount_end_date']);
      }, 50);
    }
  }, [data, form, foodId]);

  const getLatestFormData = () => {
    const updatedData = form.getValues();
    let itemTiming: any[] = [];
    const daysOfWeekWithIds = [
      { day: 'Monday', day_id: '1' },
      { day: 'Tuesday', day_id: '2' },
      { day: 'Wednesday', day_id: '3' },
      { day: 'Thursday', day_id: '4' },
      { day: 'Friday', day_id: '5' },
      { day: 'Saturday', day_id: '6' },
      { day: 'Sunday', day_id: '7' }
    ];
    const formatDateTime = (time: string) => {
      const [hours, minutes] = (time || '09:00').split(':');
      const date = new Date(2024, 0, 1, parseInt(hours), parseInt(minutes));
      return date.toISOString();
    };

    if (updatedData.availability === 'same_time') {
      itemTiming = daysOfWeekWithIds.map((d) => ({
        ...d,
        start_time: formatDateTime(slot.start || '09:00'),
        end_time: formatDateTime(slot.end || '22:00')
      }));
    } else if (updatedData.availability === 'different_time') {
      itemTiming = daysOfWeekWithIds.map((d) => {
        const daySetting = daySettings[d.day];
        const startTime = daySetting?.slots?.[0]?.startTime || '09:00';
        const endTime = daySetting?.slots?.[0]?.endTime || '22:00';
        return {
          ...d,
          start_time: formatDateTime(startTime),
          end_time: formatDateTime(endTime)
        };
      });
    } else {
      itemTiming = [];
    }
    return {
      food_type: updatedData?.food_type,
      name: updatedData?.name,
      image: updatedData?.image?.map((img: any) => img?.url) || [],
      price: updatedData?.price,
      description: updatedData?.itemDescription,
      discounted_price: updatedData?.is_discount_active ? updatedData?.discounted_price : null,
      discount_type: updatedData?.is_discount_active ? (updatedData?.discount_type || 'percentage') : null,
      discount_value: updatedData?.is_discount_active ? updatedData?.discount_value : null,
      discount_start_date: updatedData?.is_discount_active && updatedData?.discount_start_date ? formatDateStringToUTC(updatedData.discount_start_date, false) : null,
      discount_end_date: updatedData?.is_discount_active && updatedData?.discount_end_date ? formatDateStringToUTC(updatedData.discount_end_date, true) : null,
      is_discount_active: Boolean(updatedData?.is_discount_active),
      is_available: (updatedData?.availability_status || 'in_stock') === 'in_stock',
      availability_status: updatedData?.availability_status || 'in_stock',
      is_hidden: updatedData?.availability_status === 'hidden',
      quantity: updatedData?.variants?.quantity,
      size: updatedData?.variants?.size,
      add_ons:
        (updatedData?.customization?.addons || []).map((addOn: any) => ({
          title: addOn.name || addOn.title,
          additional_price: Number(addOn.price ?? addOn.additional_price ?? 0),
          min_selection: Number(addOn.min_selection ?? 0),
          max_selection: Number(addOn.max_selection ?? 1)
        })) || [],
      toppings:
        (updatedData?.customization?.toppings || []).map((topping: any) => ({
          title: topping.name || topping.title,
          additional_price: Number(topping.price ?? topping.additional_price ?? 0),
          min_selection: Number(topping.min_selection ?? 0),
          max_selection: Number(topping.max_selection ?? 1)
        })) || [],
      other_add_ons: Array.isArray(updatedData.customization?.custom_groups)
        ? updatedData.customization!.custom_groups.map((group: any) => ({
            title: group.title,
            description: group.description || '',
            min_selection: Number(group.min_selection ?? 0),
            max_selection: Number(group.max_selection ?? 1),
            options: (group.options || []).map((opt: any) => ({
              title: opt.title || opt.name,
              additional_price: Number(opt.additional_price ?? opt.price ?? 0),
              min_selection: Number(opt.min_selection ?? group.min_selection ?? 0),
              max_selection: Number(opt.max_selection ?? group.max_selection ?? 1)
            }))
          }))
        : Object.entries(updatedData.customization || {})
            .filter(([key]) => !['addons', 'toppings', 'custom', 'custom_groups'].includes(key))
            .map(([key, options]: [string, any]) => ({
              title: key,
              description: '',
              min_selection: 0,
              max_selection: Array.isArray(options) ? options.length : 1,
              options: Array.isArray(options) ? options.map((opt: any) => ({
                title: opt.title || opt.name,
                additional_price: Number(opt.additional_price ?? opt.price ?? 0),
                min_selection: 0,
                max_selection: 1
              })) : []
            })),
      availability_type: updatedData?.availability,
      item_timing: itemTiming,
      category_id: catId,
      _id: foodId,
      is_recommend: Boolean(updatedData?.is_recommend)
    };
  };

  useEffect(() => {
    const subscription = form.watch(() => {
      if (data?._id && foodId !== data?._id) return;
      const payload = getLatestFormData();
      const currentPayloadStr = JSON.stringify(payload);
      if (currentPayloadStr !== lastPayloadRef.current) {
        lastPayloadRef.current = currentPayloadStr;
        onFormUpdate(payload);
      }
    });

    return () => subscription.unsubscribe();
  }, [form.watch, slot, daySettings, onFormUpdate, catId, foodId, data?._id]);

  useEffect(() => {
    console.log('timing useEffect triggered', { isFirstRender: isFirstRender.current, foodId, dataId: data?._id });
    if (isFirstRender.current) {
      console.log('timing useEffect: isFirstRender is true, returning early');
      isFirstRender.current = false;
      return;
    }

    // Prevent sending empty or stale ID updates back to the parent during initialization
    if (data?._id && foodId !== data?._id) {
      console.log('timing useEffect: initialization in progress, skipping update');
      return;
    }

    const payload = getLatestFormData();
    const currentPayloadStr = JSON.stringify(payload);
    console.log('timing useEffect: checking payload change', {
      currentPayloadStrLength: currentPayloadStr.length,
      lastPayloadStrLength: lastPayloadRef.current.length,
      changed: currentPayloadStr !== lastPayloadRef.current
    });
    if (currentPayloadStr !== lastPayloadRef.current) {
      lastPayloadRef.current = currentPayloadStr;
      console.log('timing useEffect: calling onFormUpdate');
      onFormUpdate(payload);
    }
  }, [slot, daySettings, onFormUpdate, catId, foodId, data?._id]);

  const handleImages = (data: any) => {
    form.setValue('image', data);
  };

  useEffect(() => {
    if (data?.item_timing?.length > 0 && data?._id !== foodId) {
      setSlot({
        start: getLocalTimeFromUTC(data?.item_timing[0]?.start_time),
        end: getLocalTimeFromUTC(data?.item_timing[0]?.end_time)
      });
    }
  }, [data, foodId]);

  const handleModalData = (data: any) => {
    form.setValue(
      `variants.${data?.type}` as keyof MenuItemFormValues,
      data?.option
    );
    setShowModal({ ...showModal, [data?.type]: false });
  };

  const handleCustomModalData = (data: any) => {
    form.setValue(
      `customization.${data?.type}` as keyof MenuItemFormValues,
      data?.option
    );
    setShowModal((prev) => ({
      ...prev,
      [data.type]: false
    }));
  };

  const [selectedGroupIndex, setSelectedGroupIndex] = useState<number | null>(null);
  const [editingGroupData, setEditingGroupData] = useState<any>(null);

  const handleSaveCustomGroup = (groupData: any, editingIndex?: number | null) => {
    const currentCustomization = form.getValues('customization') || {};
    const currentGroups = [...(currentCustomization.custom_groups || [])];

    if (editingIndex !== undefined && editingIndex !== null && editingIndex >= 0) {
      currentGroups[editingIndex] = groupData;
    } else {
      currentGroups.push(groupData);
    }

    form.setValue('customization', {
      ...currentCustomization,
      custom_groups: currentGroups
    });

    setShowModal((prev: any) => ({ ...prev, addmore: false }));
    setSelectedGroupIndex(null);
    setEditingGroupData(null);
  };

  const handleEditCustomGroup = (index: number) => {
    const currentGroups = form.getValues('customization.custom_groups') || [];
    if (currentGroups[index]) {
      setSelectedGroupIndex(index);
      setEditingGroupData(currentGroups[index]);
      setShowModal((prev: any) => ({ ...prev, addmore: true }));
    }
  };

  const handleDeleteCustomGroup = (index: number) => {
    const currentCustomization = form.getValues('customization') || {};
    const currentGroups = currentCustomization.custom_groups || [];
    const updated = currentGroups.filter((_: any, i: number) => i !== index);
    form.setValue('customization', {
      ...currentCustomization,
      custom_groups: updated
    });
    setShowModal((prev: any) => ({ ...prev, addmore: false }));
    setSelectedGroupIndex(null);
    setEditingGroupData(null);
  };

  const handleSection = (data: any) => {
    setShowModal((prev) => ({ ...prev, addmore: false }));

    const currentCustomization = form.getValues('customization');

    form.setValue('customization', {
      ...currentCustomization,
      [data.name]: data.options || []
    });
  };
  const handleRemove = (type: string) => {
    if (type.startsWith('customization.')) {
      const parts = type.split('.');
      const key = parts[1];
      if (key && !['addons', 'toppings', 'custom'].includes(key)) {
        const currentCustomization = { ...form.getValues('customization') };
        delete currentCustomization[key];
        form.setValue('customization', currentCustomization);
        form.trigger('customization');
        return;
      }
    }
    form.setValue(type as any, []);
    form.trigger(type as any);
  };

  const variants = {
    quantity: form.getValues('variants.quantity') || [],
    size: form.getValues('variants.size') || [],
    pieces: form.getValues('variants.pieces') || []
  };

  // Find the first non-empty variant
  const activeVariant = Object.entries(variants).find(
    ([_, value]) => Array.isArray(value) && value.length > 0
  );
  const activeVariantKey = activeVariant?.[0];
  const activeVariantData = activeVariant?.[1] || [];

  const variantDialogs = {
    quantity: QuantityDialog,
    size: SizeDialog,
    pieces: PiecesDialog
  };

  const ActiveDialog =
    variantDialogs[activeVariantKey as keyof typeof variantDialogs];

  const updateTimeSloted = (type: 'start' | 'end', data: string) => {
    setSlot((prevSlot) => ({
      ...prevSlot,
      [type]: data
    }));
  };
  const updateTimeSlot = ({
    day,
    index,
    field,
    value
  }: TimeSlotUpdate): void => {
    setDaySettings((prev: DaySettingsState) => ({
      ...prev,
      [day]: {
        ...prev[day],
        slots: prev[day].slots.map((slot: TimeSlot, i: number) =>
          i === index ? { ...slot, [field]: value } : slot
        )
      }
    }));
  };

  const handleCopyToAllChange = (checked: boolean): void => {
    setCopyToAll(checked);
    if (checked) {
      const mondaySettings: DaySettings = daySettings['Monday'];
      setDaySettings((prev: DaySettingsState) => {
        const newSettings: DaySettingsState = { ...prev };
        daysOfWeek.forEach((day: string) => {
          if (day !== 'Monday') {
            newSettings[day] = {
              ...mondaySettings,
              enabled: prev[day].enabled
            };
          }
        });
        return newSettings;
      });
    }
  };

  const handleSave = async () => {
    let foodId: any = sessionStorage.getItem('foodId');
    const daysOfWeekWithIds = [
      { day: 'Monday', day_id: '1' },
      { day: 'Tuesday', day_id: '2' },
      { day: 'Wednesday', day_id: '3' },
      { day: 'Thursday', day_id: '4' },
      { day: 'Friday', day_id: '5' },
      { day: 'Saturday', day_id: '6' },
      { day: 'Sunday', day_id: '7' }
    ];

    const formattedData = daysOfWeekWithIds.map(({ day, day_id }) => ({
      day,
      day_id,
      start_time: daySettings[day].slots[0].startTime,
      end_time: daySettings[day].slots[0].endTime
    }));
    setItemTime(formattedData);
    setIsOpen(false);
  };
  return (
    <Form {...form}>
      <form
        onSubmit={form.handleSubmit(onSubmit, (errors) => {
          if (errors.food_type) {
            Toast.error(errors.food_type.message);
          }
        })}
        className="space-y-6 "
      >
        {/* Category Selection */}
        {isFoodCategory && (
          <div className="flex gap-2">
            <FormField
              control={form.control}
              name="food_type"
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <div className="flex gap-2">
                      <Button
                        type="button"
                        variant="outline"
                        className={`rounded-lg border ${field.value === 'veg'
                          ? 'border-green-500 bg-green-100'
                          : 'border-gray-200'
                          }`}
                        onClick={() => field.onChange('veg')}
                      >
                        <Icons.VegIcon />{' '}
                        <span style={{ color: '#248853' }}>Veg</span>
                      </Button>
                      <Button
                        type="button"
                        variant="outline"
                        className={` rounded-lg border ${field.value === 'non_veg'
                          ? 'border-red-500 bg-red-100'
                          : 'border-gray-200'
                          }`}
                        onClick={() => field.onChange('non_veg')}
                      >
                        <Icons.NonVegIcon />{' '}
                        <span style={{ color: '#BF2A34' }}>Non Veg</span>
                      </Button>
                      <Button
                        type="button"
                        variant="outline"
                        className={` rounded-lg border ${field.value === 'egg'
                          ? 'border-[var(--primary-brand)] bg-orange-100'
                          : 'border-gray-200'
                          }`}
                        onClick={() => field.onChange('egg')}
                      >
                        <Icons.EggIcon />{' '}
                        <span style={{ color: 'var(--primary-brand)' }}>Egg</span>
                      </Button>
                    </div>
                  </FormControl>
                </FormItem>
              )}
            />
          </div>
        )}

        {/* Basic Details */}
        <div>
          <h2 className="mb-4 text-start text-lg font-medium">Basic Details</h2>

          <div className="space-y-4">
            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Item Name</FormLabel>
                  <FormControl>
                    <Input placeholder="Enter item name" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="price"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Item Price</FormLabel>
                  <FormControl>
                    <Input placeholder="Enter item price" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="itemDescription"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Item Description</FormLabel>
                  <FormControl>
                    <Textarea
                      placeholder="Enter item description...."
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>
        </div>

        {/* Item Image */}
        <div>
          <FormField
            control={form.control}
            name="image"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Item Image</FormLabel>
                <FormControl>
                  <MultiImages addImages={handleImages} images={field.value} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        {/* Item Discount Section */}
        <div className="rounded-xl border border-gray-200 bg-white p-5 space-y-4 shadow-sm">
          <div className="flex items-center justify-between border-b pb-3">
            <div>
              <h2 className="text-base font-semibold text-gray-900">Item Discount</h2>
              <p className="text-xs text-gray-500">Enable and configure special promotional pricing for this item</p>
            </div>
            <div className="flex items-center gap-2">
              <span className="text-xs font-medium text-gray-600">
                {form.watch('is_discount_active') ? 'Enabled' : 'Disabled'}
              </span>
              <div
                className={cn(
                  'relative h-6 w-11 cursor-pointer rounded-full transition-colors duration-200',
                  form.watch('is_discount_active') ? 'bg-emerald-500' : 'bg-gray-200'
                )}
                onClick={() => {
                  const val = !form.watch('is_discount_active');
                  form.setValue('is_discount_active', val);
                  if (!val) {
                    form.setValue('discounted_price', undefined);
                  }
                }}
              >
                <div
                  className={cn(
                    'absolute top-0.5 h-5 w-5 rounded-full bg-white shadow-md transition-all duration-200',
                    form.watch('is_discount_active') ? 'left-[22px]' : 'left-0.5'
                  )}
                />
              </div>
            </div>
          </div>

          {form.watch('is_discount_active') && (
            <div className="space-y-4 pt-1">
              {/* Discount Type Selector */}
              <div className="grid grid-cols-2 gap-3">
                <button
                  type="button"
                  className={cn(
                    'flex items-center justify-center gap-2 h-10 rounded-lg border text-sm font-medium transition-all',
                    (form.watch('discount_type') || 'percentage') === 'percentage'
                      ? 'border-[var(--primary-brand)] bg-orange-50 text-[var(--primary-brand)] font-semibold shadow-sm'
                      : 'border-gray-200 bg-gray-50 text-gray-600 hover:bg-gray-100'
                  )}
                  onClick={() => form.setValue('discount_type', 'percentage')}
                >
                  <Percent size={15} /> Percentage (%)
                </button>
                <button
                  type="button"
                  className={cn(
                    'flex items-center justify-center gap-2 h-10 rounded-lg border text-sm font-medium transition-all',
                    form.watch('discount_type') === 'fixed'
                      ? 'border-[var(--primary-brand)] bg-orange-50 text-[var(--primary-brand)] font-semibold shadow-sm'
                      : 'border-gray-200 bg-gray-50 text-gray-600 hover:bg-gray-100'
                  )}
                  onClick={() => form.setValue('discount_type', 'fixed')}
                >
                  <Tag size={15} /> Fixed Discount ({currency})
                </button>
              </div>

              {/* Discount Value Input & Live Preview */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="discount_value"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="text-xs font-semibold text-gray-700">
                        {(form.watch('discount_type') || 'percentage') === 'percentage'
                          ? 'Discount Percentage (%)'
                          : `Fixed Discount Amount (${currency})`}
                      </FormLabel>
                      <FormControl>
                        <div className="relative">
                          <Input
                            type="number"
                            min="0"
                            max={(form.watch('discount_type') || 'percentage') === 'percentage' ? '100' : undefined}
                            placeholder={(form.watch('discount_type') || 'percentage') === 'percentage' ? 'e.g. 20' : 'e.g. 50'}
                            {...field}
                            className="h-10 text-sm"
                          />
                          <span className="absolute right-3 top-2.5 text-xs text-gray-400 font-medium">
                            {(form.watch('discount_type') || 'percentage') === 'percentage' ? '%' : currency}
                          </span>
                        </div>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                {/* Current & Discounted Price Preview Card */}
                <div className="flex flex-col justify-center bg-gray-50 border border-gray-100 rounded-lg p-3">
                  <span className="text-xs text-gray-500 font-medium mb-1">Price Preview</span>
                  {Number(form.watch('price')) > 0 ? (
                    <div className="flex items-baseline gap-2">
                      <span className="text-xs text-gray-400 line-through">
                        {currency}{Number(form.watch('price'))}
                      </span>
                      <span className="text-base font-bold text-emerald-600">
                        {currency}{form.watch('discounted_price') !== undefined ? form.watch('discounted_price') : Number(form.watch('price'))}
                      </span>
                      {form.watch('discounted_price') !== undefined && Number(form.watch('price')) > 0 && (
                        <span className="text-[11px] font-semibold bg-emerald-100 text-emerald-700 px-1.5 py-0.5 rounded">
                          {form.watch('discount_type') === 'fixed'
                            ? `${currency}${Number((Number(form.watch('price')) - Number(form.watch('discounted_price'))).toFixed(2))} OFF`
                            : `${Math.round(((Number(form.watch('price')) - Number(form.watch('discounted_price'))) / Number(form.watch('price'))) * 100)}% OFF`}
                        </span>
                      )}
                    </div>
                  ) : (
                    <span className="text-xs text-gray-400 italic">Enter item price to see discount preview</span>
                  )}
                </div>
              </div>

              {/* Start Date & End Date */}
              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="discount_start_date"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="text-xs font-semibold text-gray-700">Start Date</FormLabel>
                      <FormControl>
                        <Input
                          type="date"
                          {...field}
                          className="h-10 text-sm"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="discount_end_date"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="text-xs font-semibold text-gray-700">End Date</FormLabel>
                      <FormControl>
                        <Input
                          type="date"
                          min={form.watch('discount_start_date') || new Date().toISOString().split('T')[0]}
                          {...field}
                          className="h-10 text-sm"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </div>
          )}
        </div>

        {/* Availability Section */}
        <div className="rounded-xl border border-gray-200 bg-white p-5 space-y-4 shadow-sm">
          <h2 className="text-base font-semibold text-gray-900">Availability</h2>

          <div className="space-y-3.5">
            {[
              {
                value: 'in_stock',
                label: 'In Stock',
                description: 'Customers can view and order this item.',
              },
              {
                value: 'out_of_stock',
                label: 'Out of Stock',
                description: 'Customers can view it, but cannot order.',
              },
              {
                value: 'hidden',
                label: 'Hidden',
                description: 'The item is hidden from the customer menu.',
              },
            ].map((option) => {
              const isSelected = (form.watch('availability_status') || 'in_stock') === option.value;
              return (
                <div
                  key={option.value}
                  className="flex items-start gap-3 cursor-pointer select-none"
                  onClick={() => {
                    form.setValue('availability_status', option.value as any);
                  }}
                >
                  <div className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border transition-all duration-150 border-gray-300">
                    {isSelected ? (
                      <div className="h-5 w-5 rounded-full bg-[var(--primary-brand,#FF5200)] flex items-center justify-center">
                        <div className="h-2 w-2 rounded-full bg-white" />
                      </div>
                    ) : (
                      <div className="h-2 w-2 rounded-full bg-gray-300" />
                    )}
                  </div>
                  <div>
                    <span className={cn('text-sm font-semibold block leading-tight', isSelected ? 'text-gray-900' : 'text-gray-800')}>
                      {option.label}
                    </span>
                    <p className="text-xs text-gray-400 mt-1">{option.description}</p>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Recommended Section */}
        <div className="rounded-xl border border-gray-200 bg-white p-5 space-y-4 shadow-sm">
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-base font-semibold text-gray-900">Recommended</h2>
              <p className="text-xs text-gray-500">Mark this item as recommended to feature it prominently to customers</p>
            </div>
            <div className="flex items-center gap-2">
              <span className="text-xs font-medium text-gray-600">
                {form.watch('is_recommend') ? 'Yes' : 'No'}
              </span>
              <div
                className={cn(
                  'relative h-6 w-11 cursor-pointer rounded-full transition-colors duration-200',
                  form.watch('is_recommend') ? 'bg-emerald-500' : 'bg-gray-200'
                )}
                onClick={() => {
                  form.setValue('is_recommend', !form.watch('is_recommend'));
                }}
              >
                <div
                  className={cn(
                    'absolute top-0.5 h-5 w-5 rounded-full bg-white shadow-md transition-all duration-200',
                    form.watch('is_recommend') ? 'left-[22px]' : 'left-0.5'
                  )}
                />
              </div>
            </div>
          </div>
        </div>

        {/* Variants */}
        <div>
          <h2 className="mb-4 text-start text-lg font-medium">
            Variants of Item
          </h2>

          {activeVariant ? (
            <div className="mb-3 rounded-lg border p-2">
              <div className="flex flex-row justify-between">
                <span className="text-[14px] font-[500] capitalize text-[#121212]">
                  {activeVariantKey}
                </span>
                <div
                  className="cursor-pointer"
                  onClick={() => {
                    if (activeVariantKey) {
                      setShowModal((prev) => ({
                        ...prev,
                        [activeVariantKey]: true
                      }));
                      setEditingVariantKey(activeVariantKey);
                    }
                  }}
                >
                  <Pencil color="#FA0909" size={15} />
                </div>
              </div>

              {activeVariantData.map((item: any) => (
                <div
                  className="mt-2 flex flex-row justify-between"
                  key={item.id}
                >
                  <span className="text-[15px] font-[500] text-[#808080]">
                    {item.title || item.name}
                  </span>
                  <span className="text-[15px] font-[500] text-[#808080]">
                    {currency}{item.final_price}
                  </span>
                </div>
              ))}

              <div className="mt-2 flex flex-row justify-end">
                <span
                  className="cursor-pointer text-[12px] font-[500] text-[var(--primary-brand)] hover:text-[var(--primary-brand)]/80 transition-colors"
                  onClick={() => handleRemove(`variants.${activeVariantKey}`)}
                >
                  Remove
                </span>
              </div>
              <ActiveDialog
                open={showModal}
                setOpen={setShowModal}
                onSave={handleModalData}
                price={form.getValues('price')}
                initialData={activeVariantData}
                showTrigger={false}
              />
            </div>
          ) : (
            // If no active variant exists, show all selection dialogs
            (
              Object.keys(variantDialogs) as Array<keyof typeof variantDialogs>
            ).map((key) => {
              const DialogComponent = variantDialogs[key];
              const typedKey = key;
              return (
                <div className="mb-3 rounded-lg border" key={key}>
                  <DialogComponent
                    open={showModal}
                    setOpen={setShowModal}
                    onSave={handleModalData}
                    price={form.getValues('price')}
                    initialData={form.getValues(`variants.${typedKey}` as any)}
                  />
                </div>
              );
            })
          )}
        </div>

        {/* Add-on/Toppings */}
        <div>
          <h2 className="mb-4 text-start text-lg font-medium">
            Add-on/Toppings
          </h2>

          {/* Add-on */}
          {(form.getValues('customization.addons')?.length || 0) > 0 ? (
            <div className="mb-3 rounded-lg border p-2">
              <div className="flex flex-row justify-between">
                <span className="text-[14px] font-[500] text-[#121212]">
                  Add on
                </span>
                <Pencil
                  color="#FA0909"
                  size={15}
                  className="cursor-pointer"
                  onClick={() => {
                    const currentAddons =
                      form.getValues('customization.addons') || [];
                    setEditAddonData(currentAddons);
                    setShowModal((prev) => ({ ...prev, addon: true }));
                  }}
                />
              </div>

              {(form.getValues('customization.addons') || []).map(
                (item: any, index: number) => (
                  <div
                    className="mt-2 flex flex-row justify-between"
                    key={index}
                  >
                    <span className="text-[15px] font-[500] text-[#808080]">
                      {item.title || item?.name}
                    </span>
                    <span className="text-[15px] font-[500] text-[#808080]">
                      {currency}{item.additional_price || item?.price}
                    </span>
                  </div>
                )
              )}

              <div className="mt-2 flex flex-row justify-end">
                <span
                  className="cursor-pointer text-[12px] font-[500] text-[var(--primary-brand)]"
                  onClick={() => {
                    handleRemove('customization.addons');
                  }}
                >
                  Remove
                </span>
              </div>
            </div>
          ) : (
            <div className="mb-3 rounded-lg border">
              <AddonDialog
                open={showModal}
                setOpen={setShowModal}
                onSave={handleCustomModalData}
              />
            </div>
          )}
          {showModal?.addon && (
            <AddonDialog
              open={showModal}
              setOpen={setShowModal}
              onSave={handleCustomModalData}
              initialData={editAddonData}
              showTrigger={false}
            />
          )}

          {/* Toppings */}
          {(form.getValues('customization.toppings')?.length || 0) > 0 ? (
            <div className="mb-3 rounded-lg border p-2">
              <div className="flex flex-row justify-between">
                <span className="text-[14px] font-[500] text-[#121212]">
                  Toppings
                </span>
                <Pencil
                  color="#FA0909"
                  size={15}
                  onClick={() => {
                    const currentAddons =
                      form.getValues('customization.toppings') || [];
                    setEditAddonData1(currentAddons);
                    setShowModal((prev) => ({ ...prev, toppings: true }));
                  }}
                />
              </div>

              {(form.getValues('customization.toppings') || []).map(
                (item: any, index: number) => (
                  <div
                    className="mt-2 flex flex-row justify-between"
                    key={index}
                  >
                    <span className="text-[15px] font-[500] text-[#808080]">
                      {item.title || item?.name}
                    </span>
                    <span className="text-[15px] font-[500] text-[#808080]">
                      {currency}{item.additional_price || item?.price}
                    </span>
                  </div>
                )
              )}
              <div className="mt-2 flex flex-row justify-end">
                <span
                  className="cursor-pointer text-[12px] font-[500] text-[var(--primary-brand)]"
                  onClick={() => {
                    handleRemove('customization.toppings');
                  }}
                >
                  Remove
                </span>
              </div>
            </div>
          ) : (
            <div className="mb-3 rounded-lg border">
              <ToppingsDialog
                open={showModal}
                setOpen={setShowModal}
                onSave={handleCustomModalData}
              />
            </div>
          )}
          {showModal?.toppings && (
            <ToppingsDialog
              open={showModal}
              setOpen={setShowModal}
              onSave={handleCustomModalData}
              initialData={editAddonData1}
              showTrigger={false}
            />
          )}
        </div>

        {/* Customization of Item */}
        <div>
          {((form.watch('customization.custom_groups') || []).length === 0) ? (
            <>
              <h2 className="mb-4 text-start text-lg font-semibold text-gray-900">
                Customization of Item
              </h2>
              <div className="rounded-xl border border-gray-200 bg-white shadow-sm overflow-hidden">
                <button
                  type="button"
                  className="flex w-full items-center justify-between p-4 text-start hover:bg-gray-50/50 transition-colors"
                  onClick={() => {
                    setSelectedGroupIndex(null);
                    setEditingGroupData(null);
                    setShowModal((prev: any) => ({ ...prev, addmore: true }));
                  }}
                >
                  <div>
                    <p className="font-semibold text-gray-900 text-sm sm:text-base">Make your own</p>
                    <p className="text-xs sm:text-sm text-gray-500">
                      Create your own variation if no template fits.
                    </p>
                  </div>
                  <ChevronRight className="h-5 w-5 text-gray-400" />
                </button>
              </div>
            </>
          ) : (
            <>
              <div className="mb-4 flex items-center justify-between">
                <h2 className="text-lg font-semibold text-gray-900">
                  Customization of Item
                </h2>
                <Button
                  type="button"
                  variant="outline"
                  className="h-8 border-[var(--primary-brand)] text-[var(--primary-brand)] hover:bg-[var(--primary-brand)]/5 hover:text-[var(--primary-brand)] font-semibold px-3 text-xs flex items-center gap-1 rounded-lg transition-colors"
                  onClick={() => {
                    setSelectedGroupIndex(null);
                    setEditingGroupData(null);
                    setShowModal((prev: any) => ({ ...prev, addmore: true }));
                  }}
                >
                  <Plus className="h-3.5 w-3.5" /> Add
                </Button>
              </div>

              <div className="rounded-xl border border-gray-200 bg-white p-4 space-y-4 shadow-sm">
                <p className="text-xs font-semibold text-gray-500 uppercase tracking-wider">
                  Customization of Item
                </p>
                {(form.watch('customization.custom_groups') || []).map(
                  (group: any, index: number) => (
                    <div
                      key={index}
                      className="border-b border-gray-100 last:border-b-0 pb-3 last:pb-0 pt-2 first:pt-0"
                    >
                      <div className="flex items-center justify-between mb-2">
                        <span className="font-bold text-gray-900 text-sm capitalize">
                          {group.title}
                        </span>
                        <div className="flex items-center gap-2">
                          <Pencil
                            className="h-4 w-4 text-[var(--primary-brand)] cursor-pointer hover:text-[var(--primary-brand)]/80 transition-colors"
                            onClick={() => handleEditCustomGroup(index)}
                          />
                          <Trash2
                            className="h-4 w-4 text-red-500 cursor-pointer hover:text-red-700 transition-colors"
                            onClick={() => handleDeleteCustomGroup(index)}
                          />
                        </div>
                      </div>
                      <div className="space-y-1.5 pl-1">
                        {(group.options || []).map((opt: any, optIdx: number) => (
                          <div
                            key={optIdx}
                            className="flex items-center justify-between text-xs text-gray-600"
                          >
                            <span>{opt.title || opt.name}</span>
                            <span className="font-semibold text-gray-800">
                              {currency}
                              {opt.additional_price ?? opt.price ?? 0}
                            </span>
                          </div>
                        ))}
                      </div>
                    </div>
                  )
                )}
              </div>
            </>
          )}

          <AddMoreDialog
            open={showModal}
            setOpen={setShowModal}
            onAdd={handleSaveCustomGroup}
            initialData={editingGroupData}
            editingIndex={selectedGroupIndex}
            onDeleteGroup={handleDeleteCustomGroup}
          />
        </div>

        {/* Item Timings */}
        <div>
          <h2 className="mb-4 text-start text-lg font-medium">Item Timings</h2>

          <FormField
            control={form.control}
            name="availability"
            render={({ field }) => (
              <FormItem>
                <FormControl>
                  <RadioGroup
                    onValueChange={(value) => {
                      field.onChange(value); // Update form state
                      // If you want to update external state or API after selection:
                      // saveAvailabilityToAPI(value);
                    }}
                    value={field.value} // Ensure form value is properly bound
                    className="flex flex-col space-y-3"
                  >
                    <div className="flex items-start space-x-2">
                      <RadioGroupItem
                        value="all_time"
                        id="all_time"
                        className={
                          field.value !== 'all_time' ? 'border-[#808080]' : ''
                        }
                      />
                      <label
                        htmlFor="all_time"
                        className={
                          field.value === 'all_time'
                            ? `text-[16px] text-[#121212]`
                            : 'text-[16px] text-[#808080]'
                        }
                      >
                        Item is available at all times when kitchen /
                        restaurants is open.
                      </label>
                    </div>
                    <div className="flex flex-col gap-2">
                      <div className="flex items-start space-x-2">
                        <RadioGroupItem
                          value="same_time"
                          id="same_time"
                          className={
                            field.value !== 'same_time'
                              ? 'border-[#808080]'
                              : ''
                          }
                        />
                        <label
                          htmlFor="same_time"
                          className={
                            field.value === 'same_time'
                              ? `text-[16px] text-[#121212]`
                              : 'text-[16px] text-[#808080]'
                          }
                        >
                          Item is available at the same time for all days of the
                          week.
                        </label>
                      </div>
                      {field.value === 'same_time' && (
                        <div className="flex h-[54px] w-full flex-row items-center justify-around">
                          <Select
                            value={slot.start}
                            onValueChange={(value) =>
                              updateTimeSloted('start', value)
                            }
                          >
                            <SelectTrigger className="w-60">
                              <SelectValue placeholder="Start Time" />
                            </SelectTrigger>
                            <SelectContent className="h-[30vh]">
                              {timeSlots?.map((time) => (
                                <SelectItem key={time} value={time}>
                                  {time}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                          <Select
                            value={slot.end}
                            onValueChange={(value) =>
                              updateTimeSloted('end', value)
                            }
                          >
                            <SelectTrigger className="w-60">
                              <SelectValue placeholder="End Time" />
                            </SelectTrigger>
                            <SelectContent className="h-[30vh]">
                              {timeSlots?.map((time) => (
                                <SelectItem key={time} value={time}>
                                  {time}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                      )}
                    </div>

                    <div className="flex flex-col gap-2">
                      <div className="flex items-start space-x-2">
                        <RadioGroupItem
                          value="different_time"
                          id="different_time"
                          className={
                            field.value !== 'different_time'
                              ? 'border-[#808080]'
                              : ''
                          }
                        />
                        <label
                          htmlFor="different_time"
                          className={
                            field.value === 'different_time'
                              ? `text-[16px] text-[#121212]`
                              : 'text-[16px] text-[#808080]'
                          }
                        >
                          Item is available at different times for all days of the
                          week.
                        </label>
                      </div>
                      {field.value === 'different_time' && (
                        <div className="mt-2 ml-6 p-4 bg-gray-50 rounded-xl border border-gray-100 space-y-3 max-w-[500px]">
                          <div className="flex items-center justify-between">
                            <span className="text-sm font-semibold text-gray-700">Configured Timings</span>
                            <Button
                              type="button"
                              variant="outline"
                              size="sm"
                              className="text-[var(--primary-brand)] border-[var(--primary-brand)] hover:bg-[var(--primary-brand)]/5 font-medium flex items-center gap-1.5 rounded-lg px-3 py-1"
                              onClick={() => setIsOpen(true)}
                            >
                              <Pencil className="w-3.5 h-3.5" />
                              Edit Timings
                            </Button>
                          </div>

                          <div className="grid grid-cols-2 gap-2 text-xs">
                            {daysOfWeek.map((day) => {
                              const settings = daySettings[day];
                              const slot = settings?.slots?.[0];
                              const timeStr = slot ? `${slot.startTime} - ${slot.endTime}` : '09:00 - 22:00';
                              return (
                                <div key={day} className="flex justify-between items-center py-1 border-b border-gray-100/50 last:border-0">
                                  <span className="font-medium text-gray-500">{day}</span>
                                  <span className="font-semibold text-gray-700">{timeStr}</span>
                                </div>
                              );
                            })}
                          </div>
                        </div>
                      )}
                    </div>
                  </RadioGroup>
                </FormControl>
              </FormItem>
            )}
          />
        </div>

        {/* <Button
        // type="submit"
        // onClick={() => router.push(`/auth/restaurant/itemtimings`)}
        className="w-full bg-[#6030f4] text-black hover:bg-[#6030f4]"
      >
        Save
      </Button> */}
      </form>
      <Dialog open={isOpen} onOpenChange={() => setIsOpen(false)}>
        <DialogContent className="max-w-[500px] p-0 border-0 bg-white rounded-[24px] shadow-2xl overflow-hidden focus:outline-none">
          <div className="px-6 pt-6 pb-4 border-b border-gray-100 flex items-center justify-between">
            <h2 className="text-[20px] font-bold text-gray-900">Configure Item Timings</h2>
          </div>
          <div className="no-scrollbar p-6 h-[65vh] space-y-4 overflow-y-auto bg-gray-50/50 pb-24">
            {daysOfWeek.map((day) => (
              <div
                key={day}
                className={cn(
                  "rounded-2xl border transition-all duration-200 overflow-hidden",
                  expandedDays.includes(day)
                    ? "border-[var(--primary-brand)]/20 shadow-md shadow-[var(--orange-100)]/30"
                    : "border-gray-100 hover:border-gray-200"
                )}
              >
                <div
                  className={cn(
                    "flex cursor-pointer items-center justify-between p-4 font-semibold transition-colors duration-200",
                    expandedDays.includes(day)
                      ? "bg-[var(--orange-50)]/40 text-[var(--primary-brand)] border-l-4 border-l-[var(--primary-brand)]"
                      : "bg-white text-gray-700 hover:bg-gray-50"
                  )}
                  onClick={() => toggleDay(day)}
                >
                  <span className="text-sm font-bold">{day}</span>
                  {expandedDays.includes(day) ? (
                    <ChevronUp className="h-5 w-5 opacity-70" />
                  ) : (
                    <ChevronDown className="h-5 w-5 opacity-40" />
                  )}
                </div>

                {expandedDays.includes(day) && (
                  <div className="space-y-4 border-t border-gray-100 p-4 bg-white">
                    {daySettings[day].slots.map((slot, index) => (
                      <div key={index} className="flex items-center gap-4">
                        <div className="flex flex-col gap-1.5 flex-1">
                          <span className="text-[12px] font-semibold text-gray-400">Start Time</span>
                          <Select
                            value={slot.startTime}
                            onValueChange={(value) =>
                              updateTimeSlot({
                                day,
                                index,
                                field: 'startTime',
                                value
                              })
                            }
                          >
                            <SelectTrigger className="w-full h-11 rounded-xl border-gray-200">
                              <SelectValue placeholder="Start Time" />
                            </SelectTrigger>
                            <SelectContent className="h-[30vh]">
                              {timeSlots.map((time) => (
                                <SelectItem key={time} value={time}>
                                  {time}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>

                        <div className="text-gray-400 mt-5 font-medium">to</div>

                        <div className="flex flex-col gap-1.5 flex-1">
                          <span className="text-[12px] font-semibold text-gray-400">End Time</span>
                          <Select
                            value={slot.endTime}
                            onValueChange={(value) =>
                              updateTimeSlot({
                                day,
                                index,
                                field: 'endTime',
                                value
                              })
                            }
                          >
                            <SelectTrigger className="w-full h-11 rounded-xl border-gray-200">
                              <SelectValue placeholder="End Time" />
                            </SelectTrigger>
                            <SelectContent className="h-[30vh]">
                              {timeSlots.map((time) => (
                                <SelectItem key={time} value={time}>
                                  {time}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                      </div>
                    ))}

                    {day === 'Monday' && (
                      <div className="flex items-center gap-2.5 pt-2 border-t border-gray-50 mt-4">
                        <Checkbox
                          id="copyAll"
                          checked={copyToAll}
                          onCheckedChange={handleCopyToAllChange}
                          className="h-5 w-5 border-gray-300 rounded-md data-[state=checked]:bg-[var(--primary-brand)] data-[state=checked]:border-[var(--primary-brand)]"
                        />
                        <label
                          htmlFor="copyAll"
                          className="text-sm font-medium text-gray-500 cursor-pointer select-none"
                        >
                          Copy above timings for all days
                        </label>
                      </div>
                    )}
                  </div>
                )}
              </div>
            ))}
          </div>

          <div className="absolute bottom-0 left-0 right-0 p-4 bg-white/90 backdrop-blur-sm border-t border-gray-100">
            <Button
              className="w-full py-6 text-[16px] font-semibold text-white bg-[var(--primary-brand)] hover:opacity-90 rounded-2xl shadow-lg shadow-[var(--orange-100)]/30 transition-all duration-200"
              variant={'theme'}
              onClick={handleSave}
            >
              Save Timings
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </Form>
  );
});

export default EditItem;
