"use client";

import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { Eye, EyeOff } from "lucide-react";
import {
  Select,
  SelectGroup,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import Image from "next/image";
import loginImage from "@/src/assets/images/registeration/login.jpg";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import mailIcon from "@/src/assets/images/registeration/mailIcon.svg";
import { useRouter } from "next/navigation";
import termsIcon from "@/src/assets/images/registeration/termsIcon.svg";
import termsArr from "@/src/assets/images/registeration/termsArr.svg";
import { t } from "@/lib/i18n";
import { register } from "../Requests/register";
import { useGetCities } from "../Requests/useGetCities";

import CongatsCard from "../global/CongatsCard";

import "flag-icons/css/flag-icons.min.css";
import { getCountries, getCountryCallingCode } from "react-phone-number-input";
import { useGetFixedPages } from "../Requests/useGetFixedPages";
import parse from "html-react-parser";

export default function Register({
  formData,
  setFormData,
  step,
  setStep,
  lang,
}) {
  const [showPassword, setShowPassword] = useState(false);
  const [country, setCountry] = useState("");
  const [loading, setLoading] = useState(false);
  const [showSuccessModal, setShowSuccessModal] = useState(false);
  const router = useRouter();
  const [showTermsModal, setShowTermsModal] = useState(false);
  const [countrySearch, setCountrySearch] = useState("");
  const countries = getCountries(); // ["US","SA","EG",...]
  const { data: terms, isLoading: termsLoading } = useGetFixedPages(
    lang,
    "terms",
  );

  // Filter countries based on search term
  const filteredCountries = React.useMemo(() => {
    if (countrySearch.length < 2) {
      return countries;
    }
    const searchLower = countrySearch.toLowerCase();
    return countries.filter((iso2) => {
      const countryCode = getCountryCallingCode(iso2);
      return (
        countryCode.includes(searchLower) ||
        iso2.toLowerCase().includes(searchLower)
      );
    });
  }, [countrySearch, countries]);

  // Zod validation schema with translated messages
  const loginSchema = z
    .object({
      phone: z
        .string()
        .min(1, { message: t(lang, "phone_required") })
        .regex(/^[0-9]+$/, { message: t(lang, "phone_numbers_only") })
        .min(8, { message: t(lang, "phone_min_length") }),
      password: z
        .string()
        .min(1, { message: t(lang, "password_required") })
        .min(6, { message: t(lang, "repassword_min_length") }),
      name: z
        .string()
        .min(1, { message: t(lang, "name_required") })
        .min(2, { message: t(lang, "name_min_length_register") }),
      country: z.string().min(1, { message: t(lang, "country_required") }),
      email: z.string().email({ message: t(lang, "email_required") }),
      city: z.string().min(1, { message: t(lang, "city_required") }),
      repassword: z
        .string()
        .min(1, { message: t(lang, "repassword_required") })
        .min(6, { message: t(lang, "repassword_min_length") }),
      terms: z.boolean().refine((val) => val === true, {
        message: t(lang, "terms_required"),
      }),
    })
    .refine((data) => data.password === data.repassword, {
      message: t(lang, "password_mismatch"),
      path: ["repassword"],
    });
  const { data: cities, isLoading: citiesLoading } = useGetCities(lang);

  const form = useForm({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      phone: formData?.phone || "",
      name: formData?.name || "",
      email: formData?.email || "",
      password: "",
      country: "+966 SA" || formData?.country || "",
      city: formData?.city || "",
      repassword: "",
      terms: false,
    },
  });

  const onSubmit = (data) => {
    setFormData({ ...formData, ...data });
    register(data, setLoading, lang, setStep, router, setShowSuccessModal);
  };

  return (
    <div
      className="login-container max-w-2xl mx-auto"
      style={{ direction: lang == "ar" ? "rtl" : "ltr" }}
    >
      {/* Terms and Conditions Modal */}
      {showSuccessModal && (
        <CongatsCard
          title={t(lang, "congratulations")}
          description={t(lang, "account_created_successfully")}
        />
      )}
      {showTermsModal && (
        <div className="modal-overlay" onClick={() => setShowTermsModal(false)}>
          <div className="terms-modal" onClick={(e) => e.stopPropagation()}>
            <button
              className="terms-modal-close"
              onClick={() => setShowTermsModal(false)}
              type="button"
            >
              <svg
                width="24"
                height="24"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
              >
                <circle cx="12" cy="12" r="10" />
                <line x1="15" y1="9" x2="9" y2="15" />
                <line x1="9" y1="9" x2="15" y2="15" />
              </svg>
            </button>
            <div className="terms-modal-header-cont">
              <div className="terms-modal-header">
                <div className="terms-modal-icon">
                  <Image src={termsIcon} alt="terms-icon" />
                </div>
                <h2 className="terms-modal-title">
                  {t(lang, "terms_modal_title")}
                </h2>
                <div className="terms-modal-arr">
                  <Image src={termsArr} alt="terms-icon" />
                </div>
              </div>
            </div>

            <div className="terms-modal-content">
              <h3 className="terms-modal-subtitle">
                {t(lang, "terms_modal_subtitle")}
              </h3>
              <p className="terms-modal-text">
                {termsLoading || !terms ? (
                  <span className="loader-btn"></span>
                ) : (
                  parse(terms?.description)
                )}
              </p>
            </div>

            <Button
              type="button"
              className="terms-modal-button"
              onClick={() => {
                form.setValue("terms", true);
                setShowTermsModal(false);
              }}
            >
              {t(lang, "accept_terms_button")}
            </Button>
          </div>
        </div>
      )}
      <div className="login-card ">
        <div className="login">
          {/* Form Section */}
          <div className="login-form-section">
            <div className="login-header">
              <h1 className="login-title">{t(lang, "register_title")}</h1>
              <p className="login-subtitle">{t(lang, "register_subtitle")}</p>
            </div>

            <Form {...form}>
              <form
                onSubmit={form.handleSubmit(onSubmit)}
                className="login-form"
              >
                {/* Name Field */}
                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem className="from-input-wrapper-password">
                      <FormLabel className="password-label">
                        {t(lang, "full_name_label")}
                      </FormLabel>
                      <FormControl>
                        <div
                          className={`password-input-wrapper ${form.formState.errors.name ? "error-password" : form.formState.isDirty && field.value ? "success-password" : ""}`}
                        >
                          <Input
                            {...field}
                            type="text"
                            placeholder={t(lang, "full_name_placeholder")}
                            className="password-input name-input"
                          />
                        </div>
                      </FormControl>
                      <FormMessage className="password-error" />
                    </FormItem>
                  )}
                />
                {/* Phone Number Field */}
                <FormField
                  control={form.control}
                  name="phone"
                  render={({ field }) => (
                    <FormItem className="from-input-wrapper-mobile">
                      <FormLabel className="password-label">
                        {t(lang, "phone_label")}
                      </FormLabel>
                      <FormControl>
                        <div
                          className={`input-of-mobile-num ${
                            form.formState.errors.phone ||
                            form.formState.errors.country
                              ? "error-mob-input"
                              : form.formState.isDirty &&
                                  field.value &&
                                  country &&
                                  !form.formState.errors.phone &&
                                  !form.formState.errors.country
                                ? "success-mob-input"
                                : ""
                          }`}
                        >
                          <div className="country-select">
                            <FormField
                              control={form.control}
                              name="country"
                              render={({ field }) => (
                                <FormItem>
                                  <FormControl>
                                    <Select
                                      value={field.value}
                                      onValueChange={(value) => {
                                        setCountry(value);
                                        field.onChange(value);
                                      }}
                                      onOpenChange={(open) => {
                                        if (!open) {
                                          setCountrySearch("");
                                        }
                                      }}
                                    >
                                      <SelectTrigger className="country-select-trigger ">
                                        <SelectValue
                                          placeholder={t(lang, "Country")}
                                        />
                                      </SelectTrigger>
                                      <SelectContent
                                        dir={lang === "ar" ? "rtl" : "ltr"}
                                        className="min-w-[250px]"
                                      >
                                        <div className="px-2 py-1.5 sticky top-0 bg-white dark:bg-gray-950 z-10">
                                          <Input
                                            placeholder={
                                              t(lang, "search_country") +
                                              " " +
                                              t(lang, "example") +
                                              " SA"
                                            }
                                            value={countrySearch}
                                            onChange={(e) =>
                                              setCountrySearch(e.target.value)
                                            }
                                            className="h-8"
                                            onClick={(e) => e.stopPropagation()}
                                            dir={lang === "ar" ? "rtl" : "ltr"}
                                          />
                                        </div>
                                        {filteredCountries?.map(
                                          (iso2, index) => (
                                            <SelectItem
                                              value={`+${getCountryCallingCode(iso2)} ${iso2}`}
                                              key={index}
                                              dir={lang == "ar" ? "rtl" : "ltr"}
                                            >
                                              <div className="code-country-slug-cont">
                                                <div className="select-country-item-cont">
                                                  <span>
                                                    <span
                                                      className={`fi fi-${iso2.toLowerCase()}`}
                                                    />{" "}
                                                    +
                                                    {getCountryCallingCode(
                                                      iso2,
                                                    )}
                                                  </span>
                                                </div>
                                              </div>
                                            </SelectItem>
                                          ),
                                        )}
                                        {filteredCountries?.length === 0 && (
                                          <div className="px-2 py-6 text-center text-sm text-gray-500">
                                            {t(lang, "no_countries_found")}
                                          </div>
                                        )}
                                      </SelectContent>
                                    </Select>
                                  </FormControl>
                                  <FormMessage
                                    className="hidden"
                                    id="country-error"
                                  />
                                </FormItem>
                              )}
                            />
                          </div>
                          <Input
                            type="tel"
                            className="phone-input"
                            style={{ direction: lang === "ar" ? "rtl" : "ltr" }}
                            placeholder={t(lang, "phone_placeholder")}
                            {...field}
                            onKeyPress={(e) => {
                              if (!/[0-9]/.test(e.key)) {
                                e.preventDefault();
                              }
                            }}
                          />
                        </div>
                      </FormControl>
                      <div className="flex items-center justify-between">
                        <FormMessage id="phone-error" />
                        {form.formState.errors.country && (
                          <p className="country-error">
                            {form.formState.errors.country?.message}
                          </p>
                        )}
                      </div>
                    </FormItem>
                  )}
                />
                {/* Email Field */}
                <FormField
                  control={form.control}
                  name="email"
                  render={({ field }) => (
                    <FormItem className="from-input-wrapper-password">
                      <FormLabel className="password-label">
                        {t(lang, "email_label")}
                      </FormLabel>
                      <FormControl>
                        <div
                          className={`password-input-wrapper ${form.formState.errors.email ? "error-password" : form.formState.isDirty && field.value ? "success-password" : ""}`}
                        >
                          <Input
                            {...field}
                            type="email"
                            placeholder={t(lang, "email_placeholder")}
                            className="password-input name-input"
                          />
                          <div className="field-icon">
                            <Image
                              className="eye-icon"
                              src={mailIcon}
                              alt="mailIcon"
                            />
                          </div>
                        </div>
                      </FormControl>
                      <FormMessage className="password-error" />
                    </FormItem>
                  )}
                />
                {/* City Field */}
                <FormField
                  control={form.control}
                  name="city"
                  render={({ field }) => (
                    <FormItem className="from-input-wrapper-password">
                      <FormLabel className="password-label">
                        {t(lang, "city_label")}
                      </FormLabel>
                      <FormControl>
                        <Select
                          onValueChange={(value) => {
                            field.onChange(value);
                          }}
                          value={field.value}
                          disabled={cities?.length === 0 || citiesLoading}
                        >
                          <SelectTrigger
                            className={`password-input-wrapper ${form.formState.errors.city ? "error-password" : field.value ? "success-password" : ""}`}
                            style={{ direction: lang === "ar" ? "rtl" : "ltr" }}
                          >
                            <SelectValue placeholder={t(lang, "city_label")} />
                          </SelectTrigger>
                          <SelectContent>
                            {cities?.map((city) => (
                              <SelectItem
                                key={city.id}
                                value={city.id}
                                dir={lang === "ar" ? "rtl" : "ltr"}
                              >
                                {city.name}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </FormControl>
                      <FormMessage className="password-error" />
                    </FormItem>
                  )}
                />
                {/* Password Field */}
                <FormField
                  control={form.control}
                  name="password"
                  render={({ field }) => (
                    <FormItem className="from-input-wrapper-password">
                      <FormLabel className="password-label">
                        {t(lang, "password_label")}
                      </FormLabel>
                      <FormControl>
                        <div
                          className={`password-input-wrapper ${form.formState.errors.password ? "error-password" : form.formState.isDirty && field.value ? "success-password" : ""}`}
                        >
                          <Input
                            {...field}
                            type={showPassword ? "text" : "password"}
                            placeholder={t(lang, "password_placeholder")}
                            className="password-input"
                          />
                          <button
                            type="button"
                            onClick={() => setShowPassword(!showPassword)}
                            className="field-icon"
                          >
                            {showPassword ? (
                              <EyeOff className="eye-icon" />
                            ) : (
                              <Eye className="eye-icon" />
                            )}
                          </button>
                        </div>
                      </FormControl>
                      <FormMessage className="password-error" />
                    </FormItem>
                  )}
                />
                {/* RePassword Field */}
                <FormField
                  control={form.control}
                  name="repassword"
                  render={({ field }) => (
                    <FormItem className="from-input-wrapper-password">
                      <FormLabel className="password-label">
                        {t(lang, "confirm_password_label")}
                      </FormLabel>
                      <FormControl>
                        <div
                          className={`password-input-wrapper ${form.formState.errors.password ? "error-password" : form.formState.isDirty && field.value ? "success-password" : ""}`}
                        >
                          <Input
                            {...field}
                            type={showPassword ? "text" : "password"}
                            placeholder={t(
                              lang,
                              "confirm_password_placeholder",
                            )}
                            className="password-input"
                          />
                          <button
                            type="button"
                            onClick={() => setShowPassword(!showPassword)}
                            className="field-icon"
                          >
                            {showPassword ? (
                              <EyeOff className="eye-icon" />
                            ) : (
                              <Eye className="eye-icon" />
                            )}
                          </button>
                        </div>
                      </FormControl>
                      <FormMessage className="password-error" />
                    </FormItem>
                  )}
                />
                {/* Terms and Conditions Checkbox */}
                <FormField
                  control={form.control}
                  name="terms"
                  render={({ field }) => (
                    <FormItem className="terms-checkbox-wrapper">
                      <div className="terms-checkbox-container">
                        <FormControl>
                          <input
                            type="checkbox"
                            checked={field.value}
                            onChange={field.onChange}
                            className="terms-checkbox"
                            id="terms"
                          />
                        </FormControl>
                        <label htmlFor="terms" className="terms-label">
                          {t(lang, "agree_terms")}{" "}
                          <button
                            type="button"
                            onClick={(e) => {
                              e.preventDefault();
                              setShowTermsModal(true);
                            }}
                            className="terms-link"
                          >
                            {t(lang, "terms_and_conditions")}
                          </button>
                        </label>
                      </div>
                      <FormMessage className="terms-error" />
                    </FormItem>
                  )}
                />

                {/* Submit Button */}
                <Button
                  type="submit"
                  className="submit-btn"
                  disabled={!form.formState.isValid && !form.formState.isDirty}
                >
                  {loading ? (
                    <span className="loader-btn"></span>
                  ) : (
                    <span>{t(lang, "register_button")}</span>
                  )}
                </Button>
              </form>
            </Form>
          </div>

          {/* Image Section */}
          {/* <div className="login-image-section">
                        <Image
                            src={loginImage}
                            alt="login"
                            fill
                            className="login-image"
                            priority
                        />
                    </div> */}
        </div>
      </div>
    </div>
  );
}
