"use client";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { signupSchema } from "@/lib/zodSchemas";
import { toast, Flip } from "react-toastify";
import Image from "next/image";
import { signIn, useSession } from "next-auth/react";

const SignupForm = ({
  onEmailSignup,
}: {
  onEmailSignup: (
    email: string,
    password: string,
    fullName: string
  ) => Promise<void>;
}) => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(signupSchema),
  });
  // const [gender, setGender] = useState("");
  // const [date, setDate] = useState<Date>();
  const onSubmit = async (data: any) => {
    const password = data.password;
    const confirmPassword = data.confirmPassword;
    const full_Name = `${data.firstName} ${data.lastName}`;

    try {
      if (password !== confirmPassword) {
        toast.error("Passwords do not match", {
          position: "bottom-right",
          autoClose: 4000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
          theme: "colored",
          transition: Flip,
        });
      } else {
        onEmailSignup(data.email, data.password, full_Name);
      }
    } catch (error: any) {
      toast.error(error.message, {
        position: "bottom-right",
        autoClose: 4000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
        theme: "colored",
        transition: Flip,
      });
    }
  };

   const handleSignIn = async () => {
      try {
        const response = await signIn("google", {
          redirect: false,
          callbackUrl: "/",
        });
      } catch (error: any) {
        // await logToServer("error", error.message);
        toast.error(error.message, {
          position: "bottom-right",
          autoClose: 4000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
          theme: "colored",
          transition: Flip,
        });
      }
    };

  return (
    <div className="flex flex-col">
      <Card className="bg-white">
        <CardHeader className="text-center">
          <CardTitle className="text-xl">Welcome to barrack</CardTitle>
          <CardDescription>
            Sign up with your Email or Google account
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit(onSubmit)}>
            <div className="grid gap-6">
              <div className="grid gap-6">
                <div className="flex gap-2">
                  <div>
                    <Label htmlFor="email">First Name</Label>
                    <Input
                      id="email"
                      type="text"
                      placeholder="John"
                      required
                      {...register("firstName", {
                        required: "First name is required",
                      })}
                    />
                  </div>
                  <div>
                    <Label htmlFor="email">Last Name</Label>
                    <Input
                      id="email"
                      type="text"
                      placeholder="Doe"
                      required
                      {...register("lastName", {
                        required: "Last name is required",
                      })}
                    />
                  </div>
                </div>
                <div className="grid gap-2">
                  <Label htmlFor="email">Email</Label>
                  <Input
                    id="email"
                    type="email"
                    placeholder="example@mail.com"
                    required
                    {...register("email", {
                      required: "Email is required",
                      pattern: {
                        value: /\S+@\S+\.\S+/,
                        message: "Invalid email address",
                      },
                    })}
                  />
                  {errors.email && typeof errors.email.message === "string" && (
                    <div className="text-red-500">{errors.email.message}</div>
                  )}
                </div>
                <div className="grid gap-2">
                  <div className="flex items-center">
                    <Label htmlFor="password">Password</Label>
                  </div>
                  <Input
                    id="password"
                    type="password"
                    required
                    {...register("password", {
                      required: "Password is required",
                      minLength: {
                        value: 8,
                        message: "Password must be at least 8 characters long",
                      },
                    })}
                  />
                  {errors.password &&
                    typeof errors.password.message === "string" && (
                      <div className="text-red-500">
                        {errors.password.message}
                      </div>
                    )}
                </div>
                <div className="grid gap-2">
                  <div className="flex items-center">
                    <Label htmlFor="password">Confirm Password</Label>
                  </div>
                  <Input
                    id="password"
                    type="password"
                    required
                    {...register("confirmPassword", {
                      required: "Please confirm your password",
                    })}
                  />
                  {errors.confirmPassword &&
                    typeof errors.confirmPassword.message === "string" && (
                      <div className="text-red-500">
                        {errors.confirmPassword.message}
                      </div>
                    )}
                </div>
                <Button
                  type="submit"
                  className="w-full text-white bg-primary hover:bg-secondary"
                >
                  Sign up
                </Button>
              </div>
              <div className="relative text-center text-sm after:absolute after:inset-0 after:top-1/2 after:z-0 after:flex after:items-center after:border-t after:border-border">
                <span className="relative z-10 bg-white px-2 text-muted-foreground">
                  Or continue with
                </span>
              </div>
              <div className="flex flex-col gap-4">
                <Button
                  type="button"
                  variant="outline"
                  className="w-full"
                  onClick={handleSignIn}
                >
                  <Image
                    src="/logo/google.svg"
                    alt="Google logo"
                    width={24}
                    height={24}
                    className="mr-2"
                  />
                  Sign up with Google
                </Button>
              </div>
              <div className="text-center text-sm">
                Already have an account?{" "}
                <a href="/login" className="underline underline-offset-4">
                  Login
                </a>
              </div>
            </div>
          </form>
        </CardContent>
      </Card>
      <div className="text-balance text-center text-xs text-muted-foreground [&_a]:underline [&_a]:underline-offset-4 [&_a]:hover:text-primary  ">
        By continuing, you agree to our <a href="/privacy">Terms of Service</a> and{" "}
        <a href="/privacy">Privacy Policy</a>.
      </div>
    </div>
  );
};

export default SignupForm;
