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

const formSchema = z.object({
  name: z.string().min(3, 'Name is required'),
  //   restaurant_phone_number: z.string().min(3, 'Phone number 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')
  ]),
  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' }),
  cuisine_ids: z.array(z.string()).min(1, 'Select at least one cuisine'),
  // 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 = {
  isBoth: boolean;
};

const Login = ({ 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 [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 [cuisines, setCuisines] = useState<any[]>([]);
  const router = useRouter();
  const [blobFile, setBlobFile] = useState<File | null>(null);
  const form = useForm<LoginForm>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      phone_number: undefined,
      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);

  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(() => {
    const fetchCuisines = async () => {
      try {
        const res = await apis.Cuisine.getCuisine();
        setCuisines(res?.data || []);
      } catch (error) {
        Toast.error(error);
      }
    };
    fetchCuisines();
  }, []);

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

      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 || '');
      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);
      setVerified({ email: true, phone: true });
      form.setValue(
        'phone_number',
        (userInfo?.country_code || '') + (userInfo?.phone || '')
      );
      form.setValue('category', userInfo?.restaurant_id?.food_type || '');
      form.setValue('cuisine_ids', userInfo?.restaurant_id?.cuisine_ids || []);
      form.setValue(
        'catering_services',
        userInfo?.restaurant_id?.catering_services || []
      );
      form.setValue('referral_code', userInfo?.restaurant_id?.referral_code || '');
    } 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,
        country_code: dialCode,
        food_type: data?.category,
        average_preparing_time: Number(data?.avg_prepare),
        // subscribers_limit: Number(data?.subscribers_limit) || 0,
        isFoodDelivery: true,
        isDineOut: false,
        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 || ''
      };
      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: true,
          isDineOut: false,
          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 (mobile.length < 1) {
      Toast.error('Enter Phone Number!');
    }

    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);
      sessionStorage.setItem('otpTokenPhone', apiRes?.token);
      setOtpModal({ ...otpModal, phone: true });
      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(error);
    } 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 (
      phoneNumber === decodedToken.phone &&
      decodedToken.country_code === value?.dial_code
    ) {
      setVerified({ ...verified, phone: true });
    } else {
      setVerified({ ...verified, phone: false });
    }
  };
  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;
  };

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

  return (
    <>
      <section className="w-full">
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
            <div className="relative mx-auto mb-6 h-[140px] w-[140px]">
              {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>

            {/* 2-Column Responsive Form Fields Grid */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-4">
              <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 className="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 border border-gray-200 transition-colors focus-within:border-[var(--primary-brand)]"
                >
                  <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);

                      const phoneNumber = e.target.value.replace(/\D/g, '');
                      setState(phoneNumber);

                      if (errMsg) {
                        setErrMsg('');
                      }
                    }}
                    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>
                {otpModal.phone && (
                  <div className="flex flex-row gap-4 space-y-1 mt-2">
                    <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
                      onClick={(e: any) => phoneOtpVerified(e)}
                      className="h-11 w-full"
                      variant={'theme'}
                    >
                      Verify
                    </Button>
                  </div>
                )}
              </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) => {
                            const sanitizedValue = e.target.value.replace(
                              /\D/g,
                              ''
                            );
                            field.onChange(sanitizedValue);
                          }}
                          maxLength={3}
                        />
                      </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+/, '')
                              .replace(/[^A-Za-z\s]/g, '')
                              .replace(/\s{2,}/g, ' ');

                            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 rounded-md border border-gray-200 transition-colors focus-within:border-[var(--primary-brand)] ${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>
                  )}
                />
                {otpModal.email && (
                  <div className="flex flex-row gap-4 space-y-1 mt-2">
                    <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
                      onClick={(e: any) => emailOtpVerified(e)}
                      className="h-11 w-full"
                      variant={'theme'}
                    >
                      Verify
                    </Button>
                  </div>
                )}
              </div>


            </div>
            {/* {isBoth && (
              <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>
            )} */}

            <div className="rounded-2xl border border-slate-200 bg-white p-5 sm:p-6 shadow-2xs space-y-5">
              <FormField
                name="cuisine_ids"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-base font-bold text-slate-900">Cuisines</FormLabel>
                    <p className="text-xs text-slate-500 mt-0.5 mb-3">
                      Select types or styles of food your restaurant prepares
                    </p>
                    <FormControl>
                      <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2.5">
                        {cuisines?.map((item) => {
                          const isChecked = (field.value || []).includes(item._id);
                          return (
                            <label
                              key={item._id}
                              htmlFor={item._id}
                              className={`flex items-center gap-2 cursor-pointer px-3.5 py-2.5 rounded-xl border text-xs font-semibold transition-all ${
                                isChecked
                                  ? 'border-[var(--primary-brand)] bg-[var(--orange-50)] text-[var(--primary-brand)] shadow-2xs'
                                  : 'border-slate-200 bg-white text-slate-700 hover:border-slate-300 hover:bg-slate-50'
                              }`}
                            >
                              <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);
                                }}
                              />
                              <span className="truncate">{item.name}</span>
                            </label>
                          );
                        })}
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <div className="border-t border-slate-100 pt-4">
                <FormField
                  name="catering_services"
                  control={form.control}
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="text-sm font-bold text-slate-900">
                        Do you provide Catering Services?
                      </FormLabel>
                      <FormControl>
                        <RadioGroup
                          onValueChange={(val) => field.onChange(val === 'yes')}
                          value={field.value ? 'yes' : 'no'}
                          className="mt-2.5 flex gap-3"
                        >
                          <label
                            htmlFor="catering-yes"
                            className={`flex items-center gap-2.5 cursor-pointer px-5 py-2.5 rounded-xl border text-xs font-semibold transition-all ${
                              field.value === true
                                ? 'border-[var(--primary-brand)] bg-[var(--orange-50)] text-[var(--primary-brand)] shadow-2xs'
                                : 'border-slate-200 bg-white text-slate-700 hover:border-slate-300'
                            }`}
                          >
                            <RadioGroupItem value="yes" id="catering-yes" />
                            <span>Yes, we provide catering</span>
                          </label>
                          <label
                            htmlFor="catering-no"
                            className={`flex items-center gap-2.5 cursor-pointer px-5 py-2.5 rounded-xl border text-xs font-semibold transition-all ${
                              field.value === false
                                ? 'border-[var(--primary-brand)] bg-[var(--orange-50)] text-[var(--primary-brand)] shadow-2xs'
                                : 'border-slate-200 bg-white text-slate-700 hover:border-slate-300'
                            }`}
                          >
                            <RadioGroupItem value="no" id="catering-no" />
                            <span>No catering</span>
                          </label>
                        </RadioGroup>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <div className="border-t border-slate-100 pt-4">
                <FormField
                  name="category"
                  control={form.control}
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="text-sm font-bold text-slate-900">
                        What kind of food does this restaurant serve?
                      </FormLabel>
                      <FormControl>
                        <div className="mt-2.5 flex flex-wrap gap-2.5">
                          {foodCategories.map((category) => {
                            const isChecked = field.value?.includes(category);
                            return (
                              <label
                                key={category}
                                htmlFor={category}
                                className={`flex items-center gap-2.5 cursor-pointer px-4 py-2.5 rounded-xl border text-xs font-semibold transition-all ${
                                  isChecked
                                    ? 'border-[var(--primary-brand)] bg-[var(--orange-50)] text-[var(--primary-brand)] shadow-2xs'
                                    : 'border-slate-200 bg-white text-slate-700 hover:border-slate-300'
                                }`}
                              >
                                <Checkbox
                                  id={category}
                                  checked={isChecked}
                                  onCheckedChange={(checked) => {
                                    const newValue = checked
                                      ? [...(field.value || []), category]
                                      : field.value?.filter(
                                          (item: string) => item !== category
                                        );
                                    field.onChange(newValue);
                                    sessionStorage.setItem(
                                      'category',
                                      JSON.stringify(newValue)
                                    );
                                  }}
                                />
                                <span>
                                  {category
                                    .split('_')
                                    .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
                                    .join(' ')}
                                </span>
                              </label>
                            );
                          })}
                        </div>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </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 FormOneProps = {
  isBoth: boolean;
};

export default function FormOne({ isBoth }: FormOneProps) {
  return <Login isBoth={isBoth} />;
}
