import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/string_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/modules/site_request_module/models/site_request_model.dart';
import 'package:test_sa/modules/site_request_module/providers/site_request_provider.dart';
import 'package:test_sa/modules/site_request_module/screens/site_request_form_screen.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/app_style/app_text_styles.dart';
import 'package:test_sa/new_views/common_widgets/default_app_bar.dart';
import 'package:test_sa/views/widgets/loaders/app_loading.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';
import 'package:test_sa/views/widgets/item_views/info_date_widget.dart';
import 'package:test_sa/views/widgets/item_views/info_header_widget.dart';
import 'package:test_sa/views/widgets/item_views/info_text_widget.dart';
import 'package:test_sa/views/widgets/requests/request_status.dart';

/// Screen displaying the history of site requests with pagination support
class SiteRequestHistoryScreen extends StatefulWidget {
  static const String routeName = "/site_request_history";

  const SiteRequestHistoryScreen({Key? key}) : super(key: key);

  @override
  State<SiteRequestHistoryScreen> createState() => _SiteRequestHistoryScreenState();
}

class _SiteRequestHistoryScreenState extends State<SiteRequestHistoryScreen> {
  late SiteRequestProvider _provider;
  late UserProvider _userProvider;
  late ScrollController _scrollController;
  bool _isLoadingData = true;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _scrollController.addListener(_onScroll);
    _loadHistoryData();
  }

  @override
  void dispose() {
    _scrollController.removeListener(_onScroll);
    _scrollController.dispose();
    super.dispose();
  }

  void _onScroll() {
    if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent * 0.9) {
      _provider.loadMoreSiteRequests(userProvider: _userProvider);
    }
  }

  Future<void> _loadHistoryData() async {
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      _provider = Provider.of<SiteRequestProvider>(context, listen: false);
      _userProvider = Provider.of<UserProvider>(context, listen: false);

      await _provider.fetchSiteRequests(pageNumber: 1, pageSize: 10, userProvider: _userProvider);

      if (mounted) {
        setState(() => _isLoadingData = false);
      }
    });
  }

  Future<void> _refreshData() async {
    setState(() {
      _isLoadingData = true;
    });
    await _provider.refreshSiteRequests(userProvider: _userProvider);
    if (mounted) {
      setState(() => _isLoadingData = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    _provider = Provider.of<SiteRequestProvider>(context);
    _userProvider = Provider.of<UserProvider>(context);

    return Scaffold(
      backgroundColor: AppColor.scaffoldBackground(context),
      appBar: DefaultAppBar(
        title: "Site Request History",
        actions: [_buildNewRequestButton()],
      ),
      body: _buildBody(),
    );
  }

  Widget _buildNewRequestButton() {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 6),
      margin: const EdgeInsets.only(right: 8),
      decoration: BoxDecoration(
        color: AppColor.background(context),
        border: Border.all(color: AppColor.border2Color(context)),
        borderRadius: BorderRadius.circular(16),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(Icons.add, size: 20, color: AppColor.textStyleColor(context)),
          Text(
            "New Request",
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w500,
              color: AppColor.textStyleColor(context),
            ),
          ),
          4.width,
        ],
      ),
    ).onPress(() => Navigator.pushNamed(context, SiteRequestFormScreen.routeName));
  }

  Widget _buildBody() {
    if (_isLoadingData) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_provider.requestHistory.isEmpty) {
      return const NoDataFound().center;
    }

    return RefreshIndicator(
      onRefresh: _refreshData,
      child: ListView.separated(
        separatorBuilder: (context, index) => 12.height,
        controller: _scrollController,
        padding: EdgeInsets.all(16.toScreenWidth),
        itemCount: _provider.requestHistory.length + (_provider.isLoadingMore ? 1 : 0),
        itemBuilder: (context, index) {
          if (index == _provider.requestHistory.length) {
            return const ALoading();
          }

          return _buildRequestCard(_provider.requestHistory[index]);
        },
      ),
    );
  }

  Widget _buildRequestCard(SiteRequestModel request) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildRequestHeader(request),
        InfoHeaderWidget("Request No:  ${request.requestNumber ?? '-'}"),
        _buildUserInfo(request),
        // Show old sites if present (for Change Site requests)
        if (request.oldSiteNames != null && request.oldSiteNames!.isNotEmpty) _buildOldSitesSection(request),
        // Show new/current sites only if they are not empty and not all null
        if (_hasValidSiteNames(request.siteNames)) _buildSitesSection(request),
        // Show old departments if present (for Change Site requests)
        if (request.oldDepartmentNames != null && request.oldDepartmentNames!.isNotEmpty) _buildOldDepartmentsSection(request),
        // Show new departments only if they are not empty and not all null
        if (_hasValidDepartmentNames(request.departmentNames)) _buildDepartmentsSection(request),
      ],
    ).toShadowContainer(context);
  }

  // Helper method to check if site names list has valid (non-null, non-empty) values
  bool _hasValidSiteNames(List<String> siteNames) {
    return siteNames.isNotEmpty && siteNames.any((name) => name.isNotEmpty);
  }

  // Helper method to check if department names list has valid (non-null, non-empty) values
  bool _hasValidDepartmentNames(List<String>? departmentNames) {
    return departmentNames != null && departmentNames.isNotEmpty && departmentNames.any((name) => name.isNotEmpty);
  }

  Widget _buildRequestHeader(SiteRequestModel request) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        StatusLabel(
          label: request.status,
          textColor: _getStatusTextColor(request.status ?? ''),
          backgroundColor: _getStatusColor(request.status ?? ''),
        ),
        8.width,
        StatusLabel(
          label: request.requestType,
          textColor: AppColor.primary10,
          backgroundColor: AppColor.primary10.withValues(alpha: 0.1),
        ),
        1.width.expanded,
        InfoDateWidget(request.requestDate.toString()),
      ],
    );
  }

  Widget _buildUserInfo(SiteRequestModel request) {
    log('return reason: ${request.returnReason}');
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InfoTextWidget(
          label: "Full Name",
          value: request.fullName,
          showEmptyValue: true,
        ),
        InfoTextWidget(
          label: "Employee ID",
          value: request.employeeId,
          showEmptyValue: true,
        ),
        InfoTextWidget(
          label: "Email",
          value: request.emailAddress,
          showEmptyValue: true,
        ),
        InfoTextWidget(label: "Mobile", value: request.mobileNumber, showEmptyValue: true),
        InfoTextWidget(label: "Extension", value: request.extensionNumber, showEmptyValue: true),
        InfoTextWidget(
          label: "Role",
          value: request.role,
          showEmptyValue: true,
        ),
        if( request.returnReason != null && request.returnReason!.isNotEmpty)
        InfoTextWidget(
          label: "Return Reason".addTranslation,
          value: request.returnReason,
          showEmptyValue: true,
        ),
      ],
    );
  }

  Widget _buildOldSitesSection(SiteRequestModel request) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InfoTextLabelWidget(
          label: "Old Sites:",
        ),
        8.height,
        Wrap(
          runSpacing: 4.toScreenHeight,
          spacing: 4.toScreenWidth,
          children: request.oldSiteNames!.map((site) => _buildChip(site, isOld: true)).toList(),
        ),
      ],
    ).paddingOnly(bottom: 8);
  }

  Widget _buildSitesSection(SiteRequestModel request) {
    // Determine label based on whether old sites exist
    final label = (request.oldSiteNames != null && request.oldSiteNames!.isNotEmpty) ? "New Sites:" : "Sites:";

    // Filter out null or empty site names
    final validSiteNames = request.siteNames.where((site) => site.isNotEmpty).toList();

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InfoTextLabelWidget(
          label: label,
        ),
        8.height,
        Wrap(
          runSpacing: 4.toScreenHeight,
          spacing: 4.toScreenWidth,
          children: validSiteNames.map((site) => _buildChip(site)).toList(),
        ),
      ],
    );
  }

  Widget _buildOldDepartmentsSection(SiteRequestModel request) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InfoTextLabelWidget(
          label: "Old Departments:".addTranslation,
        ),
        8.height,
        Wrap(
          runSpacing: 4.toScreenHeight,
          spacing: 4.toScreenWidth,
          children: request.oldDepartmentNames!.map((dept) => _buildChip(dept, isOld: true)).toList(),
        ),
      ],
    ).paddingOnly(bottom: 8);
  }

  Widget _buildDepartmentsSection(SiteRequestModel request) {
    // Determine label based on whether old departments exist
    final label = (request.oldDepartmentNames != null && request.oldDepartmentNames!.isNotEmpty) ? "New Departments:" : "Departments:";

    // Filter out null or empty department names
    final validDepartmentNames = request.departmentNames!.where((dept) => dept.isNotEmpty).toList();

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InfoTextLabelWidget(
          label: label,
        ),
        // Text(
        //   label,
        //   style: TextStyle(
        //     fontSize: 14,
        //     color: AppColor.labelTextStyleColor(context),
        //     fontWeight: FontWeight.w500,
        //   ),
        // ),
        8.height,
        Wrap(
          runSpacing: 4.toScreenHeight,
          spacing: 4.toScreenWidth,
          children: validDepartmentNames.map((dept) => _buildChip(dept)).toList(),
        ),
      ],
    );
  }

  Widget _buildChip(String label, {bool isOld = false}) {
    return Chip(
      backgroundColor: isOld ? AppColor.redStatusColor.withValues(alpha: 0.1) : AppColor.backgroundTabBarColor(context),
      side: BorderSide(
        color: isOld ? AppColor.redStatusColor.withValues(alpha: 0.3) : AppColor.border2Color(context),
      ),
      label: Text(label),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30.0)),
      labelStyle: AppTextStyles.tinyFont2.copyWith(
        color: isOld ? AppColor.redStatusTextColor : AppColor.labelTextStyleColor(context),
      ),
      materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
      padding: EdgeInsets.symmetric(horizontal: 8.toScreenWidth, vertical: 4.toScreenHeight),
    );
  }

  Color _getStatusColor(String status) {
    switch (status.toLowerCase()) {
      case 'approved':
        return AppColor.greenStatusColor;
      case 'rejected':
        return AppColor.redStatusColor;
      case 'pending':
      default:
        return AppColor.yellowStatusColor;
    }
  }

  Color _getStatusTextColor(String status) {
    switch (status.toLowerCase()) {
      case 'approved':
        return AppColor.greenStatusTextColor;
      case 'rejected':
        return AppColor.redStatusTextColor;
      case 'pending':
      default:
        return AppColor.yellowStatusTextColor;
    }
  }
}
