import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:provider/provider.dart';

import '../../Notifiers/hrmProvider/CasualLeaveHistoryProvider.dart';
import '../../Utils/app_colors.dart';

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

  @override
  State<CasualLeaveHistoryScreen> createState() =>
      _CasualLeaveHistoryScreenState();
}

class _CasualLeaveHistoryScreenState extends State<CasualLeaveHistoryScreen> {
  @override
  void initState() {
    super.initState();

    // Fetch data once when the screen loads
    Future.delayed(Duration.zero, () {
      final provider =
      Provider.of<CasualLeaveHistoryProvider>(context, listen: false);
      provider.fetchCasualLeaveHistory(context);
    });
  }

  @override
  Widget build(BuildContext context) {
    final double screenWidth = MediaQuery.of(context).size.width;
    final double screenHeight = MediaQuery.of(context).size.height;
    final bool isSmallScreen = screenWidth < 360;
    final bool isLargeScreen = screenWidth > 600;
    final bool isTablet = screenWidth > 768;

    return Scaffold(
      backgroundColor: AppColors.scaffold_bg_color,
      appBar: AppBar(
        automaticallyImplyLeading: false,
        backgroundColor: Colors.white,
        title: Row(
          children: [
            InkResponse(
              onTap: () => Navigator.pop(context, true),
              child: SvgPicture.asset(
                "assets/svg/appbar_back_button.svg",
                height: isSmallScreen ? 22 : isTablet ? 28 : 25,
              ),
            ),
            SizedBox(width: isSmallScreen ? 8 : isTablet ? 12 : 10),
            Text(
              "Casual Leave History",
              style: TextStyle(
                fontSize: isSmallScreen ? 16 : isTablet ? 20 : 18,
                fontFamily: "Plus Jakarta Sans",
                fontWeight: FontWeight.w600,
                color: Colors.black87,
              ),
            ),
          ],
        ),
      ),
      body: Consumer<CasualLeaveHistoryProvider>(
        builder: (context, provider, _) {
          if (provider.isLoading) {
            return const Center(child: CircularProgressIndicator());
          }

          if (provider.errorMessage != null) {
            return Padding(
              padding: EdgeInsets.symmetric(horizontal: isSmallScreen ? 16 : 20),
              child: Center(
                child: Text(
                  provider.errorMessage!,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: isSmallScreen ? 14 : 16,
                    fontFamily: "Plus Jakarta Sans",
                  ),
                  textAlign: TextAlign.center,
                ),
              ),
            );
          }

          if (provider.casualLeaveHistoryList.isEmpty) {
            return Padding(
              padding: EdgeInsets.symmetric(horizontal: isSmallScreen ? 16 : 20),
              child: Center(
                child: Text(
                  "No leave history found",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: isSmallScreen ? 14 : 16,
                    fontFamily: "Plus Jakarta Sans",
                  ),
                ),
              ),
            );
          }

          return ListView.builder(
            padding: EdgeInsets.all(isSmallScreen ? 8 : isTablet ? 16 : 12),
            itemCount: provider.casualLeaveHistoryList.length,
            itemBuilder: (context, index) {
              final item = provider.casualLeaveHistoryList[index];
              return Padding(
                padding: EdgeInsets.symmetric(
                  vertical: isSmallScreen ? 4 : isTablet ? 8 : 6,
                ),
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(
                      isSmallScreen ? 12 : isTablet ? 20 : 16,
                    ),
                  ),
                  padding: EdgeInsets.symmetric(
                    horizontal: isSmallScreen ? 12 : isTablet ? 18 : 14,
                    vertical: isSmallScreen ? 8 : isTablet ? 14 : 10,
                  ),
                  child: Row(
                    children: [
                      // --- Avatar Circle ---
                      Container(
                        height: isSmallScreen ? 40 : isTablet ? 54 : 46,
                        width: isSmallScreen ? 40 : isTablet ? 54 : 46,
                        decoration: BoxDecoration(
                          color: _getAvatarColor(item.type),
                          shape: BoxShape.circle,
                        ),
                        child: Center(
                          child: Text(
                            getText(item.type),
                            style: TextStyle(
                              fontSize: isSmallScreen ? 13 : isTablet ? 17 : 15,
                              fontFamily: "Plus Jakarta Sans",
                              fontWeight: FontWeight.w500,
                              color: _getAvatarTxtColor(item.type),
                            ),
                          ),
                        ),
                      ),
                      SizedBox(width: isSmallScreen ? 10 : isTablet ? 16 : 12),

                      // --- Main Content ---
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              item.des ?? "No Description",
                              style: TextStyle(
                                fontFamily: "JakartaRegular",
                                fontSize: isSmallScreen ? 13 : isTablet ? 16 : 14,
                                color: AppColors.semi_black,
                                height: 1.2,
                              ),
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                            ),
                            SizedBox(height: isSmallScreen ? 2 : isTablet ? 6 : 4),
                            Text(
                              item.year ?? "",
                              style: TextStyle(
                                fontFamily: "JakartaRegular",
                                fontSize: isSmallScreen ? 12 : isTablet ? 14 : 13,
                                color: AppColors.grey_semi,
                              ),
                            ),
                          ],
                        ),
                      ),

                      // --- Duration Badge (like "1 Day") ---
                      Container(
                        decoration: BoxDecoration(
                          color: Colors.blue.shade50,
                          borderRadius: BorderRadius.circular(
                            isSmallScreen ? 16 : isTablet ? 24 : 20,
                          ),
                        ),
                        padding: EdgeInsets.symmetric(
                          horizontal: isSmallScreen ? 12 : isTablet ? 16 : 14,
                          vertical: isSmallScreen ? 4 : isTablet ? 8 : 6,
                        ),
                        child: Text(
                          "${item.cnt ?? '0'} Day${(item.cnt ?? '0') == '1' ? '' : 's'}",
                          style: TextStyle(
                            fontFamily: "JakartaMedium",
                            fontSize: isSmallScreen ? 12 : isTablet ? 15 : 14,
                            color: Color(0xff1487c9),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              );
            },
          );
        },
      ),
    );
  }

  /// Avatar color generator
  Color _getAvatarColor(value) {
    var color = AppColors.approved_bg_color;
    switch (value) {
      case 'minus':
        return AppColors.rejected_bg_color;
      case 'plus':
        return AppColors.approved_bg_color;
    }
    return color;
  }

  Color _getAvatarTxtColor(value) {
    var color = AppColors.approved_text_color;
    switch (value) {
      case 'minus':
        return AppColors.rejected_text_color;
      case 'plus':
        return AppColors.approved_text_color;
    }
    return color;
  }

  String getText(value) {
    switch (value) {
      case 'minus':
        return "M";
      case 'plus':
        return "P";
      default:
        return "-";
    }
  }
}