import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:google_fonts/google_fonts.dart';

import 'staf/beranda.dart';
import 'driver/beranda.dart' as driver_beranda;
import 'config.dart';

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

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> with TickerProviderStateMixin {
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  bool _isLoading = false;
  bool _obscureText = true;

  // --- UNIFIED DESIGN TOKENS (Matched with other pages) ---
  final Color bgLight = const Color(0xFFF7F9FB);
  final Color surfaceColor = const Color(0xFFFFFFFF);
  final Color primaryColor = const Color(0xFF0058BE);
  final Color primaryDark = const Color(0xFF004596);
  final Color textDark = const Color(0xFF191C1E);
  final Color textGray = const Color(0xFF424754);
  final Color borderLight = const Color(0xFFC2C6D6);

  late AnimationController _headerController;
  late Animation<double> _headerAnimation;

  @override
  void initState() {
    super.initState();
    _headerController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1200),
    );
    _headerAnimation =
        CurvedAnimation(parent: _headerController, curve: Curves.easeOutBack);
    _headerController.forward();
  }

  @override
  void dispose() {
    _headerController.dispose();
    super.dispose();
  }

  Future<void> _login() async {
    if (_emailController.text.isEmpty || _passwordController.text.isEmpty) {
      _showSnackBar("Harap isi semua bidang", Colors.orange);
      return;
    }

    setState(() => _isLoading = true);
    try {
      final response = await http.post(
        Uri.parse("${AppConfig.baseUrl}/login"),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: jsonEncode({
          'email': _emailController.text.trim(),
          'password': _passwordController.text,
        }),
      );

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        final prefs = await SharedPreferences.getInstance();
        await prefs.setString('userData', response.body);

        if (!mounted) return;

        String userRole = data['user']?['role'] ?? 'staf';

        if (userRole == 'driver') {
          Navigator.pushReplacement(
              context,
              MaterialPageRoute(
                  builder: (context) =>
                      driver_beranda.BerandaPage(userData: data)));
        } else {
          Navigator.pushReplacement(
              context,
              MaterialPageRoute(
                  builder: (context) => BerandaPage(userData: data)));
        }
      } else {
        _showSnackBar("Email atau password salah", Colors.redAccent);
      }
    } catch (e) {
      _showSnackBar("Terjadi kesalahan koneksi", Colors.redAccent);
    } finally {
      if (mounted) setState(() => _isLoading = false);
    }
  }

  void _showSnackBar(String msg, Color bg) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content: Container(
        padding: const EdgeInsets.symmetric(vertical: 8),
        child: Row(
          children: [
            Icon(
              bg == Colors.green
                  ? Icons.check_circle_outline
                  : Icons.error_outline_rounded,
              color: Colors.white,
              size: 28,
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    bg == Colors.green ? "Berhasil" : "Peringatan",
                    style: GoogleFonts.inter(
                        fontWeight: FontWeight.w800,
                        fontSize: 14,
                        color: Colors.white),
                  ),
                  Text(
                    msg,
                    style: GoogleFonts.inter(
                        fontSize: 12,
                        color: Colors.white.withOpacity(0.9),
                        fontWeight: FontWeight.w500),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
      behavior: SnackBarBehavior.floating,
      backgroundColor: bg.withOpacity(0.95),
      elevation: 0,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(20),
        side: BorderSide(color: Colors.white.withOpacity(0.2), width: 1),
      ),
      duration: const Duration(seconds: 3),
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: bgLight,
      body: Stack(
        children: [
          _buildBackgroundGradient(),
          SafeArea(
            child: SingleChildScrollView(
              padding: const EdgeInsets.symmetric(horizontal: 24),
              child: Column(
                children: [
                  const SizedBox(height: 60),
                  _buildHeaderLogo(),
                  const SizedBox(height: 48),
                  _buildLoginCard(),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBackgroundGradient() {
    return Container(
      height: MediaQuery.of(context).size.height * 0.4,
      decoration: BoxDecoration(
        gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [primaryColor, primaryDark]),
        borderRadius: const BorderRadius.only(
            bottomLeft: Radius.circular(40), bottomRight: Radius.circular(40)),
        boxShadow: [
          BoxShadow(
              color: primaryColor.withOpacity(0.3),
              blurRadius: 20,
              offset: const Offset(0, 10))
        ],
      ),
    );
  }

  Widget _buildHeaderLogo() {
    return ScaleTransition(
      scale: _headerAnimation,
      child: Column(
        children: [
          Container(
              padding: const EdgeInsets.all(20),
              decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.15),
                  shape: BoxShape.circle),
              child: GestureDetector(
                onDoubleTap: () =>
                    _showIPDialog(context), // Rahasia: Tap 2x di logo
                child: SizedBox(
                    width: 48,
                    height: 48,
                    child: CustomPaint(painter: MLogoPainter())),
              )),
          const SizedBox(height: 16),
          // NAMA APLIKASI DIUBAH DI SINI
          Text("My Laundry",
              style: GoogleFonts.inter(
                  color: Colors.white,
                  fontSize: 28,
                  fontWeight: FontWeight.w800,
                  letterSpacing: -1)),
          Text("Laundry Management System",
              style: GoogleFonts.inter(
                  color: Colors.white.withOpacity(0.7),
                  fontSize: 13,
                  fontWeight: FontWeight.w500)),
        ],
      ),
    );
  }

  Widget _buildLoginCard() {
    return Container(
      padding: const EdgeInsets.all(32),
      decoration: BoxDecoration(
        color: surfaceColor,
        borderRadius: BorderRadius.circular(24),
        border: Border.all(
            color: borderLight, width: 1.0), // Border tipis sesuai standar
        boxShadow: [
          BoxShadow(
              color: Colors.black.withOpacity(0.06),
              blurRadius: 20,
              offset: const Offset(0, 8))
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text("Selamat Datang",
              style: GoogleFonts.inter(
                  color: textDark,
                  fontSize: 22,
                  fontWeight: FontWeight.w800,
                  letterSpacing: -0.5)),
          const SizedBox(height: 4),
          Text("Masuk untuk mulai mengelola outlet",
              style: GoogleFonts.inter(
                  color: textGray, fontSize: 13, fontWeight: FontWeight.w500)),
          const SizedBox(height: 32),
          _buildField(
              "Email Address", Icons.alternate_email_rounded, _emailController),
          const SizedBox(height: 16),
          _buildField(
              "Password", Icons.lock_outline_rounded, _passwordController,
              isPass: true),
          const SizedBox(height: 32),
          _buildSubmitButton(),
        ],
      ),
    );
  }

  Widget _buildField(String label, IconData icon, TextEditingController ctrl,
      {bool isPass = false}) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label,
            style: GoogleFonts.inter(
                color: textDark, fontWeight: FontWeight.w700, fontSize: 12)),
        const SizedBox(height: 8),
        TextField(
          controller: ctrl,
          obscureText: isPass && _obscureText,
          style: GoogleFonts.inter(
              color: textDark, fontWeight: FontWeight.w600, fontSize: 14),
          decoration: InputDecoration(
            prefixIcon: Icon(icon, color: textGray, size: 20),
            suffixIcon: isPass
                ? IconButton(
                    icon: Icon(
                        _obscureText
                            ? Icons.visibility_off_rounded
                            : Icons.visibility_rounded,
                        color: textGray,
                        size: 18),
                    onPressed: () =>
                        setState(() => _obscureText = !_obscureText))
                : null,
            filled: true,
            fillColor: bgLight,
            hintText: "Masukkan $label",
            hintStyle: GoogleFonts.inter(
                color: textGray.withOpacity(0.5),
                fontSize: 13), // Opacity disesuaikan sedikit agar lebih terbaca
            contentPadding: const EdgeInsets.symmetric(vertical: 16),
            border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12),
                borderSide: BorderSide(
                    color: borderLight,
                    width: 1.0)), // Diubah dari none ke borderLight tipis
            enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12),
                borderSide: BorderSide(color: borderLight, width: 1.0)),
            focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12),
                borderSide: BorderSide(
                    color: primaryColor,
                    width: 1.0)), // Menyesuaikan style input
          ),
        ),
      ],
    );
  }

  Widget _buildSubmitButton() {
    return SizedBox(
      width: double.infinity,
      height: 56,
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
          backgroundColor: primaryColor,
          elevation: 0,
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        ),
        onPressed: _isLoading ? null : _login,
        child: _isLoading
            ? const SizedBox(
                height: 24,
                width: 24,
                child: CircularProgressIndicator(
                    color: Colors.white, strokeWidth: 2.5))
            : Text("MASUK SEKARANG",
                style: GoogleFonts.inter(
                    fontWeight: FontWeight.w800,
                    color: Colors.white,
                    letterSpacing: 0.5)),
      ),
    );
  }

  void _showIPDialog(BuildContext context) {
    final controller = TextEditingController(text: AppConfig.rawIp);
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        title: Text("Pengaturan IP Server",
            style: GoogleFonts.inter(fontWeight: FontWeight.w800)),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
                "Masukkan IP laptop Anda untuk menghubungkan aplikasi ke server.",
                style: GoogleFonts.inter(fontSize: 13, color: textGray)),
            const SizedBox(height: 20),
            TextField(
              controller: controller,
              decoration: InputDecoration(
                hintText: "Contoh: 192.168.1.XX",
                filled: true,
                fillColor: bgLight,
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                    borderSide: BorderSide.none),
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text("BATAL",
                style: GoogleFonts.inter(
                    fontWeight: FontWeight.bold, color: textGray)),
          ),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
              backgroundColor: primaryColor,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12)),
            ),
            onPressed: () async {
              await AppConfig.setIp(controller.text.trim());
              if (!context.mounted) return;
              Navigator.pop(context);
              _showSnackBar("IP Server berhasil diperbarui!", Colors.green);
            },
            child: Text("SIMPAN",
                style: GoogleFonts.inter(
                    fontWeight: FontWeight.bold, color: Colors.white)),
          ),
        ],
      ),
    );
  }
}

class MLogoPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paintLine = Paint()
      ..color = Colors.white
      ..strokeWidth = size.width * 0.1
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round;
    final paintDot = Paint()
      ..color = const Color(0xFF10B981)
      ..style = PaintingStyle.fill;
    double scale = size.width / 512.0;
    Path path = Path()
      ..moveTo(120 * scale, 360 * scale)
      ..lineTo(120 * scale, 220 * scale)
      ..cubicTo(120 * scale, 180 * scale, 150 * scale, 160 * scale, 180 * scale,
          190 * scale)
      ..lineTo(256 * scale, 266 * scale)
      ..lineTo(332 * scale, 190 * scale)
      ..cubicTo(362 * scale, 160 * scale, 392 * scale, 180 * scale, 392 * scale,
          220 * scale)
      ..lineTo(392 * scale, 360 * scale);
    canvas.drawPath(path, paintLine);
    canvas.drawCircle(Offset(256 * scale, 110 * scale), 32 * scale, paintDot);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
