'use client';

import React, { useState, useEffect, useRef } from 'react';

import DashboardLayout from '@/app/dashboard/layout';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Plus, Percent, Tag } from 'lucide-react';
import { useGlobalContext } from '@/context/Provider';
import dynamic from 'next/dynamic';
import 'react-quill/dist/quill.snow.css';
import apis from '@/utils/apis';
import { cn, currency, formatDateStringToUTC } from '@/lib/utils';


const ReactQuill = dynamic(() => import('react-quill'), {
  ssr: false,
  loading: () => <div className="h-[150px] w-full bg-gray-50 animate-pulse rounded-xl border border-gray-100" />
});

const grocerySchema = z.object({
  name: z.string().min(2, 'Name is required'),
  category: z.string().min(2, 'Category is required'),
  stock: z.coerce.number().min(0, 'Stock must be non-negative').max(99999, 'Stock cannot exceed 5 digits'),
  quantity: z.coerce.number().min(0, 'Quantity must be non-negative').max(99999, 'Quantity cannot exceed 5 digits'),
  unit: z.string().min(1, 'Unit is required'),
  price: z.coerce.number().min(0, 'Price must be non-negative').max(99999, 'Price cannot exceed 5 digits'),
  description: z.string().optional(),
  image: z.any().optional(),
  barcode_id: z.string().optional(),
  availability_status: z.enum(['in_stock', 'out_of_stock', 'hidden']).optional(),
  // 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(),
}).superRefine((data, ctx) => {
  if (data.is_discount_active) {
    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 (startNorm && startNorm < todayStr) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: 'Start date cannot be in the past',
        path: ['discount_start_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']
      });
    }
  }
});

type GroceryValues = z.infer<typeof grocerySchema>;


export default function AddGroceryPage() {
  const { userInfo, Toast } = useGlobalContext();
  const rawType = userInfo?.restaurant_id?.type || 'grocery';
  const typeLabel = rawType === 'food' ? 'Grocery' : rawType.charAt(0).toUpperCase() + rawType.slice(1);
  const router = useRouter();

  const fileInputRef = useRef<HTMLInputElement>(null);
  const [previewImage, setPreviewImage] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [allCategories, setAllCategories] = useState<any[]>([]);

  const form = useForm<GroceryValues>({
    resolver: zodResolver(grocerySchema),
    mode: 'onChange',
    defaultValues: {
      name: '',
      category: '',
      stock: 0,
      quantity: 0,
      unit: '',
      price: 0,
      description: '',
      barcode_id: '',
      availability_status: 'in_stock',
      is_discount_active: false,
      discount_type: 'percentage',
      discount_value: undefined,
      discounted_price: undefined,
      discount_start_date: '',
      discount_end_date: '',
    },
  });

  const fetchCategories = async () => {
    try {
      const res = await apis.category.get();
      if (res?.data) {
        setAllCategories(res.data);
      }
    } catch (error) {
      console.error('Error fetching categories:', error);
    }
  };

  useEffect(() => {
    fetchCategories();
  }, []);

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

  const barcodeRef = React.useRef<string>('');
  const lastKeyTimeRef = React.useRef<number>(0);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Shift' || e.key === 'Control' || e.key === 'Alt' || e.key === 'Meta') {
        return;
      }

      const activeElement = document.activeElement;
      const isInput = activeElement && (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA');

      if (activeElement && (activeElement as HTMLInputElement).placeholder === 'Barcode ID') {
        return;
      }

      if (isInput) {
        return;
      }

      const currentTime = Date.now();
      if (currentTime - lastKeyTimeRef.current > 50) {
        barcodeRef.current = '';
      }
      lastKeyTimeRef.current = currentTime;

      if (e.key === 'Enter') {
        if (barcodeRef.current.length > 2) {
          e.preventDefault();
          e.stopPropagation();
          form.setValue('barcode_id', barcodeRef.current);
          barcodeRef.current = '';
          Toast.success('Barcode scanned successfully');
        }
      } else {
        if (e.key.length === 1) {
          barcodeRef.current += e.key;
        }
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [form, Toast]);

  const onImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        setPreviewImage(reader.result as string);
        form.setValue('image', file);
      };
      reader.readAsDataURL(file);
    }
  };

  const onSubmit = async (values: GroceryValues) => {
    setIsSubmitting(true);
    try {
      let imageUrl = '';

      if (values.image instanceof File) {
        const uploadRes = await apis.Common.uploadSingle('file', values.image);
        if (uploadRes?.key) {
          imageUrl = uploadRes.key;
        }
      }

      let category_id = '';
      const selectedCat = allCategories.find(c => c.category_name === values.category);
      if (selectedCat) {
        category_id = selectedCat._id;
      }

      const availabilityStatus = values.availability_status || 'in_stock';

      const payload = {
        type: rawType,
        category_id,
        name: values.name,
        description: values.description,
        quantity: values.quantity.toString(),
        unit: values.unit,
        price: values.price,
        imageUrl,
        stock: values.stock,
        barcode_id: values.barcode_id || '',
        is_available: availabilityStatus === 'in_stock',
        availability_status: availabilityStatus,
        is_hidden: availabilityStatus === 'hidden',
        discounted_price: values.is_discount_active ? values.discounted_price : null,
        discount_type: values.is_discount_active ? (values.discount_type || 'percentage') : null,
        discount_value: values.is_discount_active ? values.discount_value : null,
        discount_start_date: values.is_discount_active && values.discount_start_date ? formatDateStringToUTC(values.discount_start_date, false) : null,
        discount_end_date: values.is_discount_active && values.discount_end_date ? formatDateStringToUTC(values.discount_end_date, true) : null,
        is_discount_active: Boolean(values.is_discount_active),
      };

      const res = await apis.Item.add(payload);
      if (res?.success) {
        Toast.success(res.message || `${typeLabel} item added successfully`);
        router.push('/grocery');
      } else {
        Toast.error(res?.message || 'Failed to add item');
      }
    } catch (error: any) {
      Toast.error(error || `Error adding ${typeLabel.toLowerCase()} item`);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <DashboardLayout>
      <main className="flex-1 bg-gray-50 p-6 overflow-y-auto">
        <div className="w-full max-w-4xl mx-auto bg-white rounded-3xl shadow-sm border border-gray-100 p-8">
          <h1 className="text-2xl font-bold mb-8">Add {typeLabel} Item</h1>

          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
              <div className="space-y-3">
                <label className="text-sm font-medium text-gray-700">{typeLabel} Image</label>
                <input
                  type="file"
                  ref={fileInputRef}
                  className="hidden"
                  accept="image/*"
                  onChange={onImageChange}
                />
                <div
                  className="w-28 h-28 rounded-2xl border-2 border-dashed border-gray-200 flex flex-col items-center justify-center cursor-pointer hover:border-gray-300 transition-all bg-[#F9FAFB] overflow-hidden"
                  onClick={() => fileInputRef.current?.click()}
                >
                  {previewImage ? (
                    <img src={previewImage} alt="Preview" className="w-full h-full object-cover" />
                  ) : (
                    <>
                      <Plus className="w-7 h-7 text-gray-400 mb-1" />
                      <span className="text-[10px] font-semibold text-gray-400">Upload</span>
                    </>
                  )}
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Name <span className="text-red-500">*</span></FormLabel>
                      <FormControl>
                        <Input placeholder={`${typeLabel} Name`} {...field} className="h-11 bg-[#F9FAFB] border-gray-100 rounded-xl" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="category"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Category <span className="text-red-500">*</span></FormLabel>
                      <FormControl>
                        <select
                          {...field}
                          className="h-11 w-full bg-[#F9FAFB] border border-gray-100 rounded-xl px-3 text-sm focus:outline-none"
                        >
                          <option value="">Select Category</option>
                          {allCategories.map((cat, index) => {
                            const name = cat.category_name || cat.name || 'Unnamed';
                            return (
                              <option key={cat._id || index} value={name}>
                                {name}
                              </option>
                            );
                          })}
                        </select>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="stock"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Stock <span className="text-red-500">*</span></FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          placeholder="Stock"
                          {...field}
                          onChange={(e) => {
                            const value = e.target.value;
                            if (value.length <= 5) {
                              field.onChange(e);
                            }
                          }}
                          className="h-11 bg-[#F9FAFB] border-gray-100 rounded-xl"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <FormField
                  control={form.control}
                  name="quantity"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Quantity <span className="text-red-500">*</span></FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          placeholder="Quantity"
                          {...field}
                          onChange={(e) => {
                            const value = e.target.value;
                            if (value.length <= 5) {
                              field.onChange(e);
                            }
                          }}
                          className="h-11 bg-[#F9FAFB] border-gray-100 rounded-xl"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="unit"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Unit <span className="text-red-500">*</span></FormLabel>
                      <FormControl>
                        <Input placeholder="Unit" {...field} className="h-11 bg-[#F9FAFB] border-gray-100 rounded-xl" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="price"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Price <span className="text-red-500">*</span></FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          placeholder="Price"
                          {...field}
                          onChange={(e) => {
                            const value = e.target.value;
                            if (value.length <= 5) {
                              field.onChange(e);
                            }
                          }}
                          className="h-11 bg-[#F9FAFB] border-gray-100 rounded-xl"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <FormField
                  control={form.control}
                  name="barcode_id"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Barcode ID</FormLabel>
                      <FormControl>
                        <Input placeholder="Barcode ID" {...field} className="h-11 bg-[#F9FAFB] border-gray-100 rounded-xl" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <FormField
                control={form.control}
                name="description"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Description</FormLabel>
                    <FormControl>
                      <div onKeyDownCapture={(e) => e.stopPropagation()}>
                        <ReactQuill
                          theme="snow"
                          defaultValue={field.value || ''}
                          onChange={(content) => field.onChange(content)}
                          modules={{
                            toolbar: [
                              [{ header: [1, 2, false] }],
                              ['bold', 'italic', 'underline', 'strike'],
                              [{ list: 'ordered' }, { list: 'bullet' }],
                              ['link', 'clean'],
                            ],
                          }}
                          className="bg-[#F9FAFB] rounded-xl overflow-hidden"
                          placeholder="Description"
                        />
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Availability Section */}
              <div className="rounded-2xl border border-gray-100 bg-[#F9FAFB] p-5 space-y-4">
                <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 bg-white">
                          {isSelected ? (
                            <div className="h-5 w-5 rounded-full bg-[var(--primary-brand)] 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>

              {/* Item Discount Section */}
              <div className="rounded-2xl border border-gray-100 bg-[#F9FAFB] p-5 space-y-4">
                <div className="flex items-center justify-between border-b pb-3 border-gray-200">
                  <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-[var(--primary-brand)]' : '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-xl border text-sm font-medium transition-all bg-white',
                          (form.watch('discount_type') || 'percentage') === 'percentage'
                            ? 'border-[var(--primary-brand)] bg-orange-50 text-[var(--primary-brand)] font-semibold shadow-sm'
                            : 'border-gray-200 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-xl border text-sm font-medium transition-all bg-white',
                          form.watch('discount_type') === 'fixed'
                            ? 'border-[var(--primary-brand)] bg-orange-50 text-[var(--primary-brand)] font-semibold shadow-sm'
                            : 'border-gray-200 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}
                                  onChange={(e) => {
                                    field.onChange(e);
                                    const currentPrice = Number(form.getValues('price')) || 0;
                                    const val = Number(e.target.value) || 0;
                                    const discType = form.getValues('discount_type') || 'percentage';
                                    let calcDiscounted = currentPrice;
                                    if (discType === 'percentage') {
                                      calcDiscounted = Math.max(0, currentPrice - (currentPrice * (val / 100)));
                                    } else {
                                      calcDiscounted = Math.max(0, currentPrice - val);
                                    }
                                    form.setValue('discounted_price', val > 0 ? Number(calcDiscounted.toFixed(2)) : undefined);
                                  }}
                                  className="h-10 text-sm bg-white border-gray-100 rounded-xl"
                                />
                                <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-white border border-gray-200 rounded-xl 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-[var(--primary-brand)]">
                              {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-orange-100 text-[var(--primary-brand)] 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"
                                min={new Date().toISOString().split('T')[0]}
                                {...field}
                                className="h-10 text-sm bg-white border-gray-100 rounded-xl"
                              />
                            </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 bg-white border-gray-100 rounded-xl"
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>
                  </div>
                )}
              </div>

              <div className="flex gap-4 pt-4">
                <Button
                  type="submit"
                  variant="theme"
                  className="flex-1 h-11 rounded-xl text-base font-semibold"
                  disabled={isSubmitting}
                >
                  {isSubmitting ? 'Adding...' : `Add ${typeLabel}`}
                </Button>
                <Button
                  type="button"
                  variant="outline"
                  className="flex-1 h-11 rounded-xl text-base font-semibold border-gray-200"
                  onClick={() => router.push('/grocery')}
                >
                  Cancel
                </Button>
              </div>
            </form>
          </Form>
        </div>
      </main>
    </DashboardLayout>
  );
}
