import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:on_field_work/controller/layout/layout_controller.dart';
import 'package:on_field_work/helpers/widgets/my_responsive.dart';
import 'package:on_field_work/helpers/widgets/my_text.dart';
import 'package:on_field_work/helpers/services/storage/local_storage.dart';
import 'package:on_field_work/model/employees/employee_info.dart';
import 'package:on_field_work/helpers/services/api_endpoints.dart';
import 'package:on_field_work/images.dart';
import 'package:on_field_work/view/layouts/user_profile_right_bar.dart';
import 'package:on_field_work/helpers/services/tenant_service.dart';
import 'package:on_field_work/helpers/utils/mixins/ui_mixin.dart';

class Layout extends StatefulWidget {
  final Widget? child;
  final Widget? floatingActionButton;

  const Layout({super.key, this.child, this.floatingActionButton});

  @override
  State<Layout> createState() => _LayoutState();
}

class _LayoutState extends State<Layout> with UIMixin {
  final LayoutController controller = LayoutController();
  final EmployeeInfo? employeeInfo = LocalStorage.getEmployeeInfo();
  final bool isBetaEnvironment = ApiEndpoints.baseUrl.contains("stage");

  bool hasMpin = true;

  @override
  void initState() {
    super.initState();
    _checkMpinStatus();
  }

  Future<void> _checkMpinStatus() async {
    final bool mpinStatus = await LocalStorage.getIsMpin();
    if (mounted) {
      setState(() {
        hasMpin = mpinStatus;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MyResponsive(builder: (context, _, screenMT) {
      return GetBuilder(
        init: controller,
        builder: (_) {
          return (screenMT.isMobile || screenMT.isTablet)
              ? _buildScaffold(context, isMobile: true)
              : _buildScaffold(context);
        },
      );
    });
  }

  Widget _buildScaffold(BuildContext context, {bool isMobile = false}) {
    final primaryColor = contentTheme.primary;

    return Scaffold(
        key: controller.scaffoldKey,
        endDrawer: const UserProfileBar(),
        floatingActionButton: widget.floatingActionButton,
        body: Column(
          children: [
            // Solid primary background area
            Container(
              width: double.infinity,
              color: primaryColor,
              child: _buildHeaderContent(isMobile),
            ),
            Expanded(
              child: Container(
                width: double.infinity,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [
                      primaryColor,
                      primaryColor.withOpacity(0.7),
                      primaryColor.withOpacity(0.0),
                    ],
                    stops: const [0.0, 0.1, 0.3],
                  ),
                ),
                child: SafeArea(
                  top: false,
                  child: GestureDetector(
                    behavior: HitTestBehavior.translucent,
                    onTap: () {},
                    child: SingleChildScrollView(
                      key: controller.scrollKey,
                      padding: EdgeInsets.zero,
                      child: widget.child,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ));
  }

  Widget _buildHeaderContent(bool isMobile) {
    final selectedTenant = TenantService.currentTenant;

    return Padding(
      padding: const EdgeInsets.fromLTRB(10, 45, 10, 0),
      child: Container(
        margin: const EdgeInsets.only(bottom: 18),
        width: double.infinity,
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(6),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.08),
              blurRadius: 6,
              offset: const Offset(0, 3),
            ),
          ],
        ),
        child: Row(
          children: [
            // Logo section
            Stack(
              clipBehavior: Clip.none,
              children: [
                Image.asset(
                  Images.logoDark,
                  height: 50,
                  width: 50,
                  fit: BoxFit.contain,
                ),

                // Beta badge
                if (ApiEndpoints.baseUrl.contains("stage"))
                  Positioned(
                    bottom: 0,
                    left: 0,
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 4, vertical: 2),
                      decoration: BoxDecoration(
                        color: Colors.deepPurple,
                        borderRadius: BorderRadius.circular(4),
                        border: Border.all(color: Colors.white, width: 1.2),
                      ),
                      child: const Text(
                        'B',
                        style: TextStyle(
                          fontSize: 10,
                          fontWeight: FontWeight.bold,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ),
              ],
            ),

            const SizedBox(width: 12),

            // Titles
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  MyText.bodyLarge(
                    "Dashboard",
                    fontWeight: 700,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    color: Colors.black87,
                  ),
                  if (selectedTenant != null)
                    MyText.bodySmall(
                      "Organization: ${selectedTenant.name}",
                      color: Colors.black54,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                ],
              ),
            ),

            // Menu button with red dot if MPIN missing
            Stack(
              clipBehavior: Clip.none,
              alignment: Alignment.center,
              children: [
                IconButton(
                  icon: const Icon(Icons.menu, color: Colors.black87),
                  onPressed: () =>
                      controller.scaffoldKey.currentState?.openEndDrawer(),
                ),
                if (!hasMpin)
                  Positioned(
                    right: 10,
                    top: 10,
                    child: Container(
                      width: 14,
                      height: 14,
                      decoration: BoxDecoration(
                        color: Colors.redAccent,
                        shape: BoxShape.circle,
                        border: Border.all(color: Colors.white, width: 2),
                      ),
                    ),
                  ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
