import 'package:digiplug/bat_theme/bat_theme.dart';
import 'package:digiplug/core/navigation/navigator.dart';
import 'package:digiplug/data/repositories/auth_repository.dart';
import 'package:digiplug/shared/widgets/button.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

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

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  // Controller untuk mengambil input dari text field
  final _emailController = TextEditingController(text: '');
  final _passwordController = TextEditingController(text: '');

  // State untuk mengelola status loading dan visibilitas password
  bool _isLoading = false;
  bool _isPasswordVisible = false;

  // Fungsi yang dipanggil saat tombol login ditekan
  Future<void> _handleLogin() async {
    // Sembunyikan keyboard
    FocusScope.of(context).unfocus();

    setState(() => _isLoading = true);

    // Panggil AuthRepository dari provider
    final authRepo = context.read<AuthRepository>();

    try {
      // Panggil fungsi login dengan data dari controller
      await authRepo.login(
        _emailController.text.trim(),
        _passwordController.text.trim(),
      );

      // Jika berhasil (tidak ada error), navigasi ke dashboard
      if (mounted) {
        AppNavigator.pushNamedAndClear(dashboardRoute);
      }
    } catch (e) {
      // Jika terjadi error, tampilkan pesan menggunakan SnackBar
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
          content: Text(e.toString().replaceAll("Exception: ", "")),
          backgroundColor: Colors.redAccent,
        ));
      }
    } finally {
      // Pastikan state loading di-reset, baik berhasil maupun gagal
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  @override
  void dispose() {
    _emailController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var theme = BatThemeData.of(context);
    return Scaffold(
      backgroundColor: theme.colors.background,
      body: SingleChildScrollView(
        child: ConstrainedBox(
          constraints: BoxConstraints(
            minHeight: MediaQuery.of(context).size.height,
          ),
          child: IntrinsicHeight(
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 24.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  SizedBox(height: 109.h),
                  Image.asset("assets/images/logo.png",
                      color: theme.colors.primary, width: 200.w),
                  SizedBox(height: 10.h),
                  Text(
                    'Login to your account',
                    style: theme.typography.headline4.copyWith(
                        color: theme.colors.primary,
                        fontWeight: FontWeight.w500),
                  ),
                  SizedBox(height: 48.h),
                  TextField(
                    controller: _emailController,
                    keyboardType: TextInputType.emailAddress,
                    decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Username',
                    ),
                  ),
                  SizedBox(height: 24.h),
                  TextField(
                    controller: _passwordController,
                    obscureText: !_isPasswordVisible,
                    decoration: InputDecoration(
                      border: const OutlineInputBorder(),
                      labelText: 'Password',
                      suffixIcon: IconButton(
                        icon: Icon(
                          _isPasswordVisible
                              ? Icons.visibility_off
                              : Icons.visibility,
                        ),
                        onPressed: () {
                          setState(() {
                            _isPasswordVisible = !_isPasswordVisible;
                          });
                        },
                      ),
                    ),
                  ),
                  SizedBox(height: 64.h),
                  AppButtonPrimary(
                    label: _isLoading ? 'Loading...' : 'Login',
                    onPressed: _isLoading ? null : _handleLogin,
                  ),
                  const Spacer(),
                  SizedBox(
                      height: MediaQuery.of(context).padding.bottom + 24.h),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
