import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:design_system/design_system.dart';
import 'package:krow_domain/krow_domain.dart';
import '../blocs/shifts/shifts_bloc.dart';
import '../widgets/tabs/my_shifts_tab.dart';
import '../widgets/tabs/find_shifts_tab.dart';
import '../widgets/tabs/history_shifts_tab.dart';
import '../styles/shifts_styles.dart';

class ShiftsPage extends StatefulWidget {
  final String? initialTab;
  const ShiftsPage({super.key, this.initialTab});

  @override
  State<ShiftsPage> createState() => _ShiftsPageState();
}

class _ShiftsPageState extends State<ShiftsPage> {
  late String _activeTab;
  final ShiftsBloc _bloc = Modular.get<ShiftsBloc>();

  @override
  void initState() {
    super.initState();
    _activeTab = widget.initialTab ?? 'myshifts';
    _bloc.add(LoadShiftsEvent());
  }

  @override
  void didUpdateWidget(ShiftsPage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.initialTab != null && widget.initialTab != _activeTab) {
      setState(() {
        _activeTab = widget.initialTab!;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider.value(
      value: _bloc,
      child: BlocBuilder<ShiftsBloc, ShiftsState>(
        builder: (context, state) {
          final List<Shift> myShifts = (state is ShiftsLoaded)
              ? state.myShifts
              : [];
          final List<Shift> availableJobs = (state is ShiftsLoaded)
              ? state.availableShifts
              : [];
          final List<Shift> pendingAssignments = (state is ShiftsLoaded)
              ? state.pendingShifts
              : [];
          final List<Shift> cancelledShifts = (state is ShiftsLoaded)
              ? state.cancelledShifts
              : [];
          final List<Shift> historyShifts = (state is ShiftsLoaded)
              ? state.historyShifts
              : [];

          // Note: "filteredJobs" logic moved to FindShiftsTab
          // Note: Calendar logic moved to MyShiftsTab

          return Scaffold(
            backgroundColor: AppColors.krowBackground,
            body: Column(
              children: [
                // Header (Blue)
                Container(
                  color: AppColors.krowBlue,
                  padding: EdgeInsets.fromLTRB(
                    20,
                    MediaQuery.of(context).padding.top + 10,
                    20,
                    20,
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    spacing: 16,
                    children: [
                      const Text(
                        "Shifts",
                        style: TextStyle(
                          fontSize: 24,
                          fontWeight: FontWeight.bold,
                          color: Colors.white,
                        ),
                      ),

                      // Tabs
                      Row(
                        children: [
                          _buildTab(
                            "myshifts",
                            "My Shifts",
                            UiIcons.calendar,
                            myShifts.length,
                          ),
                          const SizedBox(width: 8),
                          _buildTab(
                            "find",
                            "Find Shifts",
                            UiIcons.search,
                            availableJobs.length, // Passed unfiltered count as badge? Or logic inside? Pass availableJobs.
                          ),
                          const SizedBox(width: 8),
                          _buildTab(
                            "history",
                            "History",
                            UiIcons.clock,
                            historyShifts.length,
                          ),
                        ],
                      ),
                    ],
                  ),
                ),

                // Body Content
                Expanded(
                  child: state is ShiftsLoading
                      ? const Center(child: CircularProgressIndicator())
                      : _buildTabContent(
                          myShifts,
                          pendingAssignments,
                          cancelledShifts,
                          availableJobs,
                          historyShifts,
                        ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildTabContent(
    List<Shift> myShifts,
    List<Shift> pendingAssignments,
    List<Shift> cancelledShifts,
    List<Shift> availableJobs,
    List<Shift> historyShifts,
  ) {
    switch (_activeTab) {
      case 'myshifts':
        return MyShiftsTab(
          myShifts: myShifts,
          pendingAssignments: pendingAssignments,
          cancelledShifts: cancelledShifts,
        );
      case 'find':
        return FindShiftsTab(
          availableJobs: availableJobs,
        );
      case 'history':
        return HistoryShiftsTab(
          historyShifts: historyShifts,
        );
      default:
        return const SizedBox.shrink();
    }
  }

  Widget _buildTab(String id, String label, IconData icon, int count) {
    final isActive = _activeTab == id;
    return Expanded(
      child: GestureDetector(
        onTap: () => setState(() => _activeTab = id),
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 8),
          decoration: BoxDecoration(
            color: isActive
                ? Colors.white
                : Colors.white.withAlpha((0.2 * 255).round()),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                icon,
                size: 14,
                color: isActive ? AppColors.krowBlue : Colors.white,
              ),
              const SizedBox(width: 6),
              Flexible(
                child: Text(
                  label,
                  style: TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w500,
                    color: isActive ? AppColors.krowBlue : Colors.white,
                  ),
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              const SizedBox(width: 4),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                constraints: const BoxConstraints(minWidth: 18),
                decoration: BoxDecoration(
                  color: isActive
                      ? AppColors.krowBlue.withAlpha((0.1 * 255).round())
                      : Colors.white.withAlpha((0.2 * 255).round()),
                  borderRadius: BorderRadius.circular(999),
                ),
                child: Center(
                  child: Text(
                    "$count",
                    style: TextStyle(
                      fontSize: 10,
                      fontWeight: FontWeight.bold,
                      color: isActive ? AppColors.krowBlue : Colors.white,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
