"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { signIn } from "next-auth/react"
import { userCounties } from "@/lib/userCounties"
import styles from "./Auth.module.css"

export function RegisterForm() {
  const router = useRouter()
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    password: "",
    confirmPassword: "",
    class: "9",
    county: ""
  })
  const [error, setError] = useState("")
  const [isLoading, setIsLoading] = useState(false)

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    setFormData({
      ...formData,
      [e.target.id]: e.target.value
    })
  }

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

    if (formData.password !== formData.confirmPassword) {
      setError("Parolele nu se potrivesc.")
      setIsLoading(false)
      return
    }

    try {
      const response = await fetch("/rovibe/api/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: formData.name,
          email: formData.email,
          password: formData.password,
          class: formData.class,
          county: formData.county
        })
      })

      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.message || "A apărut o eroare la înregistrare.")
      }

      // Automatically sign in after successful registration
      const signInRes = await signIn("credentials", {
        redirect: false,
        email: formData.email,
        password: formData.password,
      })

      if (signInRes?.error) {
        setError("Cont creat, dar autentificarea a eșuat. Vă rugăm să vă autentificați manual.")
      } else {
        router.push("/dashboard")
        router.refresh()
      }
    } catch (err: any) {
      setError(err.message || "A apărut o eroare la înregistrare.")
    } finally {
      setIsLoading(false)
    }
  }

  const handleOAuthSignIn = (provider: "google") => {
    signIn(provider, { callbackUrl: "/rovibe/dashboard" })
  }

  return (
    <div className={styles.authCard}>
      <div className={styles.header}>
        <img 
          src="/rovibe/SiglaRoVIBE1.png" 
          alt="Ro-VIBE Logo" 
          style={{ height: "64px", width: "auto", margin: "0 auto 1.5rem", display: "block" }} 
        />
        <h1 className={styles.title}>Creează cont</h1>
        <p className={styles.subtitle}>Alătură-te proiectului Ro-VIBE</p>
      </div>

      {error && <div className={styles.errorMsg}>{error}</div>}

      <form onSubmit={handleSubmit}>
        <div className={styles.formGroup}>
          <label htmlFor="name" className={styles.label}>Nume și Prenume</label>
          <input
            id="name"
            type="text"
            value={formData.name}
            onChange={handleChange}
            className={styles.input}
            required
            placeholder="Popescu Ion"
          />
        </div>

        <div className={styles.formGroup}>
          <label htmlFor="email" className={styles.label}>Email</label>
          <input
            id="email"
            type="email"
            value={formData.email}
            onChange={handleChange}
            className={styles.input}
            required
            placeholder="ion.popescu@liceu.ro"
          />
        </div>

        <div className={styles.formGroup}>
          <label htmlFor="class" className={styles.label}>Clasa</label>
          <select 
            id="class" 
            value={formData.class} 
            onChange={handleChange}
            className={styles.input}
            required
          >
            <option value="9">Clasa a IX-a</option>
            <option value="10">Clasa a X-a</option>
            <option value="11">Clasa a XI-a</option>
            <option value="12">Clasa a XII-a</option>
          </select>
        </div>

        <div className={styles.formGroup}>
          <label htmlFor="county" className={styles.label}>Județ</label>
          <select 
            id="county" 
            value={formData.county} 
            onChange={handleChange}
            className={styles.input}
            required
          >
            <option value="">— Selectează Județul —</option>
            {userCounties.map(county => (
              <option key={county} value={county}>{county}</option>
            ))}
          </select>
        </div>

        <div className={styles.formGroup}>
          <label htmlFor="password" className={styles.label}>Parolă</label>
          <input
            id="password"
            type="password"
            value={formData.password}
            onChange={handleChange}
            className={styles.input}
            required
            minLength={6}
            placeholder="••••••••"
          />
        </div>

        <div className={styles.formGroup}>
          <label htmlFor="confirmPassword" className={styles.label}>Confirmare Parolă</label>
          <input
            id="confirmPassword"
            type="password"
            value={formData.confirmPassword}
            onChange={handleChange}
            className={styles.input}
            required
            minLength={6}
            placeholder="••••••••"
          />
        </div>

        <button 
          type="submit" 
          className={styles.submitBtn}
          disabled={isLoading}
        >
          {isLoading ? "Se încarcă..." : "Înregistrare"}
        </button>
      </form>

      <div className={styles.divider}>sau continuă cu</div>

      <button 
        type="button" 
        onClick={() => handleOAuthSignIn("google")}
        className={styles.socialBtn}
      >
        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 9h16"/><path d="M4 15h16"/><rect width="20" height="12" x="2" y="6" rx="2"/></svg>
        Cont Google
      </button>


      <div className={styles.footer}>
        Ai deja cont? <Link href="/login" className={styles.link}>Autentifică-te</Link>
      </div>
    </div>
  )
}
