import React, { useEffect, useState } from "react";
import { useRouter } from "next/router";
import { useTranslation } from "react-i18next";
import { useAuth } from "@/context/helpers/auth/AuthContext";
import SEO from "@/components/shared/SEO";
import { useHome } from "@/context/helpers/Home/HomeContext";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as 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 { Eye, EyeOff, Mail, Lock, User, Loader2, Phone } from "lucide-react";
import Link from "next/link";
import { Alert, AlertDescription } from "@/components/ui/alert";

export default function RegisterPage() {
  const { t } = useTranslation("auth");
  const router = useRouter();
  const { user, register, isLoading, errorMessage } = useAuth();
  const { companyData } = useHome();
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  const baseUrl =
    typeof window !== "undefined"
      ? window.location.origin
      : companyData?.domain
      ? `https://${companyData.domain}`
      : "";
  const registerUrl = `${baseUrl}${router.asPath}`;

  // Redirect if already logged in
  useEffect(() => {
    if (user) {
      router.push("/");
    }
  }, [user, router]);

  // Zod validation schema
  const formSchema = z
    .object({
      fullName: z
        .string()
        .min(2, { message: t("fullNameRequired", "Full name is required") })
        .max(100),
      email: z
        .string()
        .email({ message: t("emailInvalid", "Email is invalid") })
        .min(1, { message: t("emailRequired", "Email is required") }),
      phone: z
        .string()
        .min(10, {
          message: t("phoneMinLength", "Phone must be at least 10 digits"),
        })
        .max(15, {
          message: t("phoneMaxLength", "Phone must be at most 15 digits"),
        })
        .regex(/^[0-9+\-\s()]*$/, {
          message: t("phoneInvalid", "Phone number is invalid"),
        }),
      password: z
        .string()
        .min(6, {
          message: t(
            "passwordMinLength",
            "Password must be at least 6 characters"
          ),
        })
        .max(100),
      confirmPassword: z.string().min(1, {
        message: t("confirmPasswordRequired", "Please confirm your password"),
      }),
    })
    .refine((data) => data.password === data.confirmPassword, {
      message: t("passwordsNotMatch", "Passwords do not match"),
      path: ["confirmPassword"],
    });

  // Initialize form with react-hook-form
  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {
      fullName: "",
      email: "",
      phone: "",
      password: "",
      confirmPassword: "",
    },
  });

  // Handle form submission
  const onSubmit = async (data) => {
    // Split full name into first and last name
    const nameParts = data.fullName.trim().split(" ");
    const firstName = nameParts[0] || "";
    const lastName = nameParts.slice(1).join(" ") || nameParts[0];

    await register({
      firstName,
      lastName,
      email: data.email,
      phone: data.phone,
      password: data.password,
    });
  };

  return (
    <>
      <SEO
        title={t("seo.registerTitle", "Register")}
        description={t("seo.registerDescription", "Create a new account to start shopping")}
        keywords={t("seo.registerKeywords", "register, sign up, create account")}
        url={registerUrl}
        type="website"
        noindex={true}
      />

      <main className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100">
      <div className="container px-4 py-8 mx-auto">
        <div className="flex min-h-[calc(100vh-4rem)] items-center justify-center">
          <div className="w-full max-w-md">
            {/* Card */}
            <div className="overflow-hidden bg-white shadow-xl rounded-2xl">
              {/* Header */}
              <div className="p-8 text-white bg-gradient-to-r from-mainColor to-mainColor/90">
                <div className="flex justify-center mb-4">
                  <div className="flex items-center justify-center w-16 h-16 bg-white rounded-full">
                    <User className="w-8 h-8 text-mainColor" />
                  </div>
                </div>
                <h1 className="mb-2 text-2xl font-bold text-center">
                  {t("createAccount", "Create Account")}
                </h1>
                <p className="text-sm text-center text-white/90">
                  {t("registerSubtitle", "Join us today and start shopping")}
                </p>
              </div>

              {/* Form */}
              <div className="p-8">
                {/* Error Message from API */}
                {errorMessage && (
                  <Alert variant="destructive" className="mb-6">
                    <AlertDescription>{errorMessage}</AlertDescription>
                  </Alert>
                )}

                <Form {...form}>
                  <form
                    onSubmit={form.handleSubmit(onSubmit)}
                    className="space-y-5"
                  >
                    {/* Full Name Field */}
                    <FormField
                      control={form.control}
                      name="fullName"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>
                            {t("fullName", "Full Name")}
                          </FormLabel>
                          <FormControl>
                            <div className="relative">
                              <User className="absolute w-5 h-5 text-gray-400 -translate-y-1/2 left-3 top-1/2" />
                              <Input
                                {...field}
                                type="text"
                                placeholder="John Doe"
                                className="pl-10"
                                autoComplete="name"
                              />
                            </div>
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    {/* Email Field */}
                    <FormField
                      control={form.control}
                      name="email"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>
                            {t("email", "Email Address")}
                          </FormLabel>
                          <FormControl>
                            <div className="relative">
                              <Mail className="absolute w-5 h-5 text-gray-400 -translate-y-1/2 left-3 top-1/2" />
                              <Input
                                {...field}
                                type="email"
                                placeholder="you@example.com"
                                className="pl-10"
                                autoComplete="email"
                              />
                            </div>
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    {/* Phone Field */}
                    <FormField
                      control={form.control}
                      name="phone"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>
                            {t("phone", "Phone Number")}
                          </FormLabel>
                          <FormControl>
                            <div className="relative">
                              <Phone className="absolute w-5 h-5 text-gray-400 -translate-y-1/2 left-3 top-1/2" />
                              <Input
                                {...field}
                                type="tel"
                                placeholder="+1 (555) 000-0000"
                                className="pl-10"
                                autoComplete="tel"
                              />
                            </div>
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    {/* Password Field */}
                    <FormField
                      control={form.control}
                      name="password"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>
                            {t("password", "Password")}
                          </FormLabel>
                          <FormControl>
                            <div className="relative">
                              <Lock className="absolute w-5 h-5 text-gray-400 -translate-y-1/2 left-3 top-1/2" />
                              <Input
                                {...field}
                                type={showPassword ? "text" : "password"}
                                placeholder="••••••••"
                                className="pl-10 pr-12"
                                autoComplete="new-password"
                              />
                              <button
                                type="button"
                                onClick={() => setShowPassword(!showPassword)}
                                className="absolute -translate-y-1/2 right-3 top-1/2"
                                tabIndex={-1}
                              >
                                {showPassword ? (
                                  <EyeOff className="w-5 h-5 text-gray-400 transition-colors hover:text-gray-600" />
                                ) : (
                                  <Eye className="w-5 h-5 text-gray-400 transition-colors hover:text-gray-600" />
                                )}
                              </button>
                            </div>
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    {/* Confirm Password Field */}
                    <FormField
                      control={form.control}
                      name="confirmPassword"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>
                            {t("confirmPassword", "Confirm Password")}
                          </FormLabel>
                          <FormControl>
                            <div className="relative">
                              <Lock className="absolute w-5 h-5 text-gray-400 -translate-y-1/2 left-3 top-1/2" />
                              <Input
                                {...field}
                                type={showConfirmPassword ? "text" : "password"}
                                placeholder="••••••••"
                                className="pl-10 pr-12"
                                autoComplete="new-password"
                              />
                              <button
                                type="button"
                                onClick={() =>
                                  setShowConfirmPassword(!showConfirmPassword)
                                }
                                className="absolute -translate-y-1/2 right-3 top-1/2"
                                tabIndex={-1}
                              >
                                {showConfirmPassword ? (
                                  <EyeOff className="w-5 h-5 text-gray-400 transition-colors hover:text-gray-600" />
                                ) : (
                                  <Eye className="w-5 h-5 text-gray-400 transition-colors hover:text-gray-600" />
                                )}
                              </button>
                            </div>
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    {/* Submit Button */}
                    <Button
                      type="submit"
                      disabled={isLoading}
                      className="w-full py-6 font-semibold text-white transition-all duration-200 rounded-lg bg-mainColor hover:bg-mainColor/90"
                    >
                      {isLoading ? (
                        <>
                          <Loader2 className="w-5 h-5 mr-2 animate-spin" />
                          {t("creatingAccount", "Creating account...")}
                        </>
                      ) : (
                        t("createAccountButton", "Create Account")
                      )}
                    </Button>
                  </form>
                </Form>

                {/* Sign In Link */}
                <p className="mt-6 text-sm text-center text-gray-600">
                  {t("alreadyHaveAccount", "Already have an account?")}{" "}
                  <Link
                    href="/account/login"
                    className="font-medium transition-colors cursor-pointer text-mainColor hover:text-mainColor/80"
                  >
                    {t("signIn", "Sign in")}
                  </Link>
                </p>
              </div>
            </div>

            {/* Footer */}
            <p className="mt-8 text-sm text-center text-gray-500">
              {t(
                "termsText",
                "By creating an account, you agree to our Terms of Service and Privacy Policy"
              )}
            </p>
          </div>
        </div>
      </div>
    </main>
    </>
  );
}
