"use client"

import { signIn, useSession } from "next-auth/react"
import { useRouter } from "next/navigation"
import { useState, useEffect } from "react"
import { motion, AnimatePresence } from "framer-motion"

export default function Home() {
  const { data: session, status } = useSession()
  const router = useRouter()
  
  const [isLogin, setIsLogin] = useState(true)
  const [username, setUsername] = useState("")
  const [password, setPassword] = useState("")
  const [confirmPassword, setConfirmPassword] = useState("")
  const [error, setError] = useState("")
  const [isLoading, setIsLoading] = useState(false)

  useEffect(() => {
    if (status === "authenticated") {
      router.push("/parent")
    }
  }, [status, router])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError("")
    setIsLoading(true)

    if (isLogin) {
      // Login Flow
      const res = await signIn("credentials", {
        redirect: false,
        username,
        password,
      })

      if (res?.error) {
        setError("Invalid username or password")
        setIsLoading(false)
      } else {
        router.push("/parent")
      }
    } else {
      // Registration Flow
      if (password !== confirmPassword) {
        setError("Passwords do not match")
        setIsLoading(false)
        return
      }

      try {
        const res = await fetch("/api/auth/register", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ username, password })
        })

        if (!res.ok) {
          const data = await res.json()
          setError(data.message || "Failed to register")
          setIsLoading(false)
          return
        }

        // Auto login after successful registration
        const signInRes = await signIn("credentials", {
          redirect: false,
          username,
          password,
        })

        if (signInRes?.error) {
          setError("Account created but failed to log in automatically")
          setIsLoading(false)
        } else {
          router.push("/parent")
        }
      } catch (err) {
        setError("An unexpected error occurred")
        setIsLoading(false)
      }
    }
  }

  if (status === "loading" || status === "authenticated") {
    return <div className="loader">Loading...</div>
  }

  return (
    <div className="auth-container">
      <div className="auth-wrapper">
        <motion.div 
          className="auth-card"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, ease: "easeOut" }}
        >
          <div className="auth-header">
            <div className="auth-logo">
              <span style={{ color: "var(--primary)" }}>Daily</span> App
            </div>
            <p className="auth-subtitle">Parent Dashboard</p>
          </div>

          <div className="segmented-control" style={{ marginBottom: "2rem" }}>
            <button 
              type="button"
              className={`segmented-control-btn ${isLogin ? "active" : ""}`}
              onClick={() => { setIsLogin(true); setError(""); }}
            >
              Sign In
            </button>
            <button 
              type="button"
              className={`segmented-control-btn ${!isLogin ? "active" : ""}`}
              onClick={() => { setIsLogin(false); setError(""); }}
            >
              Register
            </button>
          </div>

          <AnimatePresence mode="wait">
            <motion.form 
              key={isLogin ? "login" : "register"}
              initial={{ opacity: 0, x: isLogin ? -20 : 20 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: isLogin ? 20 : -20 }}
              transition={{ duration: 0.2 }}
              onSubmit={handleSubmit} 
              className="form-group"
            >
              <div style={{ display: "flex", flexDirection: "column", gap: "1rem" }}>
                <div className="input-wrapper">
                  <input 
                    type="text" 
                    placeholder="Username" 
                    className="input"
                    value={username}
                    onChange={e => setUsername(e.target.value)}
                    required
                  />
                </div>

              <div className="input-wrapper">
                <input 
                  type="password" 
                  placeholder="Password" 
                  className="input"
                  value={password}
                  onChange={e => setPassword(e.target.value)}
                  required
                />
              </div>

              {!isLogin && (
                <motion.div 
                  className="input-wrapper"
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: "auto" }}
                  transition={{ duration: 0.2 }}
                >
                  <input 
                    type="password" 
                    placeholder="Confirm Password" 
                    className="input"
                    value={confirmPassword}
                    onChange={e => setConfirmPassword(e.target.value)}
                    required
                  />
                </motion.div>
              )}

              </div>

              {error && (
                <motion.p 
                  className="error-text"
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                >
                  {error}
                </motion.p>
              )}

              <div className="auth-form-bottom">
                <button type="submit" className="btn auth-submit-btn" disabled={isLoading} style={{ minHeight: "56px", fontSize: "1.1rem", borderRadius: "100px" }}>
                  {isLoading ? (
                    <span className="spinner"></span>
                  ) : (
                    isLogin ? "Sign In" : "Create Account"
                  )}
                </button>
              </div>
            </motion.form>
          </AnimatePresence>
        </motion.div>
      </div>
    </div>
  )
}
