"use client";

import { useState } from "react";
import { account, ID } from "@/lib/appwrite";
import { useRouter } from "next/navigation";

export default function CadastroTeste() {
  const router = useRouter();
  const [formData, setFormData] = useState({
    nome: "",
    email: "",
    senha: "",
  });
  const [loading, setLoading] = useState(false);
  const [erro, setErro] = useState("");
  const [sucesso, setSucesso] = useState("");

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

    try {
      console.log("🚀 Tentando criar conta...");

      // Tentar criar conta
      const userId = ID.unique();
      console.log("📝 ID gerado:", userId);

      const user = await account.create(
        userId,
        formData.email,
        formData.senha,
        formData.nome
      );

      console.log("✅ Conta criada:", user);
      setSucesso("Conta criada com sucesso! Fazendo login...");

      // Fazer login automaticamente
      await account.createEmailPasswordSession(formData.email, formData.senha);
      console.log("✅ Login realizado");

      // Redirecionar para completar registro
      setTimeout(() => {
        router.push("/completar-registro");
      }, 2000);
    } catch (error: any) {
      console.error("❌ Erro ao criar conta:", error);
      setErro(`Erro: ${error.message || "Erro desconhecido"}`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-md w-full space-y-8">
        <div className="bg-white p-8 rounded-lg shadow-lg">
          <div className="text-center mb-8">
            <h1 className="text-3xl font-bold text-blue-600">SaveInMed</h1>
            <p className="text-gray-600">Plataforma B2B de Medicamentos</p>
          </div>

          <h2 className="text-2xl font-semibold text-center mb-6">
            Criar Conta (Teste)
          </h2>

          {erro && (
            <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
              <p className="text-red-800">{erro}</p>
            </div>
          )}

          {sucesso && (
            <div className="bg-green-50 border border-green-200 rounded-lg p-4 mb-6">
              <p className="text-green-800">{sucesso}</p>
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Nome Completo
              </label>
              <input
                type="text"
                required
                value={formData.nome}
                onChange={(e) =>
                  setFormData({ ...formData, nome: e.target.value })
                }
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                placeholder="Seu nome completo"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Email
              </label>
              <input
                type="email"
                required
                value={formData.email}
                onChange={(e) =>
                  setFormData({ ...formData, email: e.target.value })
                }
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                placeholder="seu@email.com"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Senha
              </label>
              <input
                type="password"
                required
                minLength={8}
                value={formData.senha}
                onChange={(e) =>
                  setFormData({ ...formData, senha: e.target.value })
                }
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                placeholder="Mínimo 8 caracteres"
              />
            </div>

            <button
              type="submit"
              disabled={loading}
              className="w-full bg-green-600 hover:bg-green-700 text-white py-3 px-4 rounded-lg font-medium disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {loading ? "🔄 Criando Conta..." : "✅ Criar Conta"}
            </button>
          </form>

          <div className="mt-6 text-center">
            <button
              onClick={() => router.push("/")}
              className="text-blue-600 hover:text-blue-700 font-medium"
            >
              ← Voltar para Login
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
