'use client';

import { Camera } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { useGlobalContext } from '@/context/Provider';
import { use, useEffect, useRef, useState } from 'react';
import apis, { BUCKET_ROOT } from '@/utils/apis';
import { Icons } from '../icons';
import CountryPickerModal from '../countrycode/page';
import countries from '@/utils/CountryCode.json';
import {
  InputOTP,
  InputOTPGroup,
  InputOTPSlot
} from '@/components/ui/input-otp';
import { Button } from '../ui/button';
import { Checkbox } from '../ui/checkbox';
import GoogleAutocomplete from '../Map/GoogleAutoComplete';
import { useRouter } from 'next/navigation';
import { MultiImages } from '../common/MultipleDropzone';
import { HomeCookedProfile } from './HomeCookedProfile';
import { GroceryProfile } from './GroceryProfile';


interface ProfileFormData {
  avgpreptime: number;
  restaurantName: string;
  contactNumber: string;
  ownercontactNumber: string;
  ownerName: string;
  email: string;
  mobileNumber: string;
  image: string;
  countryCode: string;
  id: string;
}

export function EditProfileModal() {
  const { Toast, userInfo, setUserInfo } = useGlobalContext();
  const [loading, setLoading] = useState(false);
  const [value, setValue] = useState<any>(countries?.[97]);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [image, setImage] = useState('');
  const [blobFile, setBlobFile] = useState<File | null>(null);
  const [state, setState] = useState<any>('');
  const [ownerPhone, setOwnerPhone] = useState<any>('');
  const [fileName, setFileName] = useState('');
  const [selectedFoodTypes, setSelectedFoodTypes] = useState<string[]>([]);
  const [address, setAddress] = useState<any>(null);
  const [amenities, setAmenities] = useState<any[]>([]);
  const [selectedAmenities, setSelectedAmenities] = useState<string[]>([]);
  const [services, setServices] = useState<any[]>([]);
  const [selectedServices, setSelectedServices] = useState<string[]>([]);
  const [isDineOut, setIsDineOut] = useState(false);
  const [estimatedPricePerPlate, setEstimatedPricePerPlate] = useState<number>(0);
  const [bookingAmount, setBookingAmount] = useState<number>(0);
  const [restaurantMenu, setRestaurantMenu] = useState<string[]>([]);
  const [restaurantPhotos, setRestaurantPhotos] = useState<string[]>([]);

  // Initial values for change detection
  const [initialValues, setInitialValues] = useState<any>(null);



  const foodTypes = ['veg', 'non_veg', 'egg'];
  const [otpModal, setOtpModal] = useState({
    ownerPhone: false,
    phone: false,
    email: false
  });
  const router = useRouter();

  const [otp, setOtp] = useState({
    ownerPhone: '',
    phone: '',
    email: ''
  });
  const [verified, setVerified] = useState({
    ownerPhone: false,
    phone: false,
    email: false
  });

  useEffect(() => {
    const fetchAmenities = async () => {
      try {
        const res = await apis.restaurant.getAmeneties();
        setAmenities(res?.data || []);
        if (userInfo?.restaurant_id?.amenities) {
          setSelectedAmenities(userInfo?.restaurant_id?.amenities);
        }
      } catch (error) {
        Toast.error("Failed to fetch amenities");
      }
    };
    fetchAmenities();
  }, [userInfo]);

  useEffect(() => {
    const fetchAmenitiesAndServices = async () => {
      try {
        const amenityRes = await apis.restaurant.getAmeneties();
        setAmenities(amenityRes?.data || []);
        if (userInfo?.restaurant_id?.amenities) {
          setSelectedAmenities(userInfo?.restaurant_id?.amenities);
        }
        const urlSearchParam = new URLSearchParams();
        urlSearchParam.set('page', '1');
        urlSearchParam.set('limit', '10');
        const serviceRes = await apis.restaurant.getCategories(urlSearchParam.toString());
        setServices(serviceRes?.data || []);
        if (userInfo?.restaurant_id?.services) {
          setSelectedServices(userInfo?.restaurant_id?.services);
        }
      } catch (error) {
        Toast.error("Failed to fetch amenities or services");
      }
    };

    fetchAmenitiesAndServices();
  }, [userInfo]);



  const [formData, setFormData] = useState<ProfileFormData>({
    restaurantName: userInfo?.restaurant_id?.restaurant_name || '',
    contactNumber:
      (userInfo?.restaurant_id?.country_code || '') +
      (userInfo?.restaurant_id?.restaurant_phone || ''),
    avgpreptime: userInfo?.restaurant_id?.average_preparing_time,
    ownercontactNumber:
      (userInfo?.country_code || '') + (userInfo?.phone || ''),
    countryCode: userInfo?.restaurant_id?.country_code || '',
    ownerName: userInfo?.name || '',
    email: userInfo?.email || '',
    mobileNumber: (userInfo?.country_code || '') + (userInfo?.phone || ''),
    image: userInfo?.image || '',
    id: userInfo?.restaurant_id?._id || ''
  });

  const data = (userInfo?.restaurant_id?.uploadRestaurantMenu || []).map((file: any) => {
    return `${BUCKET_ROOT}${file}`;
  });

  useEffect(() => {
    setFormData({
      restaurantName: userInfo?.restaurant_id?.restaurant_name || '',
      contactNumber: userInfo?.restaurant_id?.restaurant_phone || '',
      ownercontactNumber: userInfo?.phone || '',
      countryCode: userInfo?.restaurant_id?.country_code || '',
      avgpreptime: userInfo?.restaurant_id?.average_preparing_time || '',
      ownerName: userInfo?.name || '',
      email: userInfo?.email || '',
      mobileNumber: (userInfo?.country_code || '') + (userInfo?.phone || ''),
      image: userInfo?.image || '',
      id: userInfo?.restaurant_id?._id || ''
    });
    setImage(userInfo?.image || '');
    setSelectedFoodTypes(userInfo?.restaurant_id?.food_type || '');
    setState(userInfo?.restaurant_id?.restaurant_phone);
    setOwnerPhone(userInfo?.phone);
    const matchedCountry = countries.find(
      (country) => country.dial_code === userInfo?.restaurant_id.country_code
    );
    setValue(matchedCountry);
    setVerified({ email: true, phone: true, ownerPhone: true });
    setIsDineOut(userInfo?.restaurant_id?.isDineOut || false);
    setEstimatedPricePerPlate(userInfo?.restaurant_id?.estimated_price_per_plate || 0);
    setBookingAmount(userInfo?.restaurant_id?.booking_amount || 0);
    const prefilledMenu = (userInfo?.restaurant_id?.uploadRestaurantMenu || []).map((file: any, index: number) => ({
      id: `menu-${index}-${file}`,
      url: file.startsWith('http') ? file : `${BUCKET_ROOT}${file}`,
    }));

    const prefilledPhotos = (userInfo?.restaurant_id?.uploadRestaurantPhotos || []).map((file: any, index: number) => ({
      id: `photo-${index}-${file}`,
      url: file.startsWith('http') ? file : `${BUCKET_ROOT}${file}`,
    }));

    setRestaurantMenu(prefilledMenu);
    setRestaurantPhotos(prefilledPhotos);

    // Store initial values for change detection
    setInitialValues({
      restaurantName: userInfo?.restaurant_id?.restaurant_name || '',
      contactNumber: userInfo?.restaurant_id?.restaurant_phone || '',
      avgpreptime: userInfo?.restaurant_id?.average_preparing_time || '',
      ownerName: userInfo?.name || '',
      email: userInfo?.email || '',
      ownerPhone: userInfo?.phone || '',
      image: userInfo?.image || '',
      selectedFoodTypes: userInfo?.restaurant_id?.food_type || [],
      isDineOut: userInfo?.restaurant_id?.isDineOut || false,
      estimatedPricePerPlate: userInfo?.restaurant_id?.estimated_price_per_plate || 0,
      bookingAmount: userInfo?.restaurant_id?.booking_amount || 0,
      selectedAmenities: userInfo?.restaurant_id?.amenities || [],
      selectedServices: userInfo?.restaurant_id?.services || [],
      address: userInfo?.restaurant_id?.address || null,
      restaurantMenu: prefilledMenu,
      restaurantPhotos: prefilledPhotos,
    });

  }, [userInfo]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    if (name === 'email') {
      setFormData((prev) => ({ ...prev, [name]: value }));
      if (value === userInfo?.email) {
        setVerified({ ...verified, email: true });
      } else {
        setVerified({ ...verified, email: false });
      }
    } else {
      setFormData((prev) => ({ ...prev, [name]: value }));
    }
  };

  const handleUpdate = async () => {
    if (!image) {
      Toast.error('Please upload vendor image');
      return;
    }

    if (!address || !address.name) {
      Toast.error('Please select an address');
      return;
    }

    if (!formData.avgpreptime || formData.avgpreptime <= 0) {
      Toast.error('Please enter average preparation time');
      return;
    }

    if (isDineOut) {
      if (!estimatedPricePerPlate || estimatedPricePerPlate <= 0) {
        Toast.error('Please enter estimated price per plate');
        return;
      }
      if (!bookingAmount || bookingAmount < 0) {
        Toast.error('Please enter booking amount');
        return;
      }
      if (restaurantMenu.length === 0) {
        Toast.error('Please upload vendor menu');
        return;
      }
      if (restaurantPhotos.length === 0) {
        Toast.error('Please upload vendor photos');
        return;
      }
    }

    let payload: any = {
      restaurant_name: formData?.restaurantName,
      restaurant_phone: state,
      country_code: value?.dial_code,
      phone: ownerPhone,
      owner_name: formData?.ownerName,
      email: formData?.email,
      image: image,
      food_type: selectedFoodTypes,
      address: address,
      average_preparing_time: parseInt(formData?.avgpreptime?.toString()) || 0,
      isDineOut: isDineOut,
    };

    if (isDineOut) {
      payload.amenities = selectedAmenities;
      payload.services = selectedServices;
      payload.estimated_price_per_plate = estimatedPricePerPlate;
      payload.booking_amount = bookingAmount;
      payload.uploadRestaurantMenu = restaurantMenu.map((item: any) => item.url);
      payload.uploadRestaurantPhotos = restaurantPhotos.map((item: any) => item.url);
    }

    try {
      setLoading(true);
      const apiRes = await apis.restaurant.update(formData?.id, payload);
      if (apiRes) {
        const successMsg = 'Profile updated successfully! Your request has been sent to admin for approval.';
        Toast.success(successMsg);
        sessionStorage.setItem('pendingToast', successMsg);
        try {
          const profileRes = await apis.Profile.getProfile();
          if (profileRes?.data) {
            setUserInfo((prev: any) => ({
              ...prev,
              ...profileRes.data
            }));
          }
        } catch (e) {
          console.log('Profile refresh error after update:', e);
        }
        setTimeout(() => {
          sessionStorage.clear();
          sessionStorage.setItem('pendingToast', successMsg);
          window.location.href = '/auth/login';
        }, 1500);
      } else {
        Toast.error(apiRes?.message || 'Failed to update profile');
      }
    } catch (error: any) {
      Toast.error(error?.message || error || 'Failed to update profile');
      console.error('Update error:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleAmenityChange = (id: string) => {
    setSelectedAmenities((prev) =>
      prev.includes(id)
        ? prev.filter((item) => item !== id)
        : [...prev, id]
    );
  };

  const handleServiceChange = (id: string) => {
    setSelectedServices((prev) =>
      prev.includes(id)
        ? prev.filter((item) => item !== id)
        : [...prev, id]
    );
  };

  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 phoneVerify = async (e: any, mobile: any) => {
    e.preventDefault();
    if (verified.phone) {
      Toast.error('Phone number already verified!');
      return;
    }
    if (!mobile || mobile.length < 1) {
      Toast.error('Enter Phone Number!');
      return;
    }
    const minLength = value?.min_length || 6;
    const maxLength = value?.max_length || 15;
    if (mobile.length < minLength) {
      Toast.error(`Vendor contact number must be at least ${minLength} digits!`);
      return;
    }
    if (mobile.length > maxLength) {
      Toast.error(`Vendor contact number must not exceed ${maxLength} digits!`);
      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);
    } catch (error) {
      Toast.error(error);
    }
  };

  const handleDineOutChange = (checked: boolean) => {
    setIsDineOut(checked);
    if (!checked) {
      setSelectedAmenities([]);
      setSelectedServices([]);
      setEstimatedPricePerPlate(0);
      setBookingAmount(0);
    }
  };

  const ownerPhoneVerify = async (e: any, mobile: any) => {
    e.preventDefault();
    if (verified.ownerPhone) {
      Toast.error('Phone number already verified!');
      return;
    }
    if (!mobile || mobile.length < 1) {
      Toast.error('Enter Phone Number!');
      return;
    }
    const minLength = value?.min_length || 6;
    const maxLength = value?.max_length || 15;
    if (mobile.length < minLength) {
      Toast.error(`Owner contact number must be at least ${minLength} digits!`);
      return;
    }
    if (mobile.length > maxLength) {
      Toast.error(`Owner contact number must not exceed ${maxLength} digits!`);
      return;
    }

    try {
      let phoneNumber = ownerPhone || '';
      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, ownerPhone: true });
      sessionStorage.setItem('otpTokenPhone', apiRes?.token);
    } 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 });
    } 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 });
      }
    } 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 });
      }
    } catch (error) {
      Toast.error(error);
    }
  };
  const ownerPhoneOtpVerified = async (e: any) => {
    e.preventDefault();
    try {
      let payload = {
        otp: otp.ownerPhone
      };
      const apiRes = await apis.Auth.VerifyP(payload);
      if (apiRes) {
        sessionStorage.removeItem('otpTokenPhone');
        setOtpModal({ ...otpModal, ownerPhone: false });
        setVerified({ ...verified, ownerPhone: true });
      }
    } catch (error) {
      Toast.error(error);
    }
  };
  const handlePhoneChange = (e: any) => {
    const maxLen = value?.max_length || 15;
    const phoneNumber = e.target.value.replace(/\D/g, '').slice(0, maxLen);
    setState(phoneNumber);
    if (
      phoneNumber === userInfo?.restaurant_id?.restaurant_phone &&
      userInfo?.restaurant_id?.country_code === value?.dial_code
    ) {
      setVerified({ ...verified, phone: true });
    } else {
      setVerified({ ...verified, phone: false });
    }
  };
  const handleOwnerPhoneChange = (e: any) => {
    const maxLen = value?.max_length || 15;
    const phoneNumber = e.target.value.replace(/\D/g, '').slice(0, maxLen);
    setOwnerPhone(phoneNumber);
    if (
      phoneNumber === userInfo?.phone &&
      userInfo?.country_code === value?.dial_code
    ) {
      setVerified({ ...verified, ownerPhone: true });
    } else {
      setVerified({ ...verified, ownerPhone: false });
    }
  };
  const handleCheckboxChange = (option: string) => {
    setSelectedFoodTypes((prev) =>
      prev.includes(option)
        ? prev.filter((item) => item !== option)
        : [...prev, option]
    );
  };

  const handleAddressSelect = (addressPayload: any) => {
    setAddress(addressPayload);
  };

  const prefilledAddress = userInfo?.restaurant_id?.address;

  useEffect(() => {
    if (prefilledAddress) {
      setAddress(prefilledAddress);
    }
  }, [prefilledAddress]);

  // Check if any field has changed from initial values
  const hasChanges = () => {
    if (!initialValues) return false;

    const isArrayEqual = (arr1: any[], arr2: any[]) => {
      if (!arr1 || !arr2) return arr1 === arr2;
      if (arr1.length !== arr2.length) return false;
      return arr1.every((item, index) => {
        if (typeof item === 'object' && item !== null) {
          return JSON.stringify(item) === JSON.stringify(arr2[index]);
        }
        return item === arr2[index];
      });
    };

    return (
      formData.restaurantName !== initialValues.restaurantName ||
      state !== initialValues.contactNumber ||
      formData.avgpreptime?.toString() !== initialValues.avgpreptime?.toString() ||
      formData.ownerName !== initialValues.ownerName ||
      formData.email !== initialValues.email ||
      ownerPhone !== initialValues.ownerPhone ||
      image !== initialValues.image ||
      !isArrayEqual(selectedFoodTypes, initialValues.selectedFoodTypes) ||
      isDineOut !== initialValues.isDineOut ||
      estimatedPricePerPlate !== initialValues.estimatedPricePerPlate ||
      bookingAmount !== initialValues.bookingAmount ||
      !isArrayEqual(selectedAmenities, initialValues.selectedAmenities) ||
      !isArrayEqual(selectedServices, initialValues.selectedServices) ||
      JSON.stringify(address) !== JSON.stringify(initialValues.address) ||
      !isArrayEqual(restaurantMenu, initialValues.restaurantMenu) ||
      !isArrayEqual(restaurantPhotos, initialValues.restaurantPhotos)
    );
  };

  const isSaveDisabled = !(verified.phone && verified.ownerPhone) || !hasChanges();

  if (userInfo?.restaurant_id?.restaurant_type === 'home-cooked-meal') {
    return <HomeCookedProfile />;
  }

  if (userInfo?.restaurant_id?.type !== 'food') {
    return <GroceryProfile />;
  }

  return (
    <>
      <div className="p-4 pb-0">
        <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-3 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"
          />
          {!image && (
            <p className="mt-2 text-xs text-red-500 text-center">Vendor image is required</p>
          )}
        </div>

        <form className="w-full space-y-6">
          <div>
            <label className="text-sm font-medium text-[#0C1018]">
              Vendor Name
            </label>
            <Input
              name="restaurantName"
              className="mt-1 h-[45px]"
              placeholder="Enter vendor name"
              value={formData.restaurantName}
              onChange={handleChange}
              maxLength={15}
            />
          </div>

          <div>
            <label className="text-sm font-medium text-[#0C1018]">
              Vendor Contact Number
            </label>
            <div className="flex flex-row rounded-lg border border-solid transition-colors focus-within:border-[var(--primary-brand)]">
              <CountryPickerModal setValue={setValue} value={value} />
              <Input
                name="contactNumber"
                className=" h-[45px] border-none shadow-none"
                placeholder="Enter contact number"
                value={state}
                onChange={(e: any) => handlePhoneChange(e)}
                minLength={value?.min_length || 6}
                maxLength={value?.max_length || 15}
              />
              <button
                type="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>
          </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="theme-background h-11 w-full text-white"
              >
                {/* <Loader loading={loading} /> */}
                Verify
              </Button>
            </div>
          )}
          <div>
            <label className="text-sm font-medium text-[#0C1018]">
              Average Preparation time (in minutes) <span className="text-red-500">*</span>
            </label>
            <Input
              name="avgpreptime"
              className="mt-1 h-[45px]"
              placeholder="Enter average preparation time"
              value={formData.avgpreptime}
              onChange={handleChange}
              maxLength={15}
            />
            {(!formData.avgpreptime || formData.avgpreptime <= 0) && (
              <p className="mt-1 text-xs text-red-500">Average preparation time is required</p>
            )}
          </div>

          <div>
            <label className="text-sm font-medium text-[#0C1018]">
              Owner Name
            </label>
            <Input
              name="ownerName"
              className="mt-1 h-[45px]"
              placeholder="Enter owner name"
              value={formData.ownerName}
              onChange={handleChange}
            />
          </div>

          <div>
            <label className="text-sm font-medium text-[#0C1018]">
              Email address
            </label>
            <div className="flex flex-row rounded-lg border border-solid transition-colors focus-within:border-[var(--primary-brand)]">
              <Input
                type="email"
                name="email"
                className="mt-1 h-[45px] border-none shadow-none"
                placeholder="Enter email address"
                value={formData.email}
                onChange={handleChange}
              />
              <button
                type="button"
                className="flex h-[48px] items-center justify-center p-2 text-[14px] font-[600] text-[var(--primary-brand)]"
                onClick={(e: any) => emailVerify(e, formData.email)}
              >
                {verified.email ? 'Verified' : 'Verify'}
              </button>
            </div>
          </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="theme-background h-11 w-full text-white"
              >
                {/* <Loader loading={loading} /> */}
                Verify
              </Button>
            </div>
          )}

          <div>
            <label className="text-sm font-medium text-[#0C1018]">
              Owner Contact Number
            </label>
            <div className="flex flex-row rounded-lg border border-solid transition-colors focus-within:border-[var(--primary-brand)]">
              <CountryPickerModal setValue={setValue} value={value} />
              <Input
                name="ownercontactNumber"
                className=" h-[45px] border-none shadow-none"
                placeholder="Enter contact number"
                value={ownerPhone}
                onChange={(e: any) => handleOwnerPhoneChange(e)}
                minLength={value?.min_length || 6}
                maxLength={value?.max_length || 15}
              />
              <button
                type="button"
                className="flex h-[48px] items-center justify-center p-2 text-[14px] font-[600] text-[var(--primary-brand)]"
                onClick={(e: any) => ownerPhoneVerify(e, ownerPhone)}
              >
                {verified.ownerPhone ? 'Verified' : 'Verify'}
              </button>
            </div>
          </div>
          {otpModal.ownerPhone && (
            <div className="flex flex-row gap-4 space-y-1">
              <InputOTP
                className="w-full"
                maxLength={4}
                value={otp.ownerPhone}
                onChange={(value: string) =>
                  setOtp({ ...otp, ownerPhone: 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) => ownerPhoneOtpVerified(e)}
                className="theme-background h-11 w-full text-white"
              >
                {/* <Loader loading={loading} /> */}
                Verify
              </Button>
            </div>
          )}

          <div>
            <label className="flex items-center gap-2 text-sm font-medium text-[#0C1018]">
              <Checkbox
                checked={isDineOut}
                onCheckedChange={handleDineOutChange}
                className="data-[state=checked]:border-primary data-[state=checked]:bg-primary"
              />
              <span>Dine Out</span>
            </label>
          </div>

          {isDineOut && (
            <>
              <div>
                <label className="text-sm font-medium text-[#0C1018]">
                  Estimated Price Per Plate <span className="text-red-500">*</span>
                </label>
                <Input
                  name="estimatedPricePerPlate"
                  type="number"
                  min="0"
                  className="mt-1 h-[45px]"
                  placeholder="Enter estimated price per plate"
                  value={estimatedPricePerPlate}
                  onChange={(e) => setEstimatedPricePerPlate(Number(e.target.value))}
                />
                {(!estimatedPricePerPlate || estimatedPricePerPlate <= 0) && (
                  <p className="mt-1 text-xs text-red-500">Estimated price per plate is required</p>
                )}
              </div>

              <div>
                <label className="text-sm font-medium text-[#0C1018]">
                  Booking Amount <span className="text-red-500">*</span>
                </label>
                <Input
                  name="bookingAmount"
                  type="number"
                  min="0"
                  className="mt-1 h-[45px]"
                  placeholder="Enter booking amount"
                  value={bookingAmount}
                  onChange={(e) => setBookingAmount(Number(e.target.value))}
                />
                {bookingAmount < 0 && (
                  <p className="mt-1 text-xs text-red-500">Booking amount cannot be negative</p>
                )}
              </div>
              <div>
                <label className="text-sm font-medium text-[#0C1018]">
                  Select Amenities
                </label>
                <div className="grid grid-cols-2 gap-3 pt-2">
                  {amenities.map((amenity) => (
                    <label
                      key={amenity._id}
                      className="flex items-center gap-2 text-sm font-medium text-[#0C1018]"
                    >
                      <Checkbox
                        checked={selectedAmenities.includes(amenity._id)}
                        onCheckedChange={() => handleAmenityChange(amenity._id)}
                        className="data-[state=checked]:border-primary data-[state=checked]:bg-primary"
                      />
                      <span>{amenity.name}</span>
                    </label>
                  ))}
                </div>
              </div>

              <div>
                <label className="text-sm font-medium text-[#0C1018]">
                  Select Services
                </label>
                <div className="grid grid-cols-2 gap-3 pt-2">
                  {services.map((service) => (
                    <label
                      key={service._id}
                      className="flex items-center gap-2 text-sm font-medium text-[#0C1018]"
                    >
                      <Checkbox
                        checked={selectedServices.includes(service._id)}
                        onCheckedChange={() => handleServiceChange(service._id)}
                        className="data-[state=checked]:border-primary data-[state=checked]:bg-primary"
                      />
                      <span>{service.name}</span>
                    </label>
                  ))}
                </div>
              </div>


              <div>
                <label className="text-sm font-medium text-[#0C1018]">
                  Upload Vendor Menu <span className="text-red-500">*</span>
                </label>
                <MultiImages
                  images={restaurantMenu}
                  addImages={setRestaurantMenu}
                />
                {restaurantMenu.length === 0 && (
                  <p className="mt-1 text-xs text-red-500">Menu image is required</p>
                )}
              </div>

              <div>
                <label className="text-sm font-medium text-[#0C1018]">
                  Upload Vendor Photos <span className="text-red-500">*</span>
                </label>
                <MultiImages
                  images={restaurantPhotos}
                  addImages={setRestaurantPhotos}
                />
                {restaurantPhotos.length === 0 && (
                  <p className="mt-1 text-xs text-red-500">At least one vendor/store photo is required</p>
                )}
              </div>


            </>
          )}



          <div>
            <label className="text-sm font-medium text-[#0C1018]">
              Select Food Type
            </label>

            <div className="flex gap-4 pt-2">
              {foodTypes.map((option) => (
                <label
                  key={option}
                  className="flex items-center gap-2 text-sm font-medium text-[#0C1018]"
                >
                  <Checkbox
                    checked={selectedFoodTypes.includes(option)}
                    onCheckedChange={() => handleCheckboxChange(option)}
                    className="data-[state=checked]:border-primary data-[state=checked]:bg-primary"
                  />
                  <span className="capitalize">{option.replace('_', ' ')}</span>
                </label>
              ))}
            </div>
          </div>
          <div className="w-full">
            <label
              htmlFor="address-autocomplete"
              className="text-sm font-medium text-[#0C1018]"
            >
              Address <span className="text-red-500">*</span>
            </label>
            <div id="address-autocomplete">
              <GoogleAutocomplete
                initialValue={userInfo?.restaurant_id?.address?.name || ''}
                onAddressSelect={handleAddressSelect}
              />
            </div>
            {!address?.name && (
              <p className="mt-1 text-xs text-red-500">Address is required</p>
            )}
          </div>
        </form>
      </div>

      <div className="mt-6 p-6 pt-0">
        <p className="mb-2 text-sm text-gray-500">
          Note: After updating your profile, your request will be sent to admin for approval and you will be redirected to the login page.
        </p>
        <button
          onClick={handleUpdate}
          disabled={isSaveDisabled}
          className={`w-full rounded-lg py-3 font-medium text-white transition-colors ${isSaveDisabled
            ? 'bg-gray-400 cursor-not-allowed'
            : 'bg-[var(--primary-brand)] hover:bg-[var(--primary-brand)]'
            }`}
        >
          Save Changes
        </button>

      </div>
    </>
  );
}
