import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import '../services/auth_service.dart';

class RegisterScreen extends StatefulWidget {
  const RegisterScreen({super.key});

  @override
  State<RegisterScreen> createState() => _RegisterScreenState();
}

class _RegisterScreenState extends State<RegisterScreen> {
  final AuthService _auth = AuthService();
  final _formKey = GlobalKey<FormState>();

  final nameController = TextEditingController();
  final emailController = TextEditingController();
  final passwordController = TextEditingController();
  final confirmPasswordController = TextEditingController();

  bool isLoading = false;
  bool isPasswordHidden = true;
  bool isConfirmPasswordHidden = true;

  void register() async {
    if (!_formKey.currentState!.validate()) return;

    if (passwordController.text != confirmPasswordController.text) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text("Password tidak sama")),
      );
      return;
    }

    setState(() => isLoading = true);

    try {
      User? user = await _auth.register(
        emailController.text.trim(),
        passwordController.text.trim(),
      );

      await user?.updateDisplayName(nameController.text.trim());

      await _auth.logout();

      if (!mounted) return;

      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text("Registrasi berhasil, silakan login"),
        ),
      );

      Navigator.pop(context);
    } catch (e) {
      String errorMsg = "Register gagal";

      if (e.toString().contains("email-already-in-use")) {
        errorMsg = "Email sudah terdaftar";
      } else if (e.toString().contains("invalid-email")) {
        errorMsg = "Format email tidak valid";
      } else if (e.toString().contains("weak-password")) {
        errorMsg = "Password terlalu lemah";
      }

      if (!mounted) return;

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(errorMsg)),
      );
    }

    if (mounted) {
      setState(() => isLoading = false);
    }
  }

  OutlineInputBorder buildBorder() {
    return OutlineInputBorder(
      borderRadius: BorderRadius.circular(18),
      borderSide: const BorderSide(
        color: Colors.black,
        width: 1.6,
      ),
    );
  }

  @override
  void dispose() {
    nameController.dispose();
    emailController.dispose();
    passwordController.dispose();
    confirmPasswordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          /// BACKGROUND
          Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage("assets/images/1.png"),
                fit: BoxFit.cover,
              ),
            ),
          ),

          /// OVERLAY
          Container(
            color: Colors.black.withOpacity(0.6),
          ),

          /// CONTENT
          Center(
            child: SingleChildScrollView(
              padding: const EdgeInsets.symmetric(horizontal: 30),
              child: Form(
                key: _formKey,
                child: Column(
                  children: [
                    Image.asset(
                      "assets/images/4.png",
                      height: 100,
                    ),

                    const SizedBox(height: 20),

                    const Text(
                      "Selada Hidroponik",
                      style: TextStyle(
                        fontSize: 26,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),

                    const SizedBox(height: 40),

                    /// CARD
                    Container(
                      padding: const EdgeInsets.all(28),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(30),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.25),
                            blurRadius: 30,
                            offset: const Offset(0, 15),
                          ),
                        ],
                      ),
                      child: Column(
                        children: [
                          const Text(
                            "Daftar sebagai pengguna baru",
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              color: Color(0xFF2E7D32),
                            ),
                          ),

                          const SizedBox(height: 30),

                          /// NAMA
                          TextFormField(
                            controller: nameController,
                            decoration: InputDecoration(
                              labelText: "Nama Lengkap",
                              prefixIcon: const Icon(Icons.person_outline),
                              enabledBorder: buildBorder(),
                              focusedBorder: buildBorder(),
                            ),
                            validator: (value) =>
                                value!.isEmpty ? "Nama wajib diisi" : null,
                          ),

                          const SizedBox(height: 20),

                          /// EMAIL
                          TextFormField(
                            controller: emailController,
                            keyboardType: TextInputType.emailAddress,
                            decoration: InputDecoration(
                              labelText: "Email",
                              prefixIcon: const Icon(Icons.email_outlined),
                              enabledBorder: buildBorder(),
                              focusedBorder: buildBorder(),
                            ),
                            validator: (value) {
                              if (value == null || value.isEmpty) {
                                return "Email wajib diisi";
                              }
                              if (!value.contains("@")) {
                                return "Email tidak valid";
                              }
                              return null;
                            },
                          ),

                          const SizedBox(height: 20),

                          /// PASSWORD
                          TextFormField(
                            controller: passwordController,
                            obscureText: isPasswordHidden,
                            decoration: InputDecoration(
                              labelText: "Password",
                              prefixIcon: const Icon(Icons.lock_outline),
                              enabledBorder: buildBorder(),
                              focusedBorder: buildBorder(),
                              suffixIcon: IconButton(
                                icon: Icon(
                                  isPasswordHidden
                                      ? Icons.visibility_off
                                      : Icons.visibility,
                                ),
                                onPressed: () {
                                  setState(() {
                                    isPasswordHidden = !isPasswordHidden;
                                  });
                                },
                              ),
                            ),
                            validator: (value) {
                              if (value == null || value.isEmpty) {
                                return "Password wajib diisi";
                              }
                              if (value.length < 6) {
                                return "Minimal 6 karakter";
                              }
                              return null;
                            },
                          ),

                          const SizedBox(height: 20),

                          /// KONFIRM PASSWORD
                          TextFormField(
                            controller: confirmPasswordController,
                            obscureText: isConfirmPasswordHidden,
                            decoration: InputDecoration(
                              labelText: "Konfirmasi Password",
                              prefixIcon: const Icon(Icons.lock_outline),
                              enabledBorder: buildBorder(),
                              focusedBorder: buildBorder(),
                              suffixIcon: IconButton(
                                icon: Icon(
                                  isConfirmPasswordHidden
                                      ? Icons.visibility_off
                                      : Icons.visibility,
                                ),
                                onPressed: () {
                                  setState(() {
                                    isConfirmPasswordHidden =
                                        !isConfirmPasswordHidden;
                                  });
                                },
                              ),
                            ),
                            validator: (value) {
                              if (value == null || value.isEmpty) {
                                return "Konfirmasi wajib diisi";
                              }
                              if (value != passwordController.text) {
                                return "Password tidak sama";
                              }
                              return null;
                            },
                          ),

                          const SizedBox(height: 35),

                          /// BUTTON
                          SizedBox(
                            width: double.infinity,
                            height: 55,
                            child: ElevatedButton(
                              onPressed: isLoading ? null : register,
                              style: ElevatedButton.styleFrom(
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(18),
                                ),
                                backgroundColor: const Color(0xFF2E7D32),
                              ),
                              child: isLoading
                                  ? const CircularProgressIndicator(
                                      color: Colors.white,
                                    )
                                  : const Text(
                                      "Sign Up",
                                      style: TextStyle(
                                        fontSize: 17,
                                        fontWeight: FontWeight.bold,
                                        color: Colors.white,
                                      ),
                                    ),
                            ),
                          ),
                        ],
                      ),
                    ),

                    const SizedBox(height: 25),

                    GestureDetector(
                      onTap: () => Navigator.pop(context),
                      child: const Text(
                        "Sudah punya akun? Login sekarang!",
                        style: TextStyle(
                          color: Colors.white,
                          decoration: TextDecoration.underline,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
