'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 } 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 } 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 } from '@/lib/utils';

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

let itemTiming: ItemTiming[] = [];

const menuItemSchema = z.object({
  food_type: z.enum(['veg', 'non_veg', 'egg'], {
    required_error: 'Please select a category'
  }),

  // 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'),

  // 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()
});

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>;

function EditItem({ data, onFormUpdate }: { data: any; onFormUpdate: any }) {
  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();
  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),
    defaultValues: {
      // category_id: "",
      food_type: undefined,
      name: '',
      image: [],
      price: undefined,
      itemDescription: '',
      variants: {
        quantity: [],
        size: [],
        pieces: []
      },
      customization: {
        addons: [],
        toppings: [],
      },
      availability: undefined,
      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')]);

  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.discounted_price ? data.discounted_price : data.price,
        itemDescription: data.description,
        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,
            price: Number(item.additional_price || 0),
            isCompulsory: item.customer_selection === "compulsory",
          })) || [],
          toppings: data?.toppings?.map((item: any, index: number) => ({
            id: index + 1,
            name: item.title,
            price: Number(item.additional_price || 0),
            isCompulsory: item.customer_selection === "compulsory",
          })) || [],
          ...Object.fromEntries(
            (data?.other_add_ons || []).map((addon: any) => [
              addon.title,
              addon.options.map((opt: any, idx: number) => ({
                id: idx + 1,
                name: opt.title,
                price: Number(opt.additional_price || 0),
                isCompulsory: opt.customer_selection === "compulsory"
              }))
            ])
          )
        },
        availability: data.availability_type
      });
      // if(data?.data.availability_type==="different_time"){
      //   setIsOpen(true)
      // }
    }
  }, [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,
      quantity: updatedData?.variants?.quantity,
      size: updatedData?.variants?.size,
      pieces: updatedData?.variants?.pieces,
      add_ons: updatedData?.customization?.addons,
      toppings: updatedData?.customization?.toppings,
      other_add_ons: Object.entries(updatedData?.customization || {})
        .filter(([key]) => !['addons', 'toppings', 'custom'].includes(key))
        .map(([key, options]: [string, any]) => ({
          title: key,
          options: options.map((opt: any) => ({
            title: opt.name,
            additional_price: opt.price,
            customer_selection: opt.isCompulsory ? 'compulsory' : 'optional'
          }))
        })),
      availability_type: updatedData?.availability,
      item_timing: itemTiming,
      category_id: catId,
      _id: foodId
    };
  };

  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 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-[#a08ed4]'
                          : '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>

        {/* 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>
          <h2 className="mb-4 text-start text-lg font-medium">
            Customization of Item
          </h2>
          {Object.entries(form.watch('customization') || {})
            .filter(
              ([key, value]) =>
                !['addons', 'toppings', 'custom'].includes(key) &&
                Array.isArray(value) &&
                value.length > 0
            )
            .map(([key, value]: [string, any]) => (
              <div key={key} className="mb-3 rounded-lg border p-2">
                <div className="flex flex-row justify-between">
                  <span className="text-[14px] font-[500] capitalize text-[#121212]">
                    {key}
                  </span>
                  <div
                    className="cursor-pointer"
                    onClick={() =>
                      setShowModal((prev) => ({ ...prev, [key]: true }))
                    }
                  >
                    <Pencil color="#FA0909" size={15} />
                  </div>
                </div>

                {value.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)] hover:text-[var(--primary-brand)]/80 transition-colors"
                    onClick={() => handleRemove(`customization.${key}`)}
                  >
                    Remove
                  </span>
                </div>
                <CustomAddOn
                  title={key}
                  open={showModal}
                  setOpen={setShowModal}
                  onSave={handleCustomModalData}
                  initialData={value}
                  showTrigger={false}
                />
              </div>
            ))}

          <div className="rounded-lg border">
            <AddMoreDialog
              open={showModal}
              setOpen={setShowModal}
              onAdd={handleSection}
            />
          </div>
        </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;
