"use client";
import { useState, useEffect } from "react";
import { useAuth } from "@/hooks/use-auth";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { Loader2 } from "lucide-react";
import { usePathname, useRouter } from "next/navigation";
import { Eye, EyeOff } from "lucide-react";
import Head from "next/head";

// Login form schema
const loginSchema = z.object({
  username: z.string().min(1, "Username is required"),
  password: z.string().min(1, "Password is required"),
});

// Registration form schema
const registerSchema = z.object({
  username: z.string().min(3, "Username must be at least 3 characters"),
  password: z.string().min(6, "Password must be at least 6 characters"),
  email: z.string().email("Invalid email address"),
  fullName: z.string().min(2, "Full name must be at least 2 characters"),
});

type LoginFormValues = z.infer<typeof loginSchema>;
type RegisterFormValues = z.infer<typeof registerSchema>;

const AuthPage = () => {
  const [activeTab, setActiveTab] = useState<"login" | "register">("login");
  const location = usePathname();
  const navigate = useRouter();
  const { user, loginMutation, registerMutation } = useAuth();

  const [showLoginPassword, setShowLoginPassword] = useState(false);
  const [showRegisterPassword, setShowRegisterPassword] = useState(false);

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

  // Setup for login form
  const loginForm = useForm<LoginFormValues>({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      username: "",
      password: "",
    },
  });

  // Setup for registration form
  const registerForm = useForm<RegisterFormValues>({
    resolver: zodResolver(registerSchema),
    defaultValues: {
      username: "",
      password: "",
      email: "",
      fullName: "",
    },
  });

  // Handle login form submission
  const onLoginSubmit = (data: LoginFormValues) => {
    loginMutation.mutate(data);
  };

  // Handle registration form submission
  const onRegisterSubmit = (data: RegisterFormValues) => {
    registerMutation.mutate({
      ...data,
      // userType: "visitor",
    });
  };

  return (
    <>
      <Head>
        <title>
          {activeTab === "login" ? "Sign In" : "Register"} | Badagry Museum
        </title>
        <meta
          name="description"
          content="Sign in or register for an account to access exclusive features at Badagry Museum's website, including community forums and booking tracking."
        />
        <meta name="robots" content="noindex" />
      </Head>

      <section className="py-16 bg-secondary min-h-screen flex items-center">
        <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 w-full">
          <div className="bg-white rounded-xl shadow-2xl overflow-hidden">
            <div className="md:flex">
              {/* Left side - Auth forms */}
              <div className="md:w-1/2 p-8">
                <h1 className="text-3xl font-bold text-primary mb-6 font-heading">
                  {activeTab === "login"
                    ? "Welcome Back"
                    : "Join Our Community"}
                </h1>

                <Tabs
                  defaultValue="login"
                  value={activeTab}
                  onValueChange={(v) => setActiveTab(v as "login" | "register")}
                >
                  <TabsList className="grid w-full grid-cols-2 mb-8">
                    <TabsTrigger value="login">Sign In</TabsTrigger>
                    <TabsTrigger value="register">Register</TabsTrigger>
                  </TabsList>

                  <TabsContent value="login">
                    <Form {...loginForm}>
                      <form
                        onSubmit={loginForm.handleSubmit(onLoginSubmit)}
                        className="space-y-4"
                      >
                        <FormField
                          control={loginForm.control}
                          name="username"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>Username or Email</FormLabel>
                              <FormControl>
                                <Input
                                  placeholder="Enter your username or email"
                                  {...field}
                                />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />

                        <FormField
                          control={loginForm.control}
                          name="password"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>Password</FormLabel>
                              <FormControl>
                                <div className="relative">
                                  <Input
                                    type={
                                      showLoginPassword ? "text" : "password"
                                    }
                                    placeholder="••••••••"
                                    {...field}
                                  />
                                  <button
                                    type="button"
                                    onClick={() =>
                                      setShowLoginPassword((prev) => !prev)
                                    }
                                    className="absolute right-2 top-1/2 transform -translate-y-1/2 text-muted-foreground"
                                  >
                                    {showLoginPassword ? (
                                      <EyeOff size={18} />
                                    ) : (
                                      <Eye size={18} />
                                    )}
                                  </button>
                                </div>
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />

                        <Button
                          type="submit"
                          className="w-full bg-primary hover:bg-primary-dark mt-2"
                          disabled={loginMutation.isPending}
                        >
                          {loginMutation.isPending ? (
                            <>
                              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                              Signing in...
                            </>
                          ) : (
                            "Sign In"
                          )}
                        </Button>
                      </form>
                    </Form>

                    <div className="mt-6 text-center">
                      <p className="text-sm text-gray-600">
                        Don't have an account?{" "}
                        <button
                          onClick={() => setActiveTab("register")}
                          className="text-primary hover:text-primary-dark font-medium"
                        >
                          Register
                        </button>
                      </p>
                    </div>
                  </TabsContent>

                  <TabsContent value="register">
                    <Form {...registerForm}>
                      <form
                        onSubmit={registerForm.handleSubmit(onRegisterSubmit)}
                        className="space-y-4"
                      >
                        <FormField
                          control={registerForm.control}
                          name="fullName"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>Full Name</FormLabel>
                              <FormControl>
                                <Input
                                  placeholder="Enter your full name"
                                  {...field}
                                />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />

                        <FormField
                          control={registerForm.control}
                          name="email"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>Email</FormLabel>
                              <FormControl>
                                <Input
                                  placeholder="your.email@example.com"
                                  type="email"
                                  {...field}
                                />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />

                        <FormField
                          control={registerForm.control}
                          name="username"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>Username</FormLabel>
                              <FormControl>
                                <Input
                                  placeholder="Choose a username"
                                  {...field}
                                />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />

                        <FormField
                          control={registerForm.control}
                          name="password"
                          render={({ field }) => (
                            <FormItem>
                              <FormLabel>Password</FormLabel>
                              <FormControl>
                                <div className="relative">
                                  <Input
                                    type={
                                      showRegisterPassword ? "text" : "password"
                                    }
                                    placeholder="Create a password"
                                    {...field}
                                  />
                                  <button
                                    type="button"
                                    onClick={() =>
                                      setShowRegisterPassword((prev) => !prev)
                                    }
                                    className="absolute right-2 top-1/2 transform -translate-y-1/2 text-muted-foreground"
                                  >
                                    {showRegisterPassword ? (
                                      <EyeOff size={18} />
                                    ) : (
                                      <Eye size={18} />
                                    )}
                                  </button>
                                </div>
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />

                        <Button
                          type="submit"
                          className="w-full bg-primary hover:bg-primary-dark mt-2"
                          disabled={registerMutation.isPending}
                        >
                          {registerMutation.isPending ? (
                            <>
                              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                              Creating account...
                            </>
                          ) : (
                            "Create Account"
                          )}
                        </Button>
                      </form>
                    </Form>

                    <div className="mt-6 text-center">
                      <p className="text-sm text-gray-600">
                        Already have an account?{" "}
                        <button
                          onClick={() => setActiveTab("login")}
                          className="text-primary hover:text-primary-dark font-medium"
                        >
                          Sign In
                        </button>
                      </p>
                    </div>
                  </TabsContent>
                </Tabs>
              </div>

              {/* Right side - Hero image and text */}
              <div className="hidden md:block md:w-1/2 bg-primary p-12 text-white">
                <div className="h-full flex flex-col justify-center">
                  <h2 className="text-3xl font-bold mb-6 font-heading">
                    Discover Nigeria's Rich Heritage
                  </h2>
                  <p className="mb-6">
                    Join the Badagry Museum community to explore the profound
                    history of the West African Slave Trade and Nigeria's
                    cultural heritage.
                  </p>

                  <ul className="space-y-4">
                    <li className="flex items-center">
                      <i className="fas fa-check-circle mr-2 text-accent"></i>
                      <span>Access exclusive historical content</span>
                    </li>
                    <li className="flex items-center">
                      <i className="fas fa-check-circle mr-2 text-accent"></i>
                      <span>Participate in community discussions</span>
                    </li>
                    <li className="flex items-center">
                      <i className="fas fa-check-circle mr-2 text-accent"></i>
                      <span>Track your museum visit bookings</span>
                    </li>
                    <li className="flex items-center">
                      <i className="fas fa-check-circle mr-2 text-accent"></i>
                      <span>Receive updates on new exhibits and events</span>
                    </li>
                  </ul>

                  <div className="mt-8 p-4 bg-white/10 rounded-lg">
                    <p className="text-sm italic">
                      "Understanding our history is the key to building a better
                      future. Join us on this journey of discovery and
                      remembrance."
                    </p>
                    <div className="mt-2 text-right">
                      <span className="text-accent">
                        — Badagry Museum Director
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </>
  );
};

export default AuthPage;
