import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../api/LoginApi.dart';

const _bg        = Color(0xFFF9FAFB);
const _bg1       = Color(0xFFFFFFFF);
const _green     = Color(0xFF10B981);
const _greenDim  = Color(0x1A2bff88);
const _t1        = Color(0xFF111827);
const _t2        = Color(0xFF6B7280);
const _t3        = Color(0xFF9CA3AF);
const _line2     = Color(0xFFE5E7EB);

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

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

class _LoginScreenState extends State<LoginScreen> {
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  bool _isPasswordVisible = false;
  bool _isLoading = false;
  final _apiService = ApiService();

  Future<void> _handleLogin() async {
    if (_usernameController.text.isEmpty || _passwordController.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Username dan Password harus diisi')),
      );
      return;
    }

    setState(() => _isLoading = true);
    
    try {
      final response = await _apiService.login(
        _usernameController.text,
        _passwordController.text,
      );

      if (response['success']) {
        Navigator.pushReplacementNamed(context, '/dashboard');
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(response['message'] ?? 'Login gagal')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Terjadi kesalahan koneksi')),
      );
    } finally {
      setState(() => _isLoading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: _bg,
      body: AnnotatedRegion<SystemUiOverlayStyle>(
        value: SystemUiOverlayStyle.light,
        child: SingleChildScrollView(
          padding: const EdgeInsets.symmetric(horizontal: 30),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const SizedBox(height: 100),
              
              // LOGO BARU (NATURAL & PROFESIONAL)
              Center(
                child: Container(
                  height: 120, width: 120,
                  decoration: BoxDecoration(
                    color: _bg1,
                    borderRadius: BorderRadius.circular(30),
                    boxShadow: [BoxShadow(color: _green.withOpacity(0.1), blurRadius: 40)],
                  ),
                  child: Center(
                    child: Icon(Icons.water_drop_rounded, color: _green, size: 70), // Fallback icon while assets loading
                  ),
                ),
              ),

              const SizedBox(height: 32),
              Center(
                child: Column(
                  children: [
                    RichText(
                      text: const TextSpan(
                        children: [
                          TextSpan(text: 'PDAM ', style: TextStyle(fontSize: 28, fontWeight: FontWeight.w900, color: _t1)),
                          TextSpan(text: 'Teknisi', style: TextStyle(fontSize: 28, fontWeight: FontWeight.w900, color: _green)),
                        ],
                      ),
                    ),
                    const SizedBox(height: 8),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                      decoration: BoxDecoration(color: _bg1, borderRadius: BorderRadius.circular(100), border: Border.all(color: _line2)),
                      child: const Text('Sistem Manajemen Teknisi', style: TextStyle(color: _t2, fontSize: 11, fontWeight: FontWeight.w600)),
                    ),
                  ],
                ),
              ),

              const SizedBox(height: 60),

              // USERNAME
              _label('USERNAME', Icons.person_outline_rounded),
              TextField(
                controller: _usernameController,
                style: const TextStyle(color: _t1),
                decoration: _inputStyle('Masukkan username'),
              ),

              const SizedBox(height: 24),

              // PASSWORD
              _label('PASSWORD', Icons.lock_outline_rounded),
              TextField(
                controller: _passwordController,
                obscureText: !_isPasswordVisible,
                style: const TextStyle(color: _t1),
                decoration: _inputStyle('Masukkan password').copyWith(
                  suffixIcon: IconButton(
                    icon: Icon(_isPasswordVisible ? Icons.visibility_off : Icons.visibility, color: _t3, size: 20),
                    onPressed: () => setState(() => _isPasswordVisible = !_isPasswordVisible),
                  ),
                ),
              ),

              const SizedBox(height: 12),
              Align(
                alignment: Alignment.centerRight,
                child: TextButton(
                  onPressed: () {},
                  child: const Text('Lupa password?', style: TextStyle(color: _t2, fontSize: 12, fontWeight: FontWeight.w600)),
                ),
              ),

              const SizedBox(height: 32),

              // BUTTON MASUK
              SizedBox(
                width: double.infinity,
                height: 56,
                child: ElevatedButton(
                  onPressed: _isLoading ? null : _handleLogin,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: _green,
                    foregroundColor: Colors.black,
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
                    elevation: 10,
                    shadowColor: _green.withOpacity(0.4),
                  ),
                  child: _isLoading 
                    ? const SizedBox(width: 24, height: 24, child: CircularProgressIndicator(color: Colors.black, strokeWidth: 3))
                    : const Text('MASUK', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w900, letterSpacing: 1)),
                ),
              ),

              const SizedBox(height: 40),
              
              // INFO
              const Divider(color: _line2),
              const SizedBox(height: 24),
              Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(color: _bg1, borderRadius: BorderRadius.circular(20), border: Border.all(color: _line2)),
                child: const Row(
                  children: [
                    Icon(Icons.info_outline_rounded, color: _green, size: 20),
                    const SizedBox(width: 14),
                    Expanded(
                      child: Text('Butuh bantuan? Hubungi admin PDAM Anda untuk mendapatkan akses.', 
                        style: TextStyle(color: _t2, fontSize: 11, height: 1.5, fontWeight: FontWeight.w500)),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 40),
            ],
          ),
        ),
      ),
    );
  }

  Widget _label(String text, IconData icon) {
    return Padding(
      padding: const EdgeInsets.only(left: 4, bottom: 8),
      child: Row(
        children: [
          Icon(icon, color: _green, size: 14),
          const SizedBox(width: 8),
          Text(text, style: const TextStyle(color: _t2, fontSize: 10, fontWeight: FontWeight.w800, letterSpacing: 1.5)),
        ],
      ),
    );
  }

  InputDecoration _inputStyle(String hint) {
    return InputDecoration(
      hintText: hint,
      hintStyle: const TextStyle(color: _t3, fontSize: 14),
      filled: true,
      fillColor: _bg1,
      contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 18),
      border: OutlineInputBorder(borderRadius: BorderRadius.circular(18), borderSide: const BorderSide(color: _line2)),
      enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(18), borderSide: const BorderSide(color: _line2)),
      focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(18), borderSide: const BorderSide(color: _green, width: 1.5)),
    );
  }
}