'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, ChevronUp, Pencil } from 'lucide-react';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { MultiImages } from '@/components/common/MultipleDropzone';
// import QuantityDialog from '@/app/auth/restaurant/itemdetails/variantsmodals/QuantityModal';
import { useEffect, useState } 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, useSearchParams } from 'next/navigation';
import QuantityDialog from './variantsmodals/QuantityModal';
import PiecesDialog from './variantsmodals/PiecesModal';
import SizeDialog from './variantsmodals/SizeModal';
import apis from '@/utils/apis';
import { cn, currency } from '@/lib/utils';
import { useGlobalContext } from '@/context/Provider';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { Checkbox } from '@/components/ui/checkbox';

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

  // 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 AddItem({
  selectedItem,
  setShowAdd,
  handleAddData
}: {
  selectedItem: any;
  setShowAdd: any;
  handleAddData: any;
}) {
  const daysOfWeek = [
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday',
    'Sunday'
  ];
  const { Toast, userInfo } = useGlobalContext();
  const timeSlots = generateTimeSlots();
  const router = useRouter();
  const [recommanded, setRecommanded] = useState(false);
  const [isOpen, setIsOpen] = useState(false);
  const [itemTime, setItemTime] = useState<any>(null);
  const [slot, setSlot] = useState<{
    start: string | undefined;
    end: string | undefined;
  }>({
    start: undefined,
    end: undefined
  });
  const [showModal, setShowModal] = useState({
    quantity: false,
    size: false,
    pieces: false,
    addon: false,
    toppings: false,
    addmore: false
  });
  const [expandedDays, setExpandedDays] = useState(['Monday']);
  const [daySettings, setDaySettings] = useState<DaySettingsState>(
    daysOfWeek.reduce(
      (acc, day) => ({
        ...acc,
        [day]: {
          enabled: day === 'Monday',
          slots: [{ startTime: '09:00', endTime: '22:00' }]
        }
      }),
      {} as DaySettingsState
    )
  );
  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: [],
        custom: []
      },
      availability: undefined,
      timing: []
    }
  });

  const isFoodCategory =
    userInfo?.restaurant_id?.type === 'food';

  const [isSubmitting, setIsSubmitting] = useState(false);

  const onSubmit = async (data: MenuItemFormValues) => {
    if (isSubmitting) return;
    if (isFoodCategory && !data.food_type) {
      Toast.error('Please select a sub category (Veg / non_veg / Egg)');
      return;
    }

    let resId: any = userInfo?.restaurant_id?._id;
    setIsSubmitting(true);
    try {
      let payload: any = {
        category_id: selectedItem?._id,
        image: data?.image?.map((img: any) => img?.url) || [],
        name: data?.name,
        price: data?.price,
        food_type: data?.food_type,
        add_ons:
          data?.customization?.addons?.map((addOn) => ({
            title: addOn.name || addOn.title,
            additional_price: addOn.price,
            customer_selection: addOn.isCompulsory ? 'compulsory' : 'optional'
          })) || [],
        toppings:
          data?.customization?.toppings?.map((topping) => ({
            title: topping.name || topping.title,
            additional_price: topping.price,
            customer_selection: topping.isCompulsory ? 'compulsory' : 'optional'
          })) || [],
        // "other_add_ons": data?.image,
        pieces:
          data?.variants?.pieces?.map((piece) => ({
            title: piece.name || piece.title,
            add_price: piece.additionalPrice,
            final_price: piece.finalPrice
          })) || [],
        size:
          data?.variants?.size?.map((size) => ({
            title: size.name || size.title,
            add_price: size.additionalPrice,
            final_price: size.finalPrice
          })) || [],
        quantity:
          data?.variants?.quantity?.map((quant) => ({
            title: quant.name || quant.title,
            add_price: quant.additionalPrice,
            final_price: quant.finalPrice
          })) || [],
        description: data?.itemDescription,
        availability_type: data?.availability,
        is_recommend: recommanded,
        other_add_ons: Object.entries(data.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'
            }))
          }))
      };
      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 (data?.availability === 'same_time') {
        payload.item_timing = daysOfWeekWithIds.map((d) => ({
          ...d,
          start_time: formatDateTime(slot.start || '09:00'),
          end_time: formatDateTime(slot.end || '22:00')
        }));
      } else if (data?.availability === 'different_time') {
        payload.item_timing = 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 {
        payload.item_timing = [];
      }

      const apiRes: any = await apis.Food.add(payload, resId);
      const response = apiRes?.data;
      if (response) {
        setShowAdd(false);
        handleAddData(true);
      }
    } catch (error) {
      console.error('error:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  useEffect(() => {
    let token: any = sessionStorage.getItem('token');
    if (!token) {
      router.replace(`/auth/login`);
    }
  }, []);

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

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

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

    form.setValue('customization', {
      ...currentCustomization,
      [data.name]: data.options || []
    });
  };

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

  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 updateTimeSloted = (type: 'start' | 'end', data: string) => {
    setSlot((prevSlot) => ({
      ...prevSlot,
      [type]: data
    }));
  };

  const handleRemove = (type: any) => {
    if (type.startsWith('customization.')) {
      const key = type.split('.')[1];
      if (!['addons', 'toppings', 'custom'].includes(key)) {
        const current = form.getValues('customization');
        const updated = { ...current };
        delete (updated as any)[key];
        form.setValue('customization', updated);
        return;
      }
    }
    form.setValue(`${type}` as keyof MenuItemFormValues, []);
    form.trigger(`${type}` as keyof MenuItemFormValues);
  };

  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: Record<string, any> = {
    quantity: QuantityDialog,
    size: SizeDialog,
    pieces: PiecesDialog
  };

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

  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' }
    ];
    let formattedData: { day: string; start_time: string; end_time: string }[] =
      [];
    const formatDateTime = (time: string) => `2024-01-01T${time}:00.000Z`;

    if (form.getValues('availability') === 'different_time') {
      formattedData = daysOfWeek.map((day) => ({
        day,
        start_time: formatDateTime(daySettings[day]?.slots[0]?.startTime),
        end_time: formatDateTime(daySettings[day]?.slots[0]?.endTime)
      }));
    } else if (form.getValues('availability') === 'same_time') {
      formattedData = [
        {
          day: 'all_days',
          start_time: slot.start!,
          end_time: slot.end!
        }
      ];
    }

    setItemTime(formattedData);

    setIsOpen(false);
  };
  return (
    <Form {...form}>
      <form
        onSubmit={form.handleSubmit(onSubmit, (errors) => {
          if (errors.food_type) {
            Toast.error(errors.food_type.message);
          }
        })}
        className="flex-1 overflow-y-auto no-scrollbar space-y-6 pr-1 pb-6"
      >
        {/* Category Selection */}
        {isFoodCategory && (
          <div className="flex gap-2">
            <FormField
              control={form.control}
              name="food_type"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Sub category</FormLabel>
                  <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-yellow-500 bg-yellow-100'
                          : 'border-gray-200'
                          }`}
                        onClick={() => field.onChange('egg')}
                      >
                        <Icons.EggIcon />
                        <span className={field.value === 'egg' ? 'text-yellow-600' : 'text-gray-600'}>
                          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}
                      maxLength={30}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

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

            <FormField
              control={form.control}
              name="itemDescription"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Item Description</FormLabel>
                  <FormControl>
                    <Textarea
                      placeholder="Enter item description...."
                      {...field}
                      maxLength={120}
                    />
                  </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>

          {/* If an active variant exists, render it */}
          {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={() =>
                    setShowModal({
                      ...showModal,
                      [activeVariantKey as string]: true
                    })
                  }
                >
                  <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.name || item.title}
                  </span>
                  <span className="text-[15px] font-[500] text-[#808080]">
                    {currency}{item.finalPrice}
                  </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(`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).map((key) => {
              const DialogComponent =
                variantDialogs[key as keyof typeof variantDialogs];
              return (
                <div className="mb-3 rounded-lg border" key={key}>
                  <DialogComponent
                    open={showModal}
                    setOpen={setShowModal}
                    onSave={handleModalData}
                    price={form.getValues('price')}
                  />
                </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>
                <div
                  className="cursor-pointer"
                  onClick={() => setShowModal({ ...showModal, addon: true })}
                >
                  <Pencil color="#FA0909" size={15} />
                </div>
              </div>

              {(form.getValues('customization.addons') || []).map(
                (item: any) => (
                  <div
                    className="mt-2 flex flex-row justify-between"
                    key={item.id}
                  >
                    <span className="text-[15px] font-[500] text-[#808080]">
                      {item.name}
                    </span>
                    <span className="text-[15px] font-[500] text-[#808080]">
                      {currency}{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>
              <AddonDialog
                open={showModal}
                setOpen={setShowModal}
                onSave={handleCustomModalData}
                initialData={form.getValues('customization.addons')}
                showTrigger={false}
              />
            </div>
          ) : (
            <div className="mb-3 rounded-lg border">
              <AddonDialog
                open={showModal}
                setOpen={setShowModal}
                onSave={handleCustomModalData}
              />
            </div>
          )}

          {/* 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>
                <div
                  className="cursor-pointer"
                  onClick={() => setShowModal({ ...showModal, toppings: true })}
                >
                  <Pencil color="#FA0909" size={15} />
                </div>
              </div>

              {(form.getValues('customization.toppings') || []).map(
                (item: any) => (
                  <div
                    className="mt-2 flex flex-row justify-between"
                    key={item.id}
                  >
                    <span className="text-[15px] font-[500] text-[#808080]">
                      {item.name}
                    </span>
                    <span className="text-[15px] font-[500] text-[#808080]">
                      {currency}{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>
              <ToppingsDialog
                open={showModal}
                setOpen={setShowModal}
                onSave={handleCustomModalData}
                initialData={form.getValues('customization.toppings')}
                showTrigger={false}
              />
            </div>
          ) : (
            <div className="mb-3 rounded-lg border">
              <ToppingsDialog
                open={showModal}
                setOpen={setShowModal}
                onSave={handleCustomModalData}
              />
            </div>
          )}
        </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]) => !['addons', 'toppings', 'custom'].includes(key))
            .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) => (
                  <div
                    className="mt-2 flex flex-row justify-between"
                    key={item.id}
                  >
                    <span className="text-[15px] font-[500] text-[#808080]">
                      {item.name}
                    </span>
                    <span className="text-[15px] font-[500] text-[#808080]">
                      {currency}{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.${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={field.onChange}
                    defaultValue={field.value}
                    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="always"
                        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 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 time 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>

        <div className="flex flex-row justify-between">
          <span>Recommended</span>
          <div
            className={cn(
              'relative h-6 w-12 cursor-pointer rounded-full',
              recommanded ? 'bg-green-500' : 'bg-gray-200'
            )}
            onClick={() => setRecommanded(!recommanded)}
          >
            <div
              className={cn(
                'absolute top-0.5 h-5 w-5 rounded-full bg-white transition-all',
                recommanded ? 'left-[26px]' : 'left-0.5'
              )}
            />
          </div>
        </div>

        <Button
          type="submit"
          className="w-full"
          variant={'theme'}
          disabled={isSubmitting}
        >
          {isSubmitting ? 'Saving...' : '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 AddItem;
