'use client';
import React, { useRef, useState } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { SelectItem, useDisclosure } from '@heroui/react';
import ReCaptcha from 'react-google-recaptcha';
import Select from '@/components/base/Select';
import TextField from '@/components/base/TextField';
import Button from '@/components/base/Button';
import CheckBox from '@/components/base/CheckBox';
import PhoneInput from '@/components/base/PhoneInput';
import Container from '@/components/layout/Container';

export interface IContactFormValues {
  title: string;
  firstName: string;
  lastName: string;
  email: string;
  mobile: string;
  mobileNumber: string;
  dialCode: string;
  residence?: string;
  unitType: string;
  unitSize?: string;
  budget?: string;
  terms: boolean;
  purpose: string;
  recaptchaToken: string;
}

// export interface IContactForm {
//   title?: string;
//   footerText?: string;
//   titleOptions: ISelectOption[];
//   budgetOptions: ISelectOption[];
//   purposeOptions: ISelectOption[];
//   unitSizeOptions: ISelectOption[];
//   unitTypeOptions: ISelectOption[];
//   labels: IFormLabels;
//   onSubmit: (values: IContactFormValues) => Promise<IResponse>;
// }

const defaultValues = {
  title: '',
  firstName: '',
  lastName: '',
  email: '',
  mobile: '+20',
  mobileNumber: '',
  dialCode: '',
  //optional
  residence: '',
  unitType: '',
  //optional
  unitSize: '',
  //optional
  budget: '',
  purpose: '',
  terms: false
};
const ContactForm: React.FC<IContactForm> = ({
  title,
  footerText,
  titleOptions,
  budgetOptions,
  purposeOptions,
  unitSizeOptions,
  unitTypeOptions,
  labels,
  onSubmit
}) => {
  const {
    control,
    handleSubmit,
    setValue,
    reset,
    getValues,
    formState: { errors }
  } = useForm<IContactFormValues>({
    defaultValues
  });
  const recaptchaRef = useRef<ReCaptcha>(null);
  const [recaptchaError, setRecaptchaError] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [formStatus, setFormStatus] = useState<'success' | 'error' | null>(
    null
  );

  const handleRecaptchaChange = (value: string | null) => {
    if (value) {
      // Clear any previous error
      setRecaptchaError('');
    }
  };

  const submit = async (values: IContactFormValues) => {
    setFormStatus(null);
    const recaptchaValue = recaptchaRef?.current?.getValue();
    console.log('recaptchaValue', recaptchaValue);
    if (!recaptchaValue) {
      setRecaptchaError(labels.errorRecaptchaRequired);
      return;
    }

    setIsSubmitting(true);
    const response = await onSubmit({
      ...values,
      recaptchaToken: recaptchaValue
    });
    console.log('response', response);
    recaptchaRef?.current?.reset();

    if (response.success) {
      reset();
      setFormStatus('success');
      onOpenChange();
    } else {
      console.error(response.code);
      setFormStatus('error');
    }
    setIsSubmitting(false);
  };

  const resetRecaptcha = () => {
    recaptchaRef?.current?.reset();
    setRecaptchaError('');
  };

  const handleReset = () => {
    reset();
    resetRecaptcha();
    setFormStatus(null);
  };

  const { isOpen, onClose, onOpenChange } = useDisclosure();

  return (
    <section className="dark bg-default-100 text-foreground mb-6 py-12">
      {/* <FormSuccessModal
        isOpen={isOpen}
        onClose={onClose}
        onOpenChange={onOpenChange}
        title="Thank you for your enquiry"
        description="We'll be in touch with you in the next 24 business hours."
        button={{
          label: 'Home',
          url: '/'
        }}
      /> */}
      <Container className="overflow-hidden lg:px-40">
        {title && (
          <h1 className="text-center text-4xl mb-10 font-serif md:text-5xl">
            {title}
          </h1>
        )}
        <form onSubmit={handleSubmit(submit)}>
          {/* ✅ Controlled Select for Title */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-10 gap-y-4 items-start">
            <Controller
              name="title"
              control={control}
              rules={{ required: labels?.errorTitleRequired || '' }}
              render={({ field }) => (
                <Select
                  {...field}
                  label={labels?.title}
                  isInvalid={!!errors?.title}
                  errorMessage={errors?.title?.message}
                  selectedKeys={field.value ? [field.value] : []} // Ensure value resets
                  onSelectionChange={(keys: any) =>
                    field.onChange([...keys][0])
                  }>
                  {(titleOptions || []).map((data) => (
                    <SelectItem
                      key={data.value}
                      classNames={{ base: 'rounded-none' }}>
                      {data.label}
                    </SelectItem>
                  ))}
                </Select>
              )}
            />
            {/* ✅ First Name */}
            <Controller
              name="firstName"
              control={control}
              rules={{
                required: labels.errorFirstNameRequired || '',
                pattern: {
                  value: /^[A-Za-z]+$/,
                  message: labels.errorFirstNameInvalid || ''
                }
              }}
              render={({ field }) => (
                <TextField
                  {...field}
                  variant="underlined"
                  isInvalid={!!errors?.firstName}
                  errorMessage={errors?.firstName?.message || ''}
                  label={labels?.firstName}
                />
              )}
            />
            {/* */}
            {/* ✅ Last Name with Controller */}
            <Controller
              name="lastName"
              control={control}
              rules={{
                required: labels.errorLastNameRequired || '',
                pattern: {
                  value: /^[A-Za-z]+$/,
                  message: labels.errorLastNameInvalid || ''
                }
              }}
              render={({ field }) => (
                <TextField
                  {...field}
                  variant="underlined"
                  isInvalid={!!errors?.lastName}
                  errorMessage={errors?.lastName?.message || ''}
                  label={labels?.lastName}
                />
              )}
            />
            {/* ✅ Email */}
            <Controller
              name="email"
              control={control}
              rules={{
                required: labels.errorEmailRequired || '',
                pattern: {
                  value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
                  message: labels.errorEmailInvalid || ''
                }
              }}
              render={({ field }) => (
                <TextField
                  {...field}
                  label={labels?.email}
                  isInvalid={!!errors?.email}
                  errorMessage={errors?.email?.message}
                />
              )}
            />
            {/* ✅ Mobile */}

            <div className="relative z-20 isolate mt-4 sm:mt-0">
              <Controller
                name="mobile"
                control={control}
                defaultValue=""
                rules={{
                  required: errors.mobile?.message,
                  validate: (value) => {
                    if (!/^\d{6,15}$/.test(value)) {
                      return labels.errorMobileInvalid;
                    }
                    return true;
                  }
                }}
                render={({ field }) => (
                  <PhoneInput
                    {...field}
                    label={labels.mobile}
                    enableSearch
                    name={field.name}
                    isInValid={!!errors.mobile}
                    onBlur={field.onBlur}
                    onChange={(value, parts) => {
                      if ('dialCode' in parts) {
                        const mobileNumber = value.replace(parts.dialCode, '');
                        setValue('dialCode', parts.dialCode);
                        setValue('mobileNumber', mobileNumber);
                        field.onChange(value);
                      }
                    }}
                  />
                )}
              />
              {!!errors.mobile && (
                <p className="text-danger text-[12px]">
                  {errors.mobile?.message}
                </p>
              )}
            </div>
            {/* ✅ Country of Residence */}
            <Controller
              name="residence"
              control={control}
              render={({ field }) => (
                <TextField
                  {...field}
                  className="sm:mt-[0.85rem]"
                  label={labels?.residence}
                  isInvalid={!!errors?.residence}
                  errorMessage={errors?.residence?.message}
                />
              )}
            />
            {/* ✅ Unit Type */}
            <Controller
              name="unitType"
              control={control}
              rules={{ required: labels?.errorUnitTypeRequired || '' }}
              render={({ field }) => (
                <Select
                  {...field}
                  label={labels?.unitType}
                  isInvalid={!!errors?.unitType}
                  errorMessage={errors?.unitType?.message}
                  selectedKeys={field.value ? [field.value] : []} // Ensure value resets
                  onSelectionChange={(keys: any) =>
                    field.onChange([...keys][0])
                  }>
                  {(unitTypeOptions || []).map((data) => (
                    <SelectItem
                      key={data.value}
                      classNames={{ base: 'rounded-none' }}>
                      {data.label}
                    </SelectItem>
                  ))}
                </Select>
              )}
            />

            {/* unit size */}
            <Controller
              name="unitSize"
              control={control}
              render={({ field }) => (
                <Select
                  {...field}
                  label={labels?.unitSize}
                  isInvalid={!!errors?.unitSize}
                  errorMessage={errors?.unitSize?.message}
                  selectedKeys={field.value ? [field.value] : []} // Ensure value resets
                  onSelectionChange={(keys: any) =>
                    field.onChange([...keys][0])
                  }>
                  {(unitSizeOptions || []).map((data) => (
                    <SelectItem
                      key={data.value}
                      classNames={{ base: 'rounded-none' }}>
                      {data.label}
                    </SelectItem>
                  ))}
                </Select>
              )}
            />
            <Controller
              name="budget"
              control={control}
              render={({ field }) => (
                <Select
                  {...field}
                  label={labels?.budget}
                  isInvalid={!!errors?.budget}
                  errorMessage={errors?.budget?.message}
                  selectedKeys={field.value ? [field.value] : []} // Ensure value resets
                  onSelectionChange={(keys: any) =>
                    field.onChange([...keys][0])
                  }>
                  {(budgetOptions || []).map((data) => (
                    <SelectItem
                      key={data.value}
                      classNames={{ base: 'rounded-none' }}>
                      {data.label}
                    </SelectItem>
                  ))}
                </Select>
              )}
            />
            <Controller
              name="purpose"
              control={control}
              rules={{
                required: labels?.errorPurposeRequired || ''
              }}
              render={({ field }) => (
                <Select
                  {...field}
                  label={labels?.purpose}
                  isInvalid={!!errors?.purpose}
                  errorMessage={errors?.purpose?.message}
                  selectedKeys={field.value ? [field.value] : []} // Ensure value resets
                  onSelectionChange={(keys: any) =>
                    field.onChange([...keys][0])
                  }>
                  {(purposeOptions || []).map((data) => (
                    <SelectItem
                      key={data.value}
                      classNames={{ base: 'rounded-none' }}>
                      {data.label}
                    </SelectItem>
                  ))}
                </Select>
              )}
            />
            <div className="flex items-center flex-col gap-5 mt-6 sm:col-span-2">
              <Controller
                name="terms"
                control={control}
                rules={{
                  required: labels.errorTermsRequired
                }}
                render={({ field }) => (
                  <div className="my-2  relative z-0">
                    <div className="flex items-center">
                      <CheckBox
                        isSelected={field.value || false}
                        onValueChange={field.onChange}
                        isInvalid={!!errors?.terms}>
                        <label
                          className="text-sm font-inter [&_a]:underline [&_a]:isolate [&_a]:relative [&_a]:z-20"
                          dangerouslySetInnerHTML={{
                            __html: labels.terms
                          }}
                        />
                      </CheckBox>
                    </div>
                    {errors?.terms?.message && (
                      <p className="text-tiny text-danger ms-8">
                        {errors?.terms?.message}
                      </p>
                    )}
                  </div>
                )}
              />

              <ReCaptcha
                ref={recaptchaRef}
                size="normal"
                sitekey={process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY as string}
                onChange={handleRecaptchaChange}
                onExpired={resetRecaptcha}
              />
              {recaptchaError && (
                <div className="text-danger text-small">{recaptchaError}</div>
              )}
              {/* {formStatus === 'success' && (
                <div className="text-success text-small">
                  {labels.formSuccessText}
                </div>
              )} */}

              {formStatus === 'error' && (
                <div className="text-danger text-small">
                  {labels.formErrorText}
                </div>
              )}
            </div>
            {/* ✅ Submit Button */}
            <div className="w-full flex gap-6 sm:gap-10 sm:justify-center mt-6 *:!basis-full flex-wrap sm:col-span-2 ">
              <Button
                className="grow sm:max-w-60"
                type="submit"
                color="primary"
                isLoading={isSubmitting}>
                {labels.submitButtonLabel}
              </Button>
              <Button
                className="grow sm:max-w-60 dark:bg-black dark:text-white"
                type="button"
                color="primary"
                variant="ghost"
                onPress={handleReset}
                isDisabled={isSubmitting}>
                {labels.clearButtonLabel}
              </Button>
            </div>
            {footerText && (
              <p className="mt-5 text-medium opacity-50 text-center sm:col-span-2">
                {footerText}
              </p>
            )}
          </div>
        </form>
      </Container>
    </section>
  );
};

export default ContactForm;
