'use client';

import AuthLayout from '@/components/layout/layout';
import authBanner from '@/assets/images/AuthImages/address.png';
import FormOne from '../../../../components/deliveryForm/deliveryForm';
import FormTwo from '../../../../components/DineOutOrComboForm/DineOutOrComboForm';
import { FormField, FormItem, FormLabel } from '@/components/ui/form';
import { Checkbox } from '@/components/ui/checkbox';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { FormProvider, useForm, useWatch } from 'react-hook-form';
import { useEffect, useMemo, useState } from 'react';
import HomeCookedForm from '@/components/HomeCookedForm/page';
import { useGlobalContext } from '@/context/Provider';
import { useSearchParams } from 'next/navigation';
import FormThree from '@/components/FormThree/FormThree';
import { Info } from 'lucide-react';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger
} from '@/components/ui/tooltip';

const formSchema = z.object({
  serviceType: z.enum(['restaurant', 'home-cooked', 'both-home-rest'], {
    required_error: 'Please select a service type'
  }),
  restaurantServices: z.array(z.enum(['Food delivery', 'Dine-out'])).optional()
});

type FormValues = z.infer<typeof formSchema>;

const Login = ({ userInfo }: { userInfo?: any }) => {
  const [foodDelivery, setFoodDelivery] = useState(false);
  const [isBothServiceSelected, setIsBothServiceSelected] = useState(false);
  const { setUserInfo } = useGlobalContext();
  const searchParams = useSearchParams();

  const slug = searchParams.get('slug');

  const defaultType = 'restaurant';

  const defaultServices: ('Food delivery' | 'Dine-out')[] = [];
  if (userInfo?.isFoodDelivery) defaultServices.push('Food delivery');
  if (userInfo?.isDineOut) defaultServices.push('Dine-out');

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      serviceType: defaultType,
      restaurantServices:
        defaultType === 'restaurant'
          ? defaultServices.length > 0
            ? defaultServices
            : ['Food delivery']
          : []
    }
  });

  const watchServiceType = form.watch('serviceType');
  const watchRestaurantServices =
    useWatch({ control: form.control, name: 'restaurantServices' }) || [];

  useEffect(() => {
    setIsBothServiceSelected(watchServiceType === 'both-home-rest');
  }, [watchServiceType]);

  useEffect(() => {
    setFoodDelivery(watchRestaurantServices.includes('Food delivery'));
  }, [watchRestaurantServices]);

  useEffect(() => {
    if (watchServiceType === 'home-cooked') {
      setUserInfo((prev: any) => ({
        ...prev,
        isFoodDelivery: false,
        isDineOut: false
      }));
    } else if (watchServiceType === 'restaurant' || watchServiceType === 'both-home-rest') {
      setUserInfo((prev: any) => ({
        ...prev,
        isFoodDelivery: watchRestaurantServices.includes('Food delivery'),
        isDineOut: watchRestaurantServices.includes('Dine-out')
      }));
    }
  }, [watchServiceType, watchRestaurantServices, setUserInfo]);

  const onSubmit = (data: FormValues) => {
  };

  if (slug !== 'food') {
    return (
      <section className="w-full">
        <FormThree />
      </section>
    );
  }

  return (
    <section className="w-full">
      <FormProvider {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="mb-8 space-y-6">
          {/* <FormField
            name="serviceType"
            control={form.control}
            render={({ field }) => (
              <FormItem>
                <FormLabel className="text-lg text-black">
                  Will you be providing vendor or home-cooked meal services?
                  <span className="ml-2 inline-block align-middle">
                    <TooltipProvider>
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <Info className="h-4 w-4 cursor-pointer text-black-500 hover:text-gray-700" />
                        </TooltipTrigger>
                        <TooltipContent className="max-w-xs p-4">
                          <div className="space-y-2 text-sm text-white">
                            <p>
                              <span className="font-semibold">Vendor:</span> Dine-in and delivery services.
                            </p>
                            <p>
                              <span className="font-semibold">Cloud Kitchen:</span>{' '}
                              Delivery-only service with Auto-Renew Orders.
                            </p>
                          </div>
                        </TooltipContent>
                      </Tooltip>
                    </TooltipProvider>
                  </span>

                </FormLabel>
                <RadioGroup
                  onValueChange={field.onChange}
                  value={field.value}
                  className="mt-3 flex gap-6"
                >
                  <div className="flex items-center space-x-2">
                    <RadioGroupItem value="restaurant" id="restaurant" />
                    <label htmlFor="restaurant" className="text-sm text-gray-600">
                      Vendor
                    </label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <RadioGroupItem value="home-cooked" id="home-cooked" />
                    <label htmlFor="home-cooked" className="text-sm text-gray-600">
                      Cloud Kitchen
                    </label>

                  </div>
                  <div className="flex items-center space-x-2">
                    <RadioGroupItem value="both-home-rest" id="both-home-rest" />
                    <label htmlFor="both-home-rest" className="text-sm text-gray-600">
                      Both
                    </label>
                  </div>
                </RadioGroup>
              </FormItem>
            )}
          /> */}

          {(watchServiceType === 'restaurant' || watchServiceType === 'both-home-rest') && (
            <FormField
              name="restaurantServices"
              control={form.control}
              render={({ field }) => {
                const selectedServices = field.value || [];
                return (
                  <FormItem>
                    <FormLabel className="text-base font-bold text-slate-900">Vendor services</FormLabel>
                    <div className="mt-3 flex flex-wrap gap-3">
                      {(['Food delivery', 'Dine-out'] as const).map((service) => {
                        const isChecked = selectedServices.includes(service);
                        return (
                          <label
                            key={service}
                            htmlFor={service}
                            className={`flex items-center gap-2.5 cursor-pointer px-4 py-2.5 rounded-xl border text-sm 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={service}
                              checked={isChecked}
                              onCheckedChange={(checked) => {
                                const newValue = checked
                                  ? [...selectedServices, service]
                                  : selectedServices.filter((item) => item !== service);
                                field.onChange(newValue);
                                setUserInfo((prev: any) => ({
                                  ...prev,
                                  isFoodDelivery: newValue.includes('Food delivery'),
                                  isDineOut: newValue.includes('Dine-out')
                                }));
                              }}
                            />
                            <span>{service}</span>
                          </label>
                        );
                      })}
                    </div>
                  </FormItem>
                );
              }}
            />
          )}
        </form>
      </FormProvider>

      {
        (watchServiceType === 'restaurant' || watchServiceType === 'both-home-rest') && (
          <>
            {watchRestaurantServices.includes('Food delivery') &&
              !watchRestaurantServices.includes('Dine-out') && (
                <FormOne isBoth={isBothServiceSelected} />
              )}
            {watchRestaurantServices.includes('Dine-out') && (
              <FormTwo
                foodDelivery={foodDelivery}
                dineOut={true}
                isBoth={isBothServiceSelected}
              />
            )}
          </>
        )
      }

      {watchServiceType === 'home-cooked' && <HomeCookedForm />}
    </section >
  );
};

export default function LoginPage() {
  const searchParams = useSearchParams();
  const type = searchParams.get('type');
  const isStore = type === 'grocery';

  const userInfo = {
    isFoodDelivery: true,
    isDineOut: true,
    isHomeCooked: false
  };

  return (
    <AuthLayout
      title={isStore ? 'Enter your Store Details' : 'Enter your Vendor Details'}
      des={isStore ? 'To get started, please provide the essential details of your store.' : 'To get started, please provide the essential details of your restaurant.'}
      image={authBanner.src}
    >
      <Login userInfo={userInfo} />
    </AuthLayout>
  );
}
