'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 { useEffect, useRef, useState } from 'react';
import { Camera } from 'lucide-react';
import apis, { BUCKET_ROOT } from '@/utils/apis';
import { useGlobalContext } from '@/context/Provider';
import { useRouter } from 'next/navigation';
import Loader from '@/components/common/loader';
import { Checkbox } from '@/components/ui/checkbox';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import countries from '@/utils/CountryCode.json';
import { Label } from '@/components/ui/label';
import {
  InputOTP,
  InputOTPGroup,
  InputOTPSlot
} from '@/components/ui/input-otp';
import { jwtDecode } from 'jwt-decode';
import { Icons } from '@/components/icons';
import CountryPickerModal from '@/components/countrycode/page';
import { MultiImages } from '@/components/common/MultipleDropzone';
import { APP_CLIENT_INTERNALS } from 'next/dist/shared/lib/constants';

type Cuisine = {
  _id: string;
  name: string;
};

const formSchema = z.object({
  name: z.string().min(3, 'Name is required'),
  owner_name: z.string().min(3, 'Owner name is required'),
  avg_prepare: z.union([
    z.number().positive('Time must be greater than 0'),
    z.string().regex(/^\d+$/, 'Time must be a valid number')
  ]),
  cuisine_ids: z.array(z.string()).min(1, "Select at least one cuisine"),
  Est_Price_per_plate: z.union([
    z.number().positive('Price must be greater than 0'),
    z.string().regex(/^\d+$/, 'Price must be a valid number')
  ]),
  booking_amount: z.union([
    z.number().positive('Booking Amount must be greater than 0'),
    z.string().regex(/^\d+$/, 'Booking Amount must be a valid number')
  ]),
  restaurantMenu: z
    .array(z.record(z.any()))
    .min(3, 'Please upload at least 3 vendor/store photos'),
  restaurantPhotos: z
    .array(z.record(z.any()))
    .min(3, 'Please upload at least 3 vendor/store photos'),
  cuisines: z.array(z.string()).optional(),
  email: z
    .string()
    .min(3, 'email name is required')
    .email('email name is required'),
  phone_number: z.string().optional(),
  category: z.array(z.string()).min(1, { message: 'Category is required' }),
  amenities: z.array(z.string()).min(1, { message: 'Ameneties is required' }),
  itemCateogy: z
    .array(z.string())
    .min(1, { message: 'Item Categories is required' }),
  // subscribers_limit: z
  //   .union([
  //     z.number().nonnegative('Subscribers limit must be 0 or greater'),
  //     z.string().regex(/^\d+$/, 'Subscribers limit must be a valid number')
  //   ])
  //   .optional(),
  catering_services: z.boolean().default(false),
  referral_code: z.string().optional()
});
type LoginForm = z.infer<typeof formSchema>;
type LoginProps = {
  foodDelivery: boolean;
  dineOut: boolean;
  isBoth: boolean;
};
const Login = ({ foodDelivery, dineOut, isBoth }: LoginProps) => {
  const { Toast, userInfo, setUserInfo } = useGlobalContext();
  const [loading, setLoading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [image, setImage] = useState('');
  const [value, setValue] = useState<any>(countries?.[97]);
  const [state, setState] = useState<any>('');
  const [cuisineList, setCuisineList] = useState<Cuisine[]>([]);
  const [otpModal, setOtpModal] = useState({
    phone: false,
    email: false
  });
  const [verified, setVerified] = useState({
    phone: false,
    email: false
  });
  const [errMsg, setErrMsg] = useState('');
  const [visibleFields, setVisibleFields] = useState(1);
  const router = useRouter();
  const [blobFile, setBlobFile] = useState<File | null>(null);
  const [fileName, setFileName] = useState('');
  const [categories, setCategories] = useState<any>([]);
  const [ameneties, setAmeneties] = useState<any>([]);
  const [cuisines, setCuisines] = useState<any[]>([]);
  const form = useForm<LoginForm>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      phone_number: undefined,
      restaurantMenu: [],
      restaurantPhotos: [],
      catering_services: false,
      cuisine_ids: [],
      referral_code: ''
    }
  });
  const baseCategories = ['veg', 'non_veg', 'egg'];

  const foodCategories = isBoth ? [...baseCategories, 'jain'] : baseCategories;

  const [otp, setOtp] = useState({
    phone: '',
    email: ''
  });
  const token: any = sessionStorage.getItem('token');
  const res: any = sessionStorage.getItem('restaurant');
  const decodedToken: any = jwtDecode(token);

  const validatePhoneNumber = (phoneNumber: string) => {
    if (!phoneNumber) {
      setErrMsg('Phone number is required!');
      return false;
    }

    const minLength = value?.min_length || 6;
    const maxLength = value?.max_length || 15;
    const phoneLength = phoneNumber.length;

    if (phoneLength < minLength) {
      setErrMsg(`Phone number must be at least ${minLength} digits for ${value?.name}!`);
      return false;
    }

    if (phoneLength > maxLength) {
      setErrMsg(`Phone number must not exceed ${maxLength} digits for ${value?.name}!`);
      return false;
    }

    setErrMsg('');
    return true;
  };

  const getCategories = async () => {
    try {
      setLoading(true);
      const urlSearchParam = new URLSearchParams();
      urlSearchParam.set('page', '1');
      urlSearchParam.set('limit', '10');
      const apiRes = await apis.restaurant.getCategories(
        urlSearchParam.toString()
      );
      setCategories(apiRes?.data);
      setLoading(false);
    } catch (error) {
      Toast.error('some error Occured');
    }
  };
  const getAmeneties = async () => {
    try {
      setLoading(true);

      const apiRes = await apis.restaurant.getAmeneties();
      setAmeneties(apiRes?.data);
      setLoading(false);
    } catch (error) {
      Toast.error('some error Occured');
    }
  };
  useEffect(() => {
    getCategories();
    getAmeneties();
  }, []);

  useEffect(() => {
    const fetchCuisines = async () => {
      try {
        const res = await apis.Cuisine.getCuisine();
        setCuisines(res?.data || []);
      } catch (error) {
        Toast.error(error);
      }
    };
    fetchCuisines();
  }, []);

  useEffect(() => {
    if (!token) {
      router.replace(`/auth/login`);
    }
  }, []);

  useEffect(() => {
    if (decodedToken.country_code === value?.dial_code) {
      setVerified({ ...verified, phone: true });
    } else {
      setVerified({ ...verified, phone: false });
    }
  }, [value]);

  useEffect(() => {
    if (state) {
      validatePhoneNumber(state);
    }
  }, [value]);

  useEffect(() => {
    if (res === 'complete' && userInfo) {
      // Image
      setImage(userInfo?.image || '');

      // Basic fields
      form.setValue('name', userInfo?.restaurant_id?.restaurant_name || '');
      form.setValue(
        'avg_prepare',
        userInfo?.restaurant_id?.average_preparing_time || ''
      );
      form.setValue('owner_name', userInfo?.name || '');
      form.setValue('email', userInfo?.email || '');

      // Phone + Country Code
      setState(userInfo?.restaurant_id?.restaurant_phone);
      const matchedCountry = countries.find(
        (country) =>
          country?.dial_code ===
          (userInfo?.restaurant_id?.country_code ||
            `+${userInfo?.restaurant_id?.country_code}`)
      );
      setValue(matchedCountry);

      form.setValue(
        'phone_number',
        (userInfo?.country_code || '') + (userInfo?.phone || '')
      );
      form.setValue('cuisine_ids', userInfo?.restaurant_id?.cuisine_ids || []);
      form.setValue('category', userInfo?.restaurant_id?.food_type || []);
      form.setValue(
        'Est_Price_per_plate',
        userInfo?.restaurant_id?.estimated_price_per_plate || ''
      );
      form.setValue(
        'booking_amount',
        userInfo?.restaurant_id?.booking_amount || ''
      );

      form.setValue(
        'restaurantMenu',
        (userInfo?.restaurant_id?.uploadRestaurantMenu || []).map((key: string) => ({
          id: key,                        // unique identifier
          fullUrl: BUCKET_ROOT + key,     // full URL for preview
          name: key                       // optional: filename
        }))
      );

      form.setValue(
        'restaurantPhotos',
        (userInfo?.restaurant_id?.uploadRestaurantPhotos || []).map((key: string) => ({
          id: key,
          fullUrl: BUCKET_ROOT + key,
          name: key
        }))
      );


      // Services & amenities
      form.setValue('itemCateogy', userInfo?.restaurant_id?.services || []);
      form.setValue('amenities', userInfo?.restaurant_id?.amenities || []);
      form.setValue(
        'catering_services',
        userInfo?.restaurant_id?.catering_services || false
      );
      form.setValue('referral_code', userInfo?.restaurant_id?.referral_code || '');
      setVerified({ email: true, phone: true });
    } else {
      setState(decodedToken.phone);
      const matchedCountry = countries.find(
        (country) =>
          country.dial_code ===
          (decodedToken.country_code || `+${decodedToken.country_code}`)
      );
      setValue(matchedCountry);
      setVerified({ ...verified, phone: true });
    }
  }, []);

  function getDeviceType() {
    const userAgent = navigator.userAgent.toLowerCase();
    const width = window.screen.width;
    const height = window.screen.height;
    if (/mobile/i.test(userAgent)) {
      return 'mobile';
    } else if (/tablet/i.test(userAgent)) {
      return 'tablet';
    } else if (width > 1024 && height <= 800) {
      return 'laptop';
    } else {
      return 'computer';
    }
  }
  const handleInputChange = (index: any, event: any, type?: any) => {
    const value = type ? event : event.target?.value.trim();
    if (value !== '' && visibleFields === index) {
      setVisibleFields((prev) => prev + 1);
    }
  };
  const onSubmit = async (data: LoginForm) => {
    // setUserInfo(null);
    // apis.setToken('');
    // destroyCookie(null, COOKIES_USER_ACCESS_TOKEN, {
    //   maxAge: 0,
    //   path: '/'
    // });
    if (!image) {
      Toast.error('Please upload a vendor/store image');
      return;
    }
    if (!verified.phone) {
      Toast.error('Please verify phone number!');
      return;
    }
    if (!verified.email) {
      Toast.error('Please verify email!');
      return;
    }

    try {
      let phoneNumber = state || '';
      let dialCode = value?.dial_code || '';

      if (phoneNumber.startsWith(dialCode)) {
        phoneNumber = phoneNumber.slice(dialCode.length);
      }

      const type =
        typeof window !== 'undefined'
          ? new URLSearchParams(window.location.search).get('type') || ''
          : '';

      let payload: any = {
        restaurant_type: isBoth ? 'both-home-rest' : 'restaurant',
        restaurant_name: data?.name,
        restaurant_phone: phoneNumber,
        uploadRestaurantMenu:
          data?.restaurantMenu?.map((img) => `${img.url}`) || [],
        uploadRestaurantPhotos:
          data?.restaurantPhotos?.map((img) => `${img.url}`) || [],
        isFoodDelivery: foodDelivery,
        estimated_price_per_plate: Number(data?.Est_Price_per_plate),
        booking_amount: Number(data?.booking_amount),
        isDineOut: dineOut,
        services: data?.itemCateogy,
        amenities: data?.amenities,
        country_code: dialCode,
        food_type: data?.category,
        average_preparing_time: Number(data?.avg_prepare),
        owner_name: data?.owner_name,
        email: data?.email,
        image: image,
        catering_services: data?.catering_services,
        cuisine_ids: data.cuisine_ids,
        type,
        referral_code: data?.referral_code || ''
      };
      // if (isBoth && foodDelivery) {
      //   payload["subscribers_limit"] = Number(data?.subscribers_limit)
      // }
      setLoading(true);

      const apiRes =
        res === 'complete'
          ? await apis.restaurant.update(userInfo?.restaurant_id?._id, payload)
          : await apis.restaurant.add(payload);

      if (apiRes?.data) {
        sessionStorage.setItem('resId', apiRes?.data?._id);
        setUserInfo((prev: any) => ({
          ...prev,
          isFoodDelivery: foodDelivery,
          isDineOut: dineOut,
          restaurant_id: {
            ...(prev?.restaurant_id || {}),
            ...apiRes.data
          }
        }));
        router.replace('/auth/restaurant/location');
      }
    } catch (error) {
      Toast.error(error);
    } finally {
      setLoading(false);
    }
  };

  const phoneVerify = async (e: any, mobile: any) => {
    e.preventDefault();
    if (verified.phone) {
      Toast.error('Phone number already verified!');
      return;
    }
    if (!validatePhoneNumber(mobile)) {
      return;
    }

    try {
      let phoneNumber = state || '';
      let dialCode = value?.dial_code || '';

      if (phoneNumber.startsWith(dialCode)) {
        phoneNumber = phoneNumber.slice(dialCode.length);
      }
      let payload = {
        country_code: dialCode,
        phone: phoneNumber
      };
      const apiRes = await apis.Auth.verifyPhoneEmail(payload);
      setOtpModal({ ...otpModal, phone: true });
      sessionStorage.setItem('otpTokenPhone', apiRes?.token);
      Toast.success('Verification code sent to your phone!');
    } catch (error) {
      Toast.error(error);
    }
  };

  const emailVerify = async (e: any, mail: string) => {
    e.preventDefault();
    if (mail?.length < 1) {
      Toast.error('Enter valid  email!');
    }
    if (verified.email) {
      Toast.error('Email already verified!');
      return;
    }
    try {
      let payload = {
        email: mail
      };
      const apiRes = await apis.Auth.verifyPhoneEmail(payload);
      sessionStorage.setItem('otpTokenEmail', apiRes?.token);
      setOtpModal({ ...otpModal, email: true });
      Toast.success('Verification code sent to your email!');
    } catch (error) {
      Toast.error(error);
    }
  };

  const emailOtpVerified = async (e: any) => {
    e.preventDefault();
    try {
      let payload = {
        otp: otp.email
      };
      const apiRes = await apis.Auth.VerifyE(payload);
      if (apiRes) {
        sessionStorage.removeItem('otpTokenEmail');
        setOtpModal({ ...otpModal, email: false });
        setVerified({ ...verified, email: true });
        Toast.success('Email verified successfully!');
      }
    } catch (error) {
      Toast.error(error);
    }
  };

  const phoneOtpVerified = async (e: any) => {
    e.preventDefault();
    try {
      let payload = {
        otp: otp.phone
      };
      const apiRes = await apis.Auth.VerifyP(payload);
      if (apiRes) {
        sessionStorage.removeItem('otpTokenPhone');
        setOtpModal({ ...otpModal, phone: false });
        setVerified({ ...verified, phone: true });
        Toast.success('Phone Number verified successfully!');
      }
    } catch (error) {
      Toast.error(error);
    }
  };

  const handleFileSelect = () => {
    if (fileInputRef?.current) {
      fileInputRef.current.click();
    }
  };
  const handleUploadImage = async (file: File) => {
    try {
      setLoading(true);

      const apiRes = await apis.Common.uploadFile('file', file);
      setImage(apiRes?.key);
      Toast.success('Image uploaded successfully!');
    } catch (error) {
      Toast.error('Failed to upload image.');
    } finally {
      setLoading(false);
    }
  };

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    event.preventDefault();
    const file = event.target.files?.[0];

    if (file) {
      const maxFileSize = 5 * 1024 * 1024;
      const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg'];

      if (!allowedTypes.includes(file.type)) {
        Toast.error('Only JPG and PNG images are allowed.');
        return;
      }

      if (file.size > maxFileSize) {
        Toast.error('Image size cannot be more than 5MB.');
        return;
      }

      setBlobFile(file);
      handleUploadImage(file);
    }
  };

  const handlePhoneChange = (e: any) => {
    const phoneNumber = e.target.value.replace(/\D/g, '');
    setState(phoneNumber);
    if (errMsg) {
      setErrMsg('');
    }
    if (
      phoneNumber === decodedToken.phone &&
      decodedToken.country_code === value?.dial_code
    ) {
      setVerified({ ...verified, phone: true });
    } else {
      setVerified({ ...verified, phone: false });
    }
  };
  const handleRestaurantMenuImages = (data: any) => {
    form.setValue('restaurantMenu', data);
  };
  const handleRestaurantPhotosImages = (data: any) => {
    form.setValue('restaurantPhotos', data);
  };

  return (
    <>
      <section className="no-scrollbar h-[80vh] w-full overflow-y-auto">
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-3">
            <div className="space-y-1">
              <div className="relative mx-auto mb-8 h-[150px] w-[150px]">
                {image ? (
                  <img
                    src={BUCKET_ROOT + image}
                    alt="Vendor"
                    className="h-[140px] w-[140px] rounded-full border-[1px] border-[var(--primary-brand)] object-cover"
                  />
                ) : (
                  <div className="flex h-[140px] w-[140px] items-center justify-center rounded-full border-[1px] border-[var(--primary-brand)]">
                    {' '}
                    <Icons.MenuIcon />
                  </div>
                )}
                <button
                  className="absolute bottom-3 right-2 rounded-full bg-[var(--primary-brand)] p-2 text-white hover:bg-[var(--primary-brand)]"
                  onClick={(e) => {
                    e.preventDefault();
                    handleFileSelect();
                  }}
                >
                  <Camera className="h-4 w-4" />
                </button>
                <Input
                  type="file"
                  accept=".jpg,.jpeg,.png"
                  hidden
                  ref={fileInputRef}
                  onChange={handleFileChange}
                  className="hidden"
                />
              </div>
              <FormField
                name="name"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-black">
                      Vendor Name
                    </FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Vendor Name"
                        {...field}
                        className={`h-[48px] ${form.formState.errors.email ? 'error-border' : ''
                          } bg-white`}
                        onChange={(e) => {
                          const sanitizedValue = e.target.value.replace(
                            /^\s+/,
                            ''
                          );
                          field.onChange(sanitizedValue);
                        }}
                        maxLength={30}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="h-[80px] space-y-1">
              <Label className="text-black">
                Vendor Contact Number<span className="ml-1">*</span>
              </Label>
              <div
                className="flex flex-row rounded-md bg-white"
                style={{ border: '1px solid #eee' }}
              >
                <CountryPickerModal setValue={setValue} value={value} />
                <Input
                  placeholder="Enter your phone number"
                  className={` $ h-[48px] w-3/4 border-none bg-white`}
                  value={state}
                  onChange={(e: any) => handlePhoneChange(e)}
                  onBlur={() => {
                    if (state) {
                      validatePhoneNumber(state);
                    }
                  }}
                  minLength={value?.min_length || 6}
                  maxLength={value?.max_length || 15}
                />
                <button
                  className="flex h-[48px] items-center justify-center p-2 text-[14px] font-[600] text-[var(--primary-brand)]"
                  onClick={(e: any) => phoneVerify(e, state)}
                >
                  {verified.phone ? 'Verified' : 'Verify'}
                </button>
              </div>

              <span className="text-[12px] font-[400] text-red-600">
                {errMsg}
              </span>
            </div>
            {otpModal.phone && (
              <div className="flex flex-row gap-4 space-y-1">
                <InputOTP
                  className="w-full"
                  maxLength={4}
                  value={otp.phone}
                  onChange={(value: string) => setOtp({ ...otp, phone: value })}
                >
                  {[...Array(4)].map((_, index) => (
                    <InputOTPGroup key={index}>
                      <InputOTPSlot
                        index={index}
                        className="h-11 w-14 rounded-md border border-gray-300 bg-white text-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                    </InputOTPGroup>
                  ))}
                </InputOTP>
                <Button
                  // type="submit"
                  onClick={(e: any) => phoneOtpVerified(e)}
                  className="h-11 w-full"
                  variant={'theme'}                >
                  {/* <Loader loading={loading} /> */}
                  Verify
                </Button>
              </div>
            )}
            <div className="space-y-1">
              <FormField
                name="avg_prepare"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-black">
                      Average Preparation time(in minutes)
                    </FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Enter average preparation time"
                        {...field}
                        className={`h-[48px] ${form.formState.errors.avg_prepare
                          ? 'error-border'
                          : ''
                          } bg-white`}
                        onChange={(e) => {
                          // Remove non-numeric characters
                          const sanitizedValue = e.target.value.replace(
                            /\D/g,
                            ''
                          );
                          field.onChange(sanitizedValue);
                        }}
                        maxLength={3}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
            <div className="space-y-1">
              <FormField
                name="Est_Price_per_plate"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-black">
                      Estimated price per plate
                    </FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Estimated price per plate"
                        {...field}
                        className={`h-[48px] ${form.formState.errors.avg_prepare
                          ? 'error-border'
                          : ''
                          } bg-white`}
                        onChange={(e) => {
                          // Remove non-numeric characters
                          const sanitizedValue = e.target.value.replace(
                            /\D/g,
                            ''
                          );
                          field.onChange(sanitizedValue);
                        }}
                        maxLength={4}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
            <div className="space-y-1">
              <FormField
                name="booking_amount"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-black">Booking amount</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Enter booking amount"
                        {...field}
                        className={`h-[48px] ${form.formState.errors.avg_prepare
                          ? 'error-border'
                          : ''
                          } bg-white`}
                        onChange={(e) => {
                          // Remove non-numeric characters
                          const sanitizedValue = e.target.value.replace(
                            /\D/g,
                            ''
                          );
                          field.onChange(sanitizedValue);
                        }}
                        maxLength={4}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div>
              <FormField
                control={form.control}
                name="restaurantMenu"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Upload vendor menu</FormLabel>
                    <FormControl>
                      <MultiImages
                        addImages={handleRestaurantMenuImages}
                        images={field.value}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
            <div>
              <FormField
                control={form.control}
                name="restaurantPhotos"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Upload vendor photos</FormLabel>
                    <FormControl>
                      <MultiImages
                        addImages={handleRestaurantPhotosImages}
                        images={field.value}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
            {/* Ameneties Section */}
            <div className="space-y-1">
              <FormField
                name="amenities"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-black">
                      Select Ameneties
                    </FormLabel>
                    <p className="text-[13px] text-gray-500 mt-1 mb-1">
                      Services provided for comfort and convenience
                    </p>
                    <FormControl>
                      <div className="mt-3 grid grid-cols-1 gap-4 sm:grid-cols-2 md:grid-cols-3">
                        {ameneties.map((category: any) => (
                          <div
                            key={category?._id}
                            className="flex items-center space-x-2"
                          >
                            <Checkbox
                              id={category?._id}
                              checked={field.value?.includes(category?._id)}
                              onCheckedChange={(checked) => {
                                const newValue = checked
                                  ? [...(field.value || []), category?._id]
                                  : field.value?.filter(
                                    (item: string) => item !== category?._id
                                  );
                                field.onChange(newValue);
                              }}
                            />
                            <label
                              htmlFor={category?._id}
                              className="text-sm text-gray-500"
                            >
                              {category?.name}
                            </label>
                          </div>
                        ))}
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            {/* Categories Section */}
            <div className="space-y-1">
              <FormField
                name="itemCateogy"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-black">
                      Select Services
                    </FormLabel>
                    <FormControl>
                      <div className="mt-3 grid grid-cols-1 gap-4 sm:grid-cols-2 md:grid-cols-3">
                        {categories.map((category: any) => (
                          <div
                            key={category._id}
                            className="flex items-center space-x-2"
                          >
                            <Checkbox
                              id={category._id}
                              checked={field.value?.includes(category._id)}
                              onCheckedChange={(checked) => {
                                const newValue = checked
                                  ? [...(field.value || []), category._id]
                                  : field.value?.filter(
                                    (item: string) => item !== category._id
                                  );
                                field.onChange(newValue);
                              }}
                            />
                            <label
                              htmlFor={category._id}
                              className="text-sm text-gray-500"
                            >
                              {category.name}
                            </label>
                          </div>
                        ))}
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="space-y-1">
              <FormField
                name="cuisine_ids"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-black">Cuisines</FormLabel>
                    <p className="text-[13px] text-gray-700 mt-1 mb-1">
                      Types or styles of food
                    </p>
                    <FormControl>
                      <div className="mt-3 grid grid-cols-2 gap-3">
                        {cuisines?.map((item) => {
                          const isChecked = (field.value || []).includes(item._id);

                          return (
                            <div
                              key={item._id}
                              className="flex items-center space-x-2"
                            >
                              <Checkbox
                                id={item._id}
                                checked={isChecked}
                                onCheckedChange={(checked) => {
                                  let newValue = [...(field.value || [])];

                                  if (checked) {
                                    newValue.push(item._id);
                                  } else {
                                    newValue = newValue.filter((id) => id !== item._id);
                                  }

                                  field.onChange(newValue);
                                }}
                              />
                              <label
                                htmlFor={item._id}
                                className="text-sm leading-none text-gray-600"
                              >
                                {item.name}
                              </label>
                            </div>
                          );
                        })}
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="space-y-1">
              <FormField
                name="owner_name"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-black">Owner Name</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Owner Name"
                        {...field}
                        className={`h-[48px] ${form.formState.errors.email ? 'error-border' : ''
                          } bg-white`}
                        onChange={(e) => {
                          const sanitizedValue = e.target.value.replace(
                            /^\s+/,
                            ''
                          );
                          field.onChange(sanitizedValue);
                        }}
                        maxLength={30}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="space-y-1">
              <FormField
                name="email"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-black">Email address</FormLabel>
                    <FormControl>
                      <div
                        className={`flex flex-row  bg-white ${form.formState.errors.email ? 'error-border' : ''
                          }`}
                      >
                        <Input
                          placeholder="Email address"
                          {...field}
                          className={`h-[48px] border-none  bg-white`}
                          onChange={(e) => {
                            const sanitizedValue = e.target.value.replace(
                              /^\s+/,
                              ''
                            );
                            field.onChange(sanitizedValue);
                            if (sanitizedValue === userInfo?.email) {
                              setVerified({ ...verified, email: true });
                            } else {
                              setVerified({ ...verified, email: false });
                            }
                          }}
                          maxLength={30}
                        />
                        <button
                          className="flex h-[48px] items-center justify-center p-2 text-[14px] font-[600] text-[var(--primary-brand)]"
                          onClick={(e: any) => emailVerify(e, field.value)}
                        >
                          {verified.email ? 'Verified' : 'Verify'}
                        </button>
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
            {otpModal.email && (
              <div className="flex flex-row gap-4 space-y-1">
                <InputOTP
                  className="w-full"
                  maxLength={4}
                  value={otp.email}
                  onChange={(value: string) => setOtp({ ...otp, email: value })}
                >
                  {[...Array(4)].map((_, index) => (
                    <InputOTPGroup key={index}>
                      <InputOTPSlot
                        index={index}
                        className="h-11 w-14 rounded-md border border-gray-300 bg-white text-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                    </InputOTPGroup>
                  ))}
                </InputOTP>
                <Button
                  // type="submit"
                  onClick={(e: any) => emailOtpVerified(e)}
                  className="h-11 w-full"
                  variant={'theme'}                >
                  {/* <Loader loading={loading} /> */}
                  Verify
                </Button>
              </div>
            )}

            <div className="space-y-1">
              <FormField
                name="referral_code"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-black">Referral Code</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Referral Code"
                        {...field}
                        className="h-[48px] bg-white"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            {/* {isBoth && foodDelivery && (
              <div className="space-y-1">
                <FormField
                  name="subscribers_limit"
                  control={form.control}
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="text-black">
                        Subscribers Limit
                      </FormLabel>
                      <FormControl>
                        <Input
                          placeholder="Enter subscribers limit"
                          {...field}
                          className={`h-[48px] ${form.formState.errors.subscribers_limit
                            ? 'error-border'
                            : ''
                            } bg-white`}
                          onChange={(e) => {
                            // Only allow numbers
                            const sanitizedValue = e.target.value.replace(
                              /\D/g,
                              ''
                            );
                            field.onChange(sanitizedValue);
                          }}
                          maxLength={5}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            )} */}

            {foodDelivery && (
              <div className="space-y-1">
                <FormField
                  name="catering_services"
                  control={form.control}
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="text-black">
                        Do you provide Catering Services?
                      </FormLabel>
                      <FormControl>
                        <RadioGroup
                          onValueChange={(val) => field.onChange(val === 'yes')}
                          value={field.value ? 'yes' : 'no'}
                          className="mt-2 flex flex-row space-x-4"
                        >
                          <div className="flex items-center space-x-2">
                            <RadioGroupItem value="yes" id="catering-yes" />
                            <Label htmlFor="catering-yes" className="text-black">Yes</Label>
                          </div>
                          <div className="flex items-center space-x-2">
                            <RadioGroupItem value="no" id="catering-no" />
                            <Label htmlFor="catering-no" className="text-black">No</Label>
                          </div>
                        </RadioGroup>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            )}

            <div className="space-y-1">
              <FormField
                name="category"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-black">
                      What kind of food does this restaurant serve
                    </FormLabel>
                    <FormControl>
                      <div className="mt-3 flex items-center gap-2">
                        {foodCategories.map((category) => (
                          <div
                            key={category}
                            className="flex items-center space-x-2"
                          >
                            <Checkbox
                              id={category}
                              checked={field.value?.includes(category)}
                              onCheckedChange={(checked) => {
                                // Update the value array based on selection
                                const newValue = checked
                                  ? [...(field.value || []), category]
                                  : field.value?.filter(
                                    (item: string) => item !== category
                                  );
                                field.onChange(newValue);
                                sessionStorage.setItem(
                                  'category',
                                  JSON.stringify(newValue)
                                );
                              }}
                            />
                            <label
                              htmlFor={category}
                              className="text-sm leading-none text-gray-500 peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                            >
                              {category
                                .split('_')
                                .map(w => w.charAt(0).toUpperCase() + w.slice(1))
                                .join(' ')}

                            </label>
                          </div>
                        ))}
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            {/* <Button className="w-full h-11 theme-background btn-text-color text-white" variant={"default"} type="submit"> */}
            <Button
              className="w-full"
              variant={'theme'}
              //   onClick={() => router.push('/auth/restaurant/location')}
              type="submit"
            >
              <Loader loading={loading} />
              Next
            </Button>
          </form>
        </Form>
      </section>
    </>
  );
};

type FormTwoProps = {
  foodDelivery: boolean;
  dineOut: boolean;
  isBoth: boolean;
};
export default function FormTwo({
  foodDelivery,
  dineOut,
  isBoth
}: FormTwoProps) {
  return (
    // <AuthLayout
    //   title="Enter your Restaurant Details"
    //   des="To get started, please provide the essential details of your restaurant."
    //   image={authBanner.src}
    // >
    <Login foodDelivery={foodDelivery} dineOut={dineOut} isBoth={isBoth} />
    // </AuthLayout>
  );
}
