"use client";

import type React from "react";

import Link               from "next/link";
import { useState }       from "react";
import { useRouter }      from "next/navigation";
import { Button }         from "@/components/ui/button";
import { Input }          from "@/components/ui/input";
import { Label }          from "@/components/ui/label";
import { Checkbox }       from "@/components/ui/checkbox";
import { toast }          from "sonner";
import { AuthCard }       from "@/components/auth-card";
import { SsoButtonGroup } from "@/components/sso-button-group";
import { PasswordInput }  from "@/components/password-input";
import { authClient }     from "@/lib/auth-client";

export default function Page() {
  const router    = useRouter();

  const [email,         setEmail]         = useState("");
  const [password,      setPassword]      = useState("");
  const [showPassword,  setShowPassword]  = useState(false);
  const [passwordFocus, setPasswordFocus] = useState(false);
  const [rememberMe,    setRememberMe]    = useState(false);
  const [isLoading,     setIsLoading]     = useState(false);
  const [emailError,    setEmailError]    = useState("");
  const [emailTouched,  setEmailTouched]  = useState(false);

  const validateEmail: (email: string) => string = (email: string) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!email) {
      return "Email is required";
    }
    if (!emailRegex.test(email)) {
      return "Please enter a valid email address";
    }
    return "";
  }

  const isFormValid = () => {
    return email && !validateEmail(email) && password
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    const emailErr = validateEmail(email)
    if (emailErr) {
      setEmailError(emailErr)
      setEmailTouched(true)
      return
    }

    setIsLoading(true)

    try {
      const { data, error } = await authClient.signIn.email({
        email,
        password,
        rememberMe,
        callbackURL: undefined // "/dashboard"
      });

      if (!!error) {
        switch (error.status) {
          case 403:
            throw new Error("Verify your email to login");
          default:
            throw new Error(error.message || 'An error occurred. Please try again.');
        }
      }

      toast.success("Login successful. Welcome back!");

      router.push(
        data.user.emailVerified ? '/dashboard' : '/verify-email'
      );
      router.refresh();
    } catch (error: any) {
      setIsLoading(false);
      toast.error(error.message || "Something went wrong. Please try again later.");
    }
  }

  const handleSocialSignIn = async (provider: string) => {
    toast.error("Sign in with " + provider + " failed");
  }

  return (
    <AuthCard
      title="Welcome back"
      description="Sign in to your account with"
      footer={
        <>
          Don&apos;t have an account?{" "}
          <Link href="/signup" className="text-primary hover:underline font-medium" tabIndex={2}>
            Sign up
          </Link>
        </>
      }
    >
      <SsoButtonGroup title="Sign in with %name%" onClick={(btn) => handleSocialSignIn(btn.name.toLowerCase())} />

      <div className="relative my-4">
        <div className="absolute inset-0 flex items-center">
          <span className="w-full border-t" />
        </div>
        <div className="relative flex justify-center text-xs uppercase">
          <span className="bg-card px-2 text-muted-foreground">Or</span>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-4">
        <div className="space-y-2">
          <Label htmlFor="email">Email</Label>
          <Input
            className={`select-all ${emailTouched && emailError ? "border-red-500" : ""}`}
            id="email"
            type="email"
            placeholder="mail@example.com"
            value={email}
            onChange={(e) => {
              setEmail(e.target.value)
              // if (emailTouched) {
              //   setEmailError(validateEmail(e.target.value))
              // }
            }}
            // onBlur={() => {
            //   setEmailTouched(true)
            //   setEmailError(validateEmail(email))
            // }}
            tabIndex={1}
            required
          />
          {emailTouched && emailError && <p className="text-sm text-red-500">{emailError}</p>}
        </div>

        <div className="space-y-2">
          <Label className="flex justify-between" htmlFor="password">
            <span>Password</span>
            <Button
              variant="link"
              size="sm"
              type="button"
              className={'text-xs h-auto p-0 text-primary ' +
                'hover:no-underline cursor-pointer ' +
                `${passwordFocus || (password.length > 0) ? 'opacity-100' : 'opacity-0'}`
              }
              onClick={() => setShowPassword(!showPassword)}
            >
              {showPassword ? "Hide" : "Show"}
            </Button>
          </Label>
          <PasswordInput
            id="password"
            placeholder="Your password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            onFocus={() => setPasswordFocus(true)}
            onBlur={() => setPasswordFocus(false)}
            open={showPassword}
            required
          />
        </div>

        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-2">
            <Checkbox
              id="remember"
              checked={rememberMe}
              onCheckedChange={(checked) => setRememberMe(checked as boolean)}
              tabIndex={1}
            />
            <label
              htmlFor="remember"
              className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
            >
              Remember me
            </label>
          </div>
          <Link href="/forgot-password" className="text-sm text-primary hover:underline" tabIndex={2}>
            Forgot password?
          </Link>
        </div>
        <Button type="submit" className="w-full cursor-pointer" disabled={isLoading || !isFormValid()} tabIndex={1}>
          {isLoading ? "Signing in..." : "Sign in"}
        </Button>
      </form>
    </AuthCard>
  )
}
