"use client"

import type React              from "react"

import { useState }       from "react";
import Link               from "next/link";
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 [confirmPassword, setConfirmPassword] = useState("")
  const [acceptTerms, setAcceptTerms] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [emailError, setEmailError] = useState("")
  const [confirmPasswordError, setConfirmPasswordError] = useState("")
  const [showPassword, setShowPassword] = useState(false)
  const [passwordFocus, setPasswordFocus] = useState(false)

  const validateEmail = (email: string):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 validateConfirmPassword = (confirmPwd: string) => {
    if (!confirmPwd) {
      return "Please confirm your password"
    }
    if (confirmPwd !== password) {
      return "Passwords don't match"
    }
    return ""
  }

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

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

    const emailErr = validateEmail(email)
    const confirmPwdErr = validateConfirmPassword(confirmPassword)

    if (emailErr || confirmPwdErr) {
      setEmailError(emailErr)
      setConfirmPasswordError(confirmPwdErr)
      return
    }

    setIsLoading(true)

    try {
      const { data, error } = await authClient.signUp.email({
        email,
        password,
        name: email,
        image: undefined,
        callbackURL: "/verify-email"
      }, {
        onRequest: (ctx) => {
        },
        onSuccess: (ctx) => {
          toast.success("Account successfully created!");
          router.push('/verify-email');
          router.refresh();
        },
        onError: (ctx) => {
          throw new Error(ctx.error.message || "Failed to create account")
        },
      });
    } catch (error: any) {
      setIsLoading(false);
      toast.error(error.message || "Something went wrong. Please try again later.");
    }
  }

  const handleSocialSignIn = async (provider: string) => {
  }

  return (
    <AuthCard
      title="Create an account"
      description="Sign up with"
      footer={
        <>
          Already have an account?{" "}
          <Link href="/login" className="text-primary hover:underline font-medium">
            Login
          </Link>
        </>
      }
    >
      <SsoButtonGroup title="Sign up 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
            id="email"
            type="email"
            placeholder="mail@example.com"
            value={email}
            onChange={(e) => {
              setEmail(e.target.value)
            }}
            onBlur={() => {
              // setEmailError(validateEmail(email))
            }}
            className={emailError ? "border-red-500" : ""}
            required
          />
          {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) || (confirmPassword.length > 0) ? 'opacity-100' : 'opacity-0'}`
              }
              onClick={() => setShowPassword(!showPassword)}
            >
              {showPassword ? "Hide" : "Show"}
            </Button>
          </Label>
          <PasswordInput
            id="password"
            placeholder="Choose a password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            onFocus={() => setPasswordFocus(true)}
            onBlur={() => setPasswordFocus(false)}
            open={showPassword}
            required
            showInvalid={true}
            showRequirements
          />
        </div>

        <div className="space-y-2">
          <Label htmlFor="confirmPassword">Confirm Password</Label>
          <PasswordInput
            id="confirmPassword"
            placeholder="Retype your password"
            value={confirmPassword}
            onChange={(e) => setConfirmPassword(e.target.value)}
            open={showPassword}
            setOpen={setShowPassword}
            onFocus={() => setPasswordFocus(true)}
            onBlur={() => setPasswordFocus(false)}
            showInvalid={true}
            required
          />
          {/* {confirmPasswordTouched && confirmPasswordError && (
            <p className="text-sm text-red-500">{confirmPasswordError}</p>
          )} */}
        </div>

        <div className="flex items-start space-x-2">
          <Checkbox
            id="terms"
            checked={acceptTerms}
            onCheckedChange={(checked) => setAcceptTerms(checked as boolean)}
          />
          <label
            htmlFor="terms"
            className="text-sm text-muted-foreground leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
          >
            I agree to the{" "}
            <Link href="https://kokotrack.com/terms" className="text-primary hover:underline">
              terms and conditions
            </Link>{" "}
            and{" "}
            <Link href="https://kokotrack.com/privacy" className="text-primary hover:underline">
              privacy policy
            </Link>
            .
          </label>
        </div>
        
        <div className="flex items-start space-x-2">
          <Checkbox
            id="subscribe"
          />
          <label
            htmlFor="subscribe"
            className="text-sm text-muted-foreground leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
          >
            I want to receive emails from{" "}
            <Link href="https://kokotrack.com" className="text-primary hover:underline">
              Kokotrack
            </Link>{" "}
            on product updates and market news.
          </label>
        </div>
        
        <Button type="submit" className="w-full cursor-pointer" disabled={isLoading || !isFormValid()}>
          {isLoading ? "Creating account..." : "Create account"}
        </Button>
      </form>
    </AuthCard>
  )
}
