// app/reset-password/page.tsx
"use client"

import { useState, useEffect } from "react"
import { useSearchParams, useRouter } from "next/navigation"
import Link from "next/link"
import { Suspense } from "react"

export const dynamic = 'force-dynamic'

function ResetPasswordForm() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const token = searchParams.get("token")

  const [password, setPassword] = useState("")
  const [confirmPassword, setConfirmPassword] = useState("")
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState("")
  const [success, setSuccess] = useState(false)

  useEffect(() => {
    if (!token) {
      setError("Token não fornecido")
    }
  }, [token])

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

    if (!token) {
      setError("Token não fornecido")
      setLoading(false)
      return
    }

    if (password !== confirmPassword) {
      setError("As senhas não coincidem")
      setLoading(false)
      return
    }

    if (password.length < 6) {
      setError("A senha deve ter pelo menos 6 caracteres")
      setLoading(false)
      return
    }

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

      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.error || "Erro ao redefinir senha")
      }

      setSuccess(true)
      setTimeout(() => {
        router.push("/login")
      }, 2000)
    } catch (err: any) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }

  if (success) {
    return (
      <div style={{
        minHeight: "100vh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        backgroundImage: "url('/pdimaker-background.jpg')",
        backgroundSize: "cover",
        backgroundPosition: "center",
        position: "relative"
      }}>
        <div style={{
          position: "absolute",
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          background: "rgba(0, 0, 0, 0.5)"
        }} />

        <div style={{
          position: "relative",
          zIndex: 1,
          background: "rgba(255, 255, 255, 0.95)",
          padding: "3rem",
          borderRadius: "1rem",
          boxShadow: "0 20px 60px rgba(0,0,0,0.3)",
          maxWidth: "450px",
          width: "100%",
          textAlign: "center"
        }}>
          <div style={{ fontSize: "4rem", marginBottom: "1rem" }}>✅</div>
          <h1 style={{ fontSize: "1.5rem", fontWeight: "bold", marginBottom: "0.5rem", color: "#333" }}>
            Senha redefinida com sucesso!
          </h1>
          <p style={{ color: "#666", marginBottom: "2rem" }}>
            Redirecionando para o login...
          </p>
          <Link
            href="/login"
            style={{
              display: "inline-block",
              padding: "0.75rem 1.5rem",
              background: "#667eea",
              color: "white",
              borderRadius: "0.5rem",
              textDecoration: "none",
              fontWeight: "500"
            }}
          >
            Ir para Login
          </Link>
        </div>
      </div>
    )
  }

  return (
    <div style={{
      minHeight: "100vh",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      backgroundImage: "url('/pdimaker-background.jpg')",
      backgroundSize: "cover",
      backgroundPosition: "center",
      position: "relative"
    }}>
      <div style={{
        position: "absolute",
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        background: "rgba(0, 0, 0, 0.5)"
      }} />

      <div style={{
        position: "relative",
        zIndex: 1,
        background: "rgba(255, 255, 255, 0.95)",
        padding: "3rem",
        borderRadius: "1rem",
        boxShadow: "0 20px 60px rgba(0,0,0,0.3)",
        maxWidth: "450px",
        width: "100%"
      }}>
        <h1 style={{ fontSize: "2rem", marginBottom: "0.5rem", color: "#333", textAlign: "center" }}>
          🔐 Redefinir Senha
        </h1>
        <p style={{ color: "#666", marginBottom: "2rem", textAlign: "center" }}>
          Digite sua nova senha
        </p>

        <form onSubmit={handleSubmit}>
          <div style={{ marginBottom: "1.5rem" }}>
            <label style={{ display: "block", marginBottom: "0.5rem", fontWeight: "500" }}>
              Nova Senha
            </label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
              minLength={6}
              style={{
                width: "100%",
                padding: "0.75rem",
                border: "1px solid #e2e8f0",
                borderRadius: "0.375rem",
                fontSize: "1rem"
              }}
            />
          </div>

          <div style={{ marginBottom: "1.5rem" }}>
            <label style={{ display: "block", marginBottom: "0.5rem", fontWeight: "500" }}>
              Confirmar Nova Senha
            </label>
            <input
              type="password"
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
              required
              minLength={6}
              style={{
                width: "100%",
                padding: "0.75rem",
                border: "1px solid #e2e8f0",
                borderRadius: "0.375rem",
                fontSize: "1rem"
              }}
            />
          </div>

          {error && (
            <div style={{
              padding: "1rem",
              background: "#fee2e2",
              border: "1px solid #fecaca",
              borderRadius: "0.375rem",
              color: "#dc2626",
              marginBottom: "1.5rem",
              fontSize: "0.875rem"
            }}>
              {error}
            </div>
          )}

          <button
            type="submit"
            disabled={loading || !token}
            style={{
              width: "100%",
              padding: "0.75rem",
              background: loading || !token ? "#cbd5e0" : "#667eea",
              color: "white",
              border: "none",
              borderRadius: "0.5rem",
              fontSize: "1rem",
              fontWeight: "600",
              cursor: loading || !token ? "not-allowed" : "pointer",
              marginBottom: "1rem"
            }}
          >
            {loading ? "Redefinindo..." : "Redefinir Senha"}
          </button>

          <div style={{ textAlign: "center" }}>
            <Link
              href="/login"
              style={{
                color: "#667eea",
                fontWeight: "500",
                fontSize: "0.875rem",
                textDecoration: "none"
              }}
            >
              ← Voltar para Login
            </Link>
          </div>
        </form>
      </div>
    </div>
  )
}

export default function ResetPasswordPage() {
  return (
    <Suspense fallback={
      <div style={{
        minHeight: "100vh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        backgroundImage: "url('/pdimaker-background.jpg')",
        backgroundSize: "cover",
        backgroundPosition: "center",
        position: "relative"
      }}>
        <div style={{
          position: "absolute",
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          background: "rgba(0, 0, 0, 0.5)"
        }} />
        <div style={{
          position: "relative",
          zIndex: 1,
          color: "white",
          textAlign: "center"
        }}>
          Carregando...
        </div>
      </div>
    }>
      <ResetPasswordForm />
    </Suspense>
  )
}

