"use client";
import Select from "react-select";
import { FaChevronDown } from "react-icons/fa";
import Button from "@/components/common/Button";
import React, { useState, useEffect } from 'react';
import { useForm, FormProvider, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { toast } from "react-toastify";
import { contactSchema, ContactSchemaType } from "@/lib/validations/authSchema";
import { useTranslations } from "next-intl";
import Input from "@/components/common/CustomInputField";
import { useRouter } from "next/navigation";
import { useAppSelector, useAppDispatch } from "@/app/store/hooks";
import { checkAuthErrorGet } from "@/lib/checkAuthError";
import { submitContactRequest } from "@/lib/actions/contactRequestAction";
import Link from "next/link";
import { useSelectTheme } from "@/hooks/useSelectTheme";

type OptionType = {
  value: string;
  label: string;
};

export default function Contact() {
  const { user } = useAppSelector((state) => state?.auth);
  const t = useTranslations();

  const dispatch = useAppDispatch();
  const router = useRouter();
  const [countryCode, setCountryCode] = useState("");


  function extractMobileNumber(
    fullNumber: string,
    countryCode: string
  ): string {
    const cleanNumber = fullNumber.replace(/^\+/, "");
    const cleanCode = countryCode.replace(/^\+/, "");
    const regex = new RegExp(`^${cleanCode}`);
    return cleanNumber.replace(regex, "");
  }

  const options: OptionType[] = [
    {
      value: t('contact_page.reason_fees'),
      label: t('contact_page.reason_fees'),
    },
    {
      value: t('contact_page.reason_refund'),
      label: t('contact_page.reason_refund'),
    },
    { value: t('contact_page.reason_annual_subscription'), label: t('contact_page.reason_annual_subscription') },
    { value: t('contact_page.reason_members'), label: t('contact_page.reason_members') },
    {
      value: t('contact_page.reason_replies'),
      label: t('contact_page.reason_replies'),
    },
  ];

  const options2: OptionType[] = [
    { value: t('contact_page.subreason_payment_methods'), label: t('contact_page.subreason_payment_methods') },
    { value: t('contact_page.subreason_calculating_fees'), label: t('contact_page.subreason_calculating_fees') },
    { value: t('contact_page.subreason_fees_reduction'), label: t('contact_page.subreason_fees_reduction') },
    { value: t('contact_page.subreason_notice_payment_fees'), label: t('contact_page.subreason_notice_payment_fees') },
    { value: t('contact_page.subreason_old_sale'), label: t('contact_page.subreason_old_sale') },
    { value: t('contact_page.subreason_make_fees_buyer'), label: t('contact_page.subreason_make_fees_buyer') },
  ];

  const {themeKey, customStyles} = useSelectTheme();

  const faqs = [
    {
      question: t('contact_page.faq_how_pay_fees_q'),
      answer: t('contact_page.faq_how_pay_fees_a'),
    },
    {
      question: t('contact_page.faq_deleted_offer_q'),
      answer: t('contact_page.faq_deleted_offer_a'),
    },
    {
      question: t('contact_page.faq_paid_fee_not_appear_q'),
      answer: t('contact_page.faq_paid_fee_not_appear_a'),
    },
  ];

  const [openIndex, setOpenIndex] = useState<number | null>(0);

  const toggleIndex = (index: number) => {
    setOpenIndex((prev) => (prev === index ? null : index));
  };

  const methods = useForm<ContactSchemaType & { phone_number?: string }>({

    resolver: zodResolver(contactSchema(t)),
  });
  const {
    handleSubmit,
    control,
    setValue,
    formState: { errors, isSubmitting },
  } = methods;

  const onSubmit = async (data: ContactSchemaType & { phone_number?: string }) => {
    try {
      // Extract contact number and country code from phone
      const contactNumber = extractMobileNumber(data.phone_number || "", countryCode);
      const payload = {
        ...data,
        countryCode,
        contactNumber,
      };
      const res = await submitContactRequest(payload, user?.token);
      toast.success(t('contact_page.message_sent'));
      methods.reset();
    } catch (error: any) {
      if (checkAuthErrorGet(error, dispatch, router)) return;
      toast.error(error?.response?.data?.message || t('validation.error_msg'));
    }
  };

  return (
    <div className="px-6 bg-gradient-to-b from-white to-kzsoftBlue max-lg:min-h-px dark:from-background dark:to-background max-sm:bg-white max-sm:to-white">
      <div className="contact-wrapper max-w-wxl2 mx-auto py-5">
        <div className="flex flex-col lg:flex-row min-h-[500px]">
          <div className="w-full mb-6 lg:mb-0 max-lg:hidden">
            <img
              src="/contact-img.webp"
              alt="Help Center"
              className="w-full max-h-[851px] h-full object-cover"
            />
          </div>
          <div className="w-full py-10 px-[20px] border-neutrals100 border bg-white max-h-[851px] overflow-y-auto max-lg:overflow-visible max-lg:max-h-full max-lg:min-h-[560px] max-sm:px-0 max-sm:bg-transparent max-sm:border-hidden max-sm:pt-1 dark:bg-card dark:border-darkborder max-sm:dark:!bg-background">
            <div className="text-center">
              <h2 className="text-2xl font-bold text-neutrals800 mb-2 dark:text-white max-md:text-xl">
                {t('contact_page.title')}
              </h2>
              <p className="text-neutrals500 text-sm dark:text-neutrals400">
                {t('contact_page.description')}
              </p>
            </div>
            <FormProvider {...methods}>
              <form
                onSubmit={handleSubmit(onSubmit)}
                className="space-y-4 relative"
              >
                <div className="select-wrap py-10 pb-8">
                  <label
                    htmlFor="reason"
                    className="block text-sm font-medium text-neutrals800 mb-1 dark:text-neutrals400"
                  >
                    {t('contact_page.reason_label')}<span className="text-sm text-red-500">*</span>
                  </label>
                  <Controller
                    name="mainReason"
                    control={control}
                    rules={{ required: "Reason is required" }}
                    render={({ field }) => (
                      <Select
                        {...field}
                        id="reason"
                        options={options}
                        placeholder="Select"
                        key={themeKey}
                        styles={customStyles}
                        components={{ IndicatorSeparator: () => null }}
                        value={options.find((opt) => opt.value === field.value) || null}
                        onChange={(option) => {
                          field.onChange((option as OptionType)?.value || "");
                          setValue("subReason", "");
                        }}
                        isClearable
                      />
                    )}
                  />
                  {errors.mainReason && (
                    <p className="text-red-800 text-sm mt-1 dark:text-red-500">
                      {errors.mainReason.message as string}
                    </p>
                  )}

                  {methods.watch("mainReason") && (
                    <div className="mt-5">
                      <label
                        htmlFor="reason2"
                        className="block text-sm font-medium text-neutrals800 mb-1 dark:text-neutrals400"
                      >
                        {t('contact_page.sub_reason_label')}<span className="text-sm text-red-500">*</span>
                      </label>
                      <Controller
                        name="subReason"
                        control={control}
                        rules={{ required: "Sub Reason is required" }}
                        render={({ field }) => (
                          <Select
                            {...field}
                            id="reason2"
                            options={options2}
                            placeholder="Select"
                            key={themeKey}
                            styles={customStyles}
                            components={{ IndicatorSeparator: () => null }}
                            value={options2.find((opt) => opt.value === field.value) || null}
                            onChange={(option) => field.onChange((option as OptionType)?.value || "")}
                            isClearable
                          />
                        )}
                      />
                      {errors.subReason && (
                        <p className="text-red-800 text-sm mt-1 dark:text-red-500">
                          {errors.subReason.message as string}
                        </p>
                      )}
                    </div>
                  )}

                  {methods.watch("subReason") && (
                    <div className="contact-form space-y-4">
                      <div className="my-5 border border-neutrals100 rounded dark:border-cardfooter">
                        {faqs.map((faq, index) => (
                          <div
                            key={index}
                            className="border-b border-neutrals100 last:border-b-0 dark:border-cardfooter"
                          >
                            <button
                              className={`w-full text-left p-3 px-2 pr-3 text-sm font-medium flex justify-between items-center transition-colors duration-200 ${
                                openIndex === index
                                  ? "text-primary500 dark:text-primary400"
                                  : "text-neutrals800 dark:text-neutrals300"
                              }`}
                              onClick={() => toggleIndex(index)}
                              type="button"
                            >
                              {faq.question}
                              <FaChevronDown
                                className={`transform transition-transform w-[18px] text-neutrals500 duration-200 ${
                                  openIndex === index
                                    ? "rotate-180 text-primary500"
                                    : ""
                                }`}
                              />
                            </button>
                            {openIndex === index && (
                              <div className="pb-4 text-sm px-2 text-neutrals500 whitespace-pre-line dark:text-neutrals400">
                                {faq.answer}
                              </div>
                            )}
                          </div>
                        ))}
                      </div>
                      <Input
                        label={t('contact_page.first_name_label')}
                        name="firstName"
                        placeholder={t('contact_page.first_name_placeholder')}
                        required
                      />
                      <Input
                        label={t('contact_page.last_name_label')}
                        name="lastName"
                        placeholder={t('contact_page.last_name_placeholder')}
                        required
                      />
                      <Input
                        label={t('contact_page.email_label')}
                        name="email"
                        placeholder={t('contact_page.email_placeholder')}
                        type="email"
                        required
                      />
                      <Input
                            label={t('contact_page.contact_number_label')}
                            type="country_code_phone"
                            name="phone_number"
                            placeholder={t('contact_page.contact_number_placeholder')}
                            setCountryCode={setCountryCode}
                            required
                          />
                      <Input
                        label={t('contact_page.description_label')}
                        name="description"
                        type="textarea"
                        placeholder={t('contact_page.description_placeholder')}
                        required
                      />
                      <div className="text-center mt-5">
                        <Button
                          type="submit"
                          label={
                            isSubmitting
                              ? t("contact_page.sending")
                              : t("contact_page.send_message")
                          }
                          variant="secondary"
                          className="mx-auto min-w-[233px] md:flex items-center justify-center"
                          disabled={isSubmitting}
                        >
                          {isSubmitting ? (
                            <div
                              role="status"
                              className="flex items-center justify-center"
                            >
                              <svg
                                className="animate-spin -ml-1 mr-2 h-4 w-4 text-white"
                                xmlns="http://www.w3.org/2000/svg"
                                fill="none"
                                viewBox="0 0 24 24"
                              >
                                <circle
                                  className="opacity-25"
                                  cx="12"
                                  cy="12"
                                  r="10"
                                  stroke="currentColor"
                                  strokeWidth="4"
                                ></circle>
                                <path
                                  className="opacity-75"
                                  fill="currentColor"
                                  d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                                ></path>
                              </svg>
                              <span className="sr-only">
                                {t("button.loading")}
                              </span>
                            </div>
                          ) : null}
                        </Button>
                      </div>
                    </div>
                  )}
                </div>
              </form>
            </FormProvider>
            <Link
              href="/faq"
              className="block text-primary500 text-sm text-center font-medium hover:underline dark:text-primary400"
            >
              {t('contact_page.view_all_faqs')}
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
