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:core_localization/core_localization.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';

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

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

class _ShiftsPageState extends State<ShiftsPage> {
  late String _activeTab;
  DateTime? _selectedDate;
  bool _prioritizeFind = false;
  final ShiftsBloc _bloc = Modular.get<ShiftsBloc>();

  @override
  void initState() {
    super.initState();
    _activeTab = widget.initialTab ?? 'myshifts';
    _selectedDate = widget.selectedDate;
    _prioritizeFind = widget.initialTab == 'find';
    if (_prioritizeFind) {
      _bloc.add(LoadFindFirstEvent());
    } else {
      _bloc.add(LoadShiftsEvent());
    }
    if (_activeTab == 'history') {
      _bloc.add(LoadHistoryShiftsEvent());
    }
    if (_activeTab == 'find') {
      if (!_prioritizeFind) {
        _bloc.add(LoadAvailableShiftsEvent());
      }
    }
  }

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

  @override
  Widget build(BuildContext context) {
    final t = Translations.of(context);
    return BlocProvider.value(
      value: _bloc,
      child: BlocConsumer<ShiftsBloc, ShiftsState>(
        listener: (context, state) {
          if (state is ShiftsError) {
            UiSnackbar.show(
              context,
              message: translateErrorKey(state.message),
              type: UiSnackbarType.error,
            );
          }
        },
        builder: (context, state) {
          final bool baseLoaded = state is ShiftsLoaded;
          final List<Shift> myShifts = (state is ShiftsLoaded)
              ? state.myShifts
              : [];
          final List<Shift> availableJobs = (state is ShiftsLoaded)
              ? state.availableShifts
              : [];
          final bool availableLoading = (state is ShiftsLoaded)
              ? state.availableLoading
              : false;
          final bool availableLoaded = (state is ShiftsLoaded)
              ? state.availableLoaded
              : false;
          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
              : [];
          final bool historyLoading = (state is ShiftsLoaded)
              ? state.historyLoading
              : false;
          final bool historyLoaded = (state is ShiftsLoaded)
              ? state.historyLoaded
              : false;
          final bool myShiftsLoaded = (state is ShiftsLoaded)
              ? state.myShiftsLoaded
              : false;
          final bool blockTabsForFind = _prioritizeFind && !availableLoaded;

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

          return Scaffold(
            backgroundColor: UiColors.background,
            body: Column(
              children: [
                // Header (Blue)
                Container(
                  color: UiColors.primary,
                  padding: EdgeInsets.fromLTRB(
                    UiConstants.space5,
                    MediaQuery.of(context).padding.top + UiConstants.space2,
                    UiConstants.space5,
                    UiConstants.space5,
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    spacing: UiConstants.space4,
                    children: [
                      Text(
                        t.staff_shifts.title,
                        style: UiTypography.display1b.white,
                      ),

                      // Tabs
                      Row(
                        children: [
                          _buildTab(
                            "myshifts",
                            t.staff_shifts.tabs.my_shifts,
                            UiIcons.calendar,
                            myShifts.length,
                            showCount: myShiftsLoaded,
                            enabled: !blockTabsForFind,
                          ),
                          const SizedBox(width: UiConstants.space2),
                          _buildTab(
                            "find",
                            t.staff_shifts.tabs.find_work,
                            UiIcons.search,
                            availableJobs.length,
                            showCount: availableLoaded,
                            enabled: baseLoaded,
                          ),
                          const SizedBox(width: UiConstants.space2),
                          _buildTab(
                            "history",
                            t.staff_shifts.tabs.history,
                            UiIcons.clock,
                            historyShifts.length,
                            showCount: historyLoaded,
                            enabled: !blockTabsForFind && baseLoaded,
                          ),
                        ],
                      ),
                    ],
                  ),
                ),

                // Body Content
                Expanded(
                  child: state is ShiftsLoading
                      ? const Center(child: CircularProgressIndicator())
                      : state is ShiftsError
                          ? Center(
                              child: Padding(
                                padding: const EdgeInsets.all(UiConstants.space5),
                                child: Column(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Text(
                                      translateErrorKey(state.message),
                                      style: UiTypography.body2r.textSecondary,
                                      textAlign: TextAlign.center,
                                    ),
                                  ],
                                ),
                              ),
                            )
                          : _buildTabContent(
                          myShifts,
                        pendingAssignments,
                        cancelledShifts,
                        availableJobs,
                        historyShifts,
                        availableLoading,
                        historyLoading,
                      ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildTabContent(
    List<Shift> myShifts,
    List<Shift> pendingAssignments,
    List<Shift> cancelledShifts,
    List<Shift> availableJobs,
    List<Shift> historyShifts,
    bool availableLoading,
    bool historyLoading,
  ) {
    switch (_activeTab) {
      case 'myshifts':
        return MyShiftsTab(
          myShifts: myShifts,
          pendingAssignments: pendingAssignments,
          cancelledShifts: cancelledShifts,
          initialDate: _selectedDate,
        );
      case 'find':
        if (availableLoading) {
          return const Center(child: CircularProgressIndicator());
        }
        return FindShiftsTab(availableJobs: availableJobs);
      case 'history':
        if (historyLoading) {
          return const Center(child: CircularProgressIndicator());
        }
        return HistoryShiftsTab(historyShifts: historyShifts);
      default:
        return const SizedBox.shrink();
    }
  }

  Widget _buildTab(
    String id,
    String label,
    IconData icon,
    int count, {
    bool showCount = true,
    bool enabled = true,
  }) {
    final isActive = _activeTab == id;
    return Expanded(
      child: GestureDetector(
        onTap: !enabled
            ? null
            : () {
          setState(() => _activeTab = id);
          if (id == 'history') {
            _bloc.add(LoadHistoryShiftsEvent());
          }
          if (id == 'find') {
            _bloc.add(LoadAvailableShiftsEvent());
          }
        },
        child: Container(
          padding: const EdgeInsets.symmetric(
            vertical: UiConstants.space2,
            horizontal: UiConstants.space2,
          ),
          decoration: BoxDecoration(
            color: isActive
                ? UiColors.white
                : UiColors.white.withValues(alpha: 0.2),
            borderRadius: BorderRadius.circular(UiConstants.radiusMdValue),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                icon,
                size: 14,
                color: !enabled
                    ? UiColors.white.withValues(alpha: 0.5)
                    : isActive
                    ? UiColors.primary
                    : UiColors.white,
              ),
              const SizedBox(width: UiConstants.space1),
              Flexible(
                child: Text(
                  label,
                  style: (isActive ? UiTypography.body3m.copyWith(color: UiColors.primary) : UiTypography.body3m.white).copyWith(
                    color: !enabled ? UiColors.white.withValues(alpha: 0.5) : null,
                  ),
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              if (showCount) ...[
                const SizedBox(width: 4),
                Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: UiConstants.space1,
                    vertical: 2,
                  ),
                  constraints: const BoxConstraints(minWidth: 18),
                  decoration: BoxDecoration(
                    color: isActive
                        ? UiColors.primary.withValues(alpha: 0.1)
                        : UiColors.white.withValues(alpha: 0.2),
                    borderRadius: UiConstants.radiusFull,
                  ),
                  child: Center(
                    child: Text(
                      "$count",
                      style: UiTypography.footnote1b.copyWith(
                        color: isActive ? UiColors.primary : UiColors.white,
                      ),
                    ),
                  ),
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }
}
