import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'dashboard.dart';
import 'history.dart';
import 'pesan.dart';
import '../widgets/fade_in_up.dart';
class AkunScreen extends StatefulWidget {
  const AkunScreen({super.key});

  @override
  State<AkunScreen> createState() => _AkunScreenState();
}

class _AkunScreenState extends State<AkunScreen> {
  final user = FirebaseAuth.instance.currentUser;
  int selectedIndex = 3;

  String get username {
    if (user?.displayName != null && user!.displayName!.isNotEmpty) {
      return user!.displayName!;
    }
    if (user?.email != null) return user!.email!.split("@")[0];
    return "User";
  }
  String get email => user?.email ?? "email";

  Future<void> _resetFermentasi() async {
    await FirebaseDatabase.instance.ref("control").update({
      "reset_request": true,
      "fermentasi_aktif": false,
      "waktu_mulai_ui": 0,
    });
    await FirebaseDatabase.instance.ref("fermentasi").update({
      "waktu": 0,
      "status": "Belum Mulai",
    });

    ScaffoldMessenger.of(
      context,
    ).showSnackBar(const SnackBar(content: Text("Reset berhasil dikirim")));
  }

  Future<void> _logout() async {
    await FirebaseAuth.instance.signOut();
    if (mounted) Navigator.pushReplacementNamed(context, '/login');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: _buildBottomNavbar(),

      body: Stack(
        children: [
          Container(
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                stops: [0.0, 0.4, 0.7, 1.0],
                colors: [
                  Color(0xFFE8F5E9),
                  Color(0xFFFFFDF0),
                  Color(0xFFF1F8E9),
                  Color(0xFFE8F5E9),
                ],
              ),
            ),
          ),
          SafeArea(
            bottom: false,
            child: SingleChildScrollView(
              padding: const EdgeInsets.fromLTRB(20, 24, 20, 110),
              child: Column(
                children: [
                  /// HEADER
                  FadeInUp(
                    delay: 0,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        IconButton(
                          icon: const Icon(Icons.arrow_back_ios_new, size: 20),
                          onPressed: () => Navigator.pushReplacement(
                            context,
                            MaterialPageRoute(builder: (context) => const DashboardPage()),
                          ),
                        ),
                        const Text(
                          "My Account",
                          style: TextStyle(
                            fontSize: 20,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        GestureDetector(
                          onTap: () => Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => const NotificationPage(),
                            ),
                          ),
                          child: Container(
                            width: 42,
                            height: 42,
                            decoration: BoxDecoration(
                            color: const Color(0xFF2E7D32),
                            borderRadius: BorderRadius.circular(14),
                          ),
                          child: const Icon(
                            Icons.notifications_none_rounded,
                            color: Colors.white,
                            size: 22,
                          ),
                          ),
                        ),
                      ],
                    ),
                  ),

                const SizedBox(height: 25),

                /// USERNAME CARD
                FadeInUp(
                  delay: 150,
                  child: _buildTopCard(
                    icon: Icons.work_outline,
                    text: username,
                    color: Colors.green,
                  ),
                ),

                const SizedBox(height: 20),

                /// PROJECT NAME
                FadeInUp(delay: 300, child: _buildProjectCard()),

                const SizedBox(height: 20),

                /// PERSONAL INFO
                FadeInUp(delay: 450, child: _buildInfoCard()),

                const SizedBox(height: 30),

                /// LOGOUT
                FadeInUp(
                  delay: 600,
                  child: SizedBox(
                  width: double.infinity,
                  height: 50,
                  child: ElevatedButton(
                    onPressed: _logout,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color(0xFFF9A825),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(14),
                      ),
                    ),
                    child: const Text(
                      "LOGOUT",
                      style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                        fontSize: 16,
                      ),
                    ),
                  ),
                  ),
                ),

                const SizedBox(height: 30),
              ],
            ),
          ),
          ),
        ],
      ),
    );
  }

  /// ================= WIDGET =================

  Widget _buildTopCard({
    required IconData icon,
    required String text,
    required Color color,
  }) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: _cardStyle(),
      child: Row(
        children: [
          _iconBox(icon, color),
          const SizedBox(width: 12),
          Text(text, style: const TextStyle(fontSize: 14)),
        ],
      ),
    );
  }

  Widget _buildProjectCard() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(18),
      decoration: _cardStyle(),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: const [
          Text(
            "Project Name",
            style: TextStyle(fontSize: 12, color: Colors.black54),
          ),
          SizedBox(height: 6),
          Text(
            "Fermentasi tape ketan dan tape singkong",
            style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
          ),
        ],
      ),
    );
  }

  Widget _buildInfoCard() {
    return Container(
      padding: const EdgeInsets.all(18),
      decoration: _cardStyle(),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            "PERSONAL INFO",
            style: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.bold,
              color: Colors.black45,
            ),
          ),

          const SizedBox(height: 15),

          _infoRow(Icons.person, Colors.blue, "Full Name", username),
          const SizedBox(height: 12),

          _infoRow(Icons.mail, Colors.blueGrey, "Email", email),
          const SizedBox(height: 12),

          GestureDetector(
            onTap: _resetFermentasi,
            behavior: HitTestBehavior.opaque,
            child: _infoRow(
              Icons.refresh,
              Colors.lightBlue,
              "Fermentasi",
              "reset waktu baru",
            ),
          ),
        ],
      ),
    );
  }

  Widget _infoRow(IconData icon, Color color, String title, String value) {
    return Row(
      children: [
        _iconBox(icon, color),
        const SizedBox(width: 12),

        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              title,
              style: const TextStyle(fontSize: 12, color: Colors.black54),
            ),
            Text(
              value,
              style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
            ),
          ],
        ),
      ],
    );
  }

  Widget _iconBox(IconData icon, Color color) {
    return Container(
      width: 40,
      height: 40,
      decoration: BoxDecoration(
        color: color.withOpacity(0.2),
        borderRadius: BorderRadius.circular(10),
      ),
      child: Icon(icon, color: color),
    );
  }

  BoxDecoration _cardStyle() {
    return BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.circular(20),
      boxShadow: [
        BoxShadow(
          color: Colors.black.withOpacity(0.05),
          blurRadius: 15,
          offset: const Offset(0, 5),
        ),
      ],
    );
  }

  Widget _buildBottomNavbar() {
    return Container(
      decoration: const BoxDecoration(
        color: Color(0xFFE8F5E9),
        borderRadius: BorderRadius.vertical(top: Radius.circular(30)),
        boxShadow: [
          BoxShadow(
            color: Colors.black12,
            blurRadius: 10,
            offset: Offset(0, -2),
          ),
        ],
      ),
      child: ClipRRect(
        borderRadius: const BorderRadius.vertical(top: Radius.circular(30)),
        child: BottomNavigationBar(
          currentIndex: 2,
          onTap: (index) {
            if (index == 0) {
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(builder: (context) => const DashboardPage()),
              );
            } else if (index == 1) {
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(builder: (context) => const HistoryPage()),
              );
            }
          },
          showSelectedLabels: false,
          showUnselectedLabels: false,
          backgroundColor: Colors.transparent,
          elevation: 0,
          type: BottomNavigationBarType.fixed,
          items: [
            BottomNavigationBarItem(
              icon: _navIcon(Icons.home_filled, 0),
              label: 'Home',
            ),
            BottomNavigationBarItem(
              icon: _navIcon(Icons.history, 1),
              label: 'History',
            ),
            BottomNavigationBarItem(
              icon: _navIcon(Icons.people_alt_rounded, 2),
              label: 'Profile',
            ),
          ],
        ),
      ),
    );
  }

  Widget _navIcon(IconData icon, int index) {
    bool isSelected = index == 2;
    return AnimatedContainer(
      duration: const Duration(milliseconds: 300),
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(16),
        gradient: isSelected
            ? const LinearGradient(
                colors: [Color(0xFF2E7D32), Color(0xFF4CAF50)],
              )
            : null,
      ),
      child: Icon(
        icon,
        color: isSelected ? Colors.white : const Color(0xFF81C784),
        size: 24,
      ),
    );
  }
}
