'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, useState } from 'react';
import apis, { BUCKET_ROOT } from '@/utils/apis';
import { useGlobalContext } from '@/context/Provider';
import { useRouter, useSearchParams } from 'next/navigation';
import Loader from '@/components/common/loader';
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 countries from '@/utils/CountryCode.json';
import { MultiImages } from '../common/MultipleDropzone';

// ✅ Updated schema with restaurantPhotos
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.string().optional(),
  email: z.string().min(3, 'Email is required').email('Enter a valid email'),
  phone_number: z.string().optional(),
  restaurantPhotos: z
    .array(z.record(z.any()))
    .min(3, 'At least 3 images are required'), // ⬅️ Added
  referral_code: z.string().optional()
});

type LoginForm = z.infer<typeof formSchema>;

const Login = () => {
  const { Toast, userInfo, setUserInfo } = useGlobalContext();
  const [loading, setLoading] = useState(false);
  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 [otp, setOtp] = useState({ phone: '', email: '' });
  const [errMsg, setErrMsg] = useState('');
  const router = useRouter();
  const form = useForm<LoginForm>({
    resolver: zodResolver(formSchema),
    defaultValues: { restaurantPhotos: [], referral_code: '' } // ⬅️ Added
  });

  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((prev) => ({ ...prev, phone: true }));
    } else {
      setVerified((prev) => ({ ...prev, phone: false }));
    }
  }, [value]);

  useEffect(() => {
    if (res === 'complete') {
      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 || '');
      form.setValue(
        'restaurantPhotos',
        (userInfo?.restaurant_id?.uploadRestaurantPhotos || []).map((key: string) => ({
          id: key,
          fullUrl: BUCKET_ROOT + key,
          name: key
        }))
      );
      form.setValue('referral_code', userInfo?.restaurant_id?.referral_code || '');
      setState(userInfo?.restaurant_id?.restaurant_phone);
      const matchedCountry = countries.find(
        (c) =>
          c.dial_code ===
          (userInfo?.restaurant_id?.country_code ||
            `+${userInfo?.restaurant_id?.country_code}`)
      );
      setValue(matchedCountry);
      setVerified({ email: true, phone: true });
    } else {
      setState(decodedToken.phone);
      const matchedCountry = countries.find(
        (c) =>
          c.dial_code ===
          (decodedToken.country_code || `+${decodedToken.country_code}`)
      );
      setValue(matchedCountry);
      setVerified((prev) => ({ ...prev, phone: true }));
    }
  }, []);

  const handlePhoneChange = (e: any) => {
    const phoneNumber = e.target.value.replace(/\D/g, '');
    setState(phoneNumber);
    setVerified({
      ...verified,
      phone:
        phoneNumber === decodedToken.phone &&
        decodedToken.country_code === value?.dial_code
    });
  };

  const phoneVerify = async (e: any, mobile: any) => {
    e.preventDefault();
    if (verified.phone) return Toast.error('Phone already verified!');
    if (!mobile) return Toast.error('Enter phone number!');
    try {
      let phoneNumber = state || '';
      let dialCode = value?.dial_code || '';
      if (phoneNumber.startsWith(dialCode))
        phoneNumber = phoneNumber.slice(dialCode.length);
      const 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 phoneOtpVerified = async (e: any) => {
    e.preventDefault();
    try {
      const apiRes = await apis.Auth.VerifyP({ otp: otp.phone });
      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 emailVerify = async (e: any, mail: string) => {
    e.preventDefault();
    if (!mail) return Toast.error('Enter valid email!');
    if (verified.email) return Toast.error('Email already verified!');
    try {
      const apiRes = await apis.Auth.verifyPhoneEmail({ email: mail });
      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 {
      const apiRes = await apis.Auth.VerifyE({ otp: otp.email });
      if (apiRes) {
        sessionStorage.removeItem('otpTokenEmail');
        setOtpModal({ ...otpModal, email: false });
        setVerified({ ...verified, email: true });
        Toast.success('Email verified successfully!');
      }
    } catch (error) {
      Toast.error(error);
    }
  };

  // ⬅️ Added handler for restaurant photos
  const handleRestaurantPhotosImages = (data: any) => {
    form.setValue('restaurantPhotos', data);
  };

  const onSubmit = async (data: LoginForm) => {
    if (!verified.phone) return Toast.error('Verify phone number!');
    if (!verified.email) return Toast.error('Verify email!');

    try {
      let phoneNumber = state || '';
      let dialCode = value?.dial_code || '';
      if (phoneNumber.startsWith(dialCode))
        phoneNumber = phoneNumber.slice(dialCode.length);

      const type = searchParams.get('type') || '';
      const isStore = type === 'grocery';

      const payload = {
        restaurant_type: 'restaurant',
        restaurant_name: data?.name,
        restaurant_phone: phoneNumber,
        country_code: dialCode,
        average_preparing_time: Number(data?.avg_prepare || 0),
        owner_name: data?.owner_name,
        email: data?.email,
        uploadRestaurantPhotos:
          data?.restaurantPhotos?.map((img: any) => `${img.url}`) || [],
        isFoodDelivery: true,
        isDineOut: false,
        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 searchParams = useSearchParams();
  const type = searchParams.get('type') || '';
  const isStore = type === 'grocery';

  return (
    <section className="w-full">
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-4">
            {/* Restaurant Name */}
            <FormField
              name="name"
              control={form.control}
              render={({ field }) => (
                <FormItem>
                  <FormLabel className="text-black">{isStore ? 'Store Name' : 'Vendor Name'}</FormLabel>
                  <FormControl>
                    <Input
                      placeholder={isStore ? 'Store Name' : 'Vendor Name'}
                      {...field}
                      className="h-[48px] bg-white"
                      onChange={(e) => {
                        const sanitizedValue = e.target.value.replace(/^\s+/, '');
                        field.onChange(sanitizedValue);
                      }}
                      maxLength={30}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Phone Number */}
            <div className="space-y-1">
              <Label className="text-black">
                {isStore ? 'Store Contact Number' : '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={handlePhoneChange}
                />
                <button
                  className="flex h-[48px] items-center justify-center p-2 text-[14px] font-[600] text-[var(--primary-brand)]"
                  onClick={(e) => phoneVerify(e, state)}
                >
                  {verified.phone ? 'Verified' : 'Verify'}
                </button>
              </div>
              <span className="text-[12px] font-[400] text-red-600">
                {errMsg}
              </span>
              {otpModal.phone && (
                <div className="mt-2 flex flex-row gap-4">
                  <InputOTP
                    className="w-full"
                    maxLength={4}
                    value={otp.phone}
                    onChange={(val) => setOtp({ ...otp, phone: val })}
                  >
                    {[...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={phoneOtpVerified}
                    className="h-11 w-full"
                    variant={'theme'}
                  >
                    Verify
                  </Button>
                </div>
              )}
            </div>

            {/* Average Preparation Time */}
            {!isStore && (
              <FormField
                name="avg_prepare"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-black">
                      Average Preparation Time (minutes)
                    </FormLabel>
                    <FormControl>
                      <Input
                        placeholder="Enter average preparation time"
                        {...field}
                        className="h-[48px] bg-white"
                        onChange={(e) =>
                          field.onChange(e.target.value.replace(/\D/g, ''))
                        }
                        maxLength={3}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            )}

            {/* Owner Name */}
            <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] 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>
              )}
            />

            {/* Email */}
            <div className="space-y-1">
              <FormField
                name="email"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-black">Email</FormLabel>
                    <FormControl>
                      <div className="flex flex-row bg-white border border-gray-200 rounded-md transition-colors focus-within:border-[var(--primary-brand)]">
                        <Input
                          placeholder="Email address"
                          {...field}
                          className="h-[48px] border-none bg-white"
                          onChange={(e) => {
                            field.onChange(e.target.value.trim());
                            if (e.target.value === userInfo?.email)
                              setVerified({ ...verified, email: true });
                            else setVerified({ ...verified, email: false });
                          }}
                        />
                        <button
                          className="flex h-[48px] items-center justify-center p-2 text-[14px] font-[600] text-[var(--primary-brand)]"
                          onClick={(e) => emailVerify(e, field.value)}
                        >
                          {verified.email ? 'Verified' : 'Verify'}
                        </button>
                      </div>
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {otpModal.email && (
                <div className="mt-2 flex flex-row gap-4">
                  <InputOTP
                    className="w-full"
                    maxLength={4}
                    value={otp.email}
                    onChange={(val) => setOtp({ ...otp, email: val })}
                  >
                    {[...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={emailOtpVerified}
                    className="h-11 w-full"
                    variant={'theme'}
                  >
                    Verify
                  </Button>
                </div>
              )}
            </div>


          </div>

          {/* ⬅️ Upload Restaurant Photos */}
          <FormField
            control={form.control}
            name="restaurantPhotos"
            render={({ field }) => (
              <FormItem>
                <FormLabel className="text-black">
                  {isStore ? 'Upload Store Photos' : 'Upload Vendor Photos'}
                </FormLabel>
                <FormControl>
                  <MultiImages
                    addImages={handleRestaurantPhotosImages}
                    images={field.value}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* Submit */}
          <Button
            className="h-[48px] w-full"
            variant={'theme'}
            type="submit"
          >
            <Loader loading={loading} />
            Next
          </Button>
        </form>
      </Form>
    </section>
  );
};

export default function FormThree() {
  return <Login />;
}
