'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 React, { useEffect, useState } from 'react';
import apis from '@/utils/apis';
import { useGlobalContext } from '@/context/Provider';
import { useRouter } from 'next/navigation';
import Loader from '@/components/common/loader';
import AuthLayout from '@/components/layout/layout';
import authBanner from '@/assets/images/AuthImages/address.png';
import { Icons } from '@/components/icons';
import GoogleMapComponent from '@/components/Map/GoogleMap';

const formSchema = z.object({
  address1: z.string().min(3, 'Name is required'),
  address2: z.string().optional(),
  country: z.string().min(3, 'Owner name is required'),
  city: z.string().min(3, 'Owner name is required'),
  landmark: z.string().optional()
});
type LoginForm = z.infer<typeof formSchema>;

const Login = (props: any) => {
  const { Toast, userInfo, setUserInfo } = useGlobalContext();
  const restaurant_id = userInfo?.restaurant_id;
  const res: any = sessionStorage.getItem('restaurant');
  const [loading, setLoading] = useState(false);
  const [place, setPlace] = useState<any>(null);
  const [address, setAddress] = useState({
    place: '',
    location: {
      lat: 30.7069892,
      lng: 76.6870682
    }
  });
  const [locate, setLocate] = useState({
    lat: 30.7069892,
    long: 76.6870682
  });
  const router = useRouter();
  const form = useForm<LoginForm>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      landmark: undefined
    }
  });

  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 onSubmit = async (data: LoginForm) => {
    const res_id: any = sessionStorage.getItem('resId');

    try {
      let payload: any = {
        address: {
          name: data.address1,
          city: data.city,
          lat: address?.location?.lat,
          long: address?.location?.lng
        }
      };

      if (data.address2) payload.address.area = data.address2;
      if (data.landmark) payload.address.nearby_landmark = data.landmark;

      setLoading(true);

      const apiRes = await apis.restaurant.update(res_id, payload);

      setUserInfo((prev: any) => ({
        ...prev,
        isFoodDelivery: prev?.isFoodDelivery ?? false,
        isDineOut: prev?.isDineOut ?? false,
        restaurant_id: {
          ...(prev?.restaurant_id || {}),
          address: {
            ...prev?.restaurant_id?.address,
            ...payload.address
          }
        }
      }));

      // Now read the latest flags from updated userInfo
      const latestUserInfo = {
        ...userInfo,
        ...payload.address
      };
      const isFoodDelivery = latestUserInfo?.isFoodDelivery;
      const isDineOut = latestUserInfo?.isDineOut;

      if (apiRes) {
        const type = userInfo?.restaurant_id?.type;
        const isDineOutCategory = type === "dine-out";
        if (isFoodDelivery && isDineOut) {
          router.replace('/auth/restaurant/restauranttimings');
        } else if (isFoodDelivery && !isDineOut) {
          router.replace('/auth/restaurant/restauranttimings');
        } else if (!isFoodDelivery && isDineOut && isDineOutCategory) {
          router.replace('/auth/restaurant/dineouttimings');
        } else {
          router.replace('/auth/restaurant/restauranttimings');
        }
      }
    } catch (error) {
      Toast.error(error);
    } finally {
      setLoading(false);
    }
  };



  const requestCurrenctLocation = () => {
    try {
      if (!location) {
        // setLocationModal(true)
      }
      navigator.geolocation.getCurrentPosition(
        (successCallback) => {
          // getLocationName(successCallback.coords.latitude, successCallback.coords.longitude)
          const latitude = successCallback?.coords?.latitude;
          const longitude = successCallback?.coords?.longitude;
          setLocate({ lat: latitude, long: longitude } as any);
          // setLocate({ lat: Number(restaurant_id?.address?.lat), long: Number(restaurant_id?.address?.log) } as any);
        },
        (errorCallback) => {
          Toast.error(
            `We need your permission to access your location to provide a better experience. Please enable location services in your browser settings.`
          );
        }
      );
    } catch (error) {
    }
  };
  useEffect(() => {
    if (place) {
      const addressComponents = place.address_components || [];

      const getComponent = (type: string) => {
        const component = addressComponents.find((comp: any) =>
          comp.types.includes(type)
        );
        return component ? component.long_name : '';
      };
      const sublocality =
        getComponent('sublocality_level_1') || getComponent('sublocality');
      const sublocality2 = getComponent('sublocality_level_2');
      const city = getComponent('locality');
      const country = getComponent('country');

      form.setValue('address1', sublocality);
      form.setValue('address2', sublocality2 || '');
      form.setValue('country', country);
      form.setValue('city', city);
    }
  }, [place]);

  useEffect(() => {
    let token: any = sessionStorage.getItem('token');
    // if (res !== "complete") {
    //   requestCurrenctLocation();
    // }
    if (!token) {
      router.replace(`/auth/login`);
    }
  }, [res]);

  useEffect(() => {
    if (res === "complete" && userInfo) {
      const restaurant_id = userInfo.restaurant_id;
      setPlace({
        formatted_address: restaurant_id?.address?.area + ',' + restaurant_id?.address?.name + ',' + restaurant_id?.address?.city
      });
      form.setValue('address1', restaurant_id?.address?.area || '');
      form.setValue('address2', restaurant_id?.address?.name || '');
      form.setValue('city', restaurant_id?.address?.city || '');

      const savedLat = restaurant_id?.address?.lat;
      const savedLong = restaurant_id?.address?.long || restaurant_id?.address?.log;
      if (savedLat && savedLong) {
        setLocate({
          lat: Number(savedLat),
          long: Number(savedLong)
        });
      }
    }
  }, [res, userInfo]);

  return (
    <>
      <section className="h-auto w-full">
        {props?.searchParams?.type == 'address' ? (
          <>
            <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">
                  <FormField
                    name="address1"
                    control={form.control}
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel className="text-black">
                          Address Line
                        </FormLabel>
                        <FormControl>
                          <Input
                            placeholder="Shop no / Building no"
                            {...field}
                            className={`h-[48px] ${form.formState.errors.address1
                              ? 'error-border'
                              : ''
                              } bg-white`}
                            onChange={(e) => {
                              const sanitizedValue = e.target.value.replace(
                                /^\s+/,
                                ''
                              );
                              field.onChange(sanitizedValue);
                            }}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    name="address2"
                    control={form.control}
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel className="text-black">
                          Address Line 2 (optional)
                        </FormLabel>
                        <FormControl>
                          <Input
                            placeholder="Floor / tower"
                            {...field}
                            className={`h-[48px] ${form.formState.errors.address2
                              ? 'error-border'
                              : ''
                              } bg-white`}
                            onChange={(e) => {
                              const sanitizedValue = e.target.value.replace(
                                /^\s+/,
                                ''
                              );
                              field.onChange(sanitizedValue);
                            }}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

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

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

                  <div className="md:col-span-2">
                    <FormField
                      name="landmark"
                      control={form.control}
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel className="text-black">Landmark</FormLabel>
                          <FormControl>
                            <Input
                              placeholder="Add any nearby landmark"
                              {...field}
                              className={`h-[48px] ${form.formState.errors.landmark
                                ? 'error-border'
                                : ''
                                } bg-white`}
                              onChange={(e) => {
                                const sanitizedValue = e.target.value.replace(
                                  /^\s+/,
                                  ''
                                );
                                field.onChange(sanitizedValue);
                              }}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </div>
                </div>

                <Button
                  className="h-11 w-full"
                  variant={'theme'}
                  type="submit"
                >
                  <Loader loading={loading} />
                  Next
                </Button>
              </form>
            </Form>
          </>
        ) : (
          <>
            <div className="map-styled-wrapper w-full">
              <div className="map-wrapper w-full">
                <GoogleMapComponent
                  defaultCenter={{ lat: locate?.lat, lng: locate.long }}
                  setAddress={setAddress}
                  setPlace={setPlace}
                />
              </div>
              <div className="mt-5">
                {place?.formatted_address.length > 0 && (
                  <div className="mb-2 flex items-center gap-2">
                    <Icons.LocationMarker />{' '}
                    <span>{place?.formatted_address}</span>
                  </div>
                )}

                <Button
                  className="h-11 w-full"
                  variant={'theme'}
                  type="button"
                  onClick={() =>
                    router.push(`/auth/restaurant/location?type=address`)
                  }
                >
                  <Loader loading={loading} />
                  Next
                </Button>
              </div>
            </div>
          </>
        )}
        {/* */}
      </section>
    </>
  );
};

export default function LoginPage(props: any) {

  return (
    <AuthLayout
      isMap={props?.searchParams?.type == 'map'}
      title={
        props?.searchParams?.type == 'address'
          ? 'Complete Vendor Address'
          : 'Vendor Location'
      }
      des={
        props?.searchParams?.type == 'address'
          ? 'To get started, please provide the essential details of your vendor.'
          : ''
      }
      image={authBanner.src}
    >
      <Login {...props} />
    </AuthLayout>
  );
}
