import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.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 '../my_shift_card.dart';
import '../shift_assignment_card.dart';
import '../shared/empty_state_view.dart';

class MyShiftsTab extends StatefulWidget {
  final List<Shift> myShifts;
  final List<Shift> pendingAssignments;
  final List<Shift> cancelledShifts;
  final DateTime? initialDate;

  const MyShiftsTab({
    super.key,
    required this.myShifts,
    required this.pendingAssignments,
    required this.cancelledShifts,
    this.initialDate,
  });

  @override
  State<MyShiftsTab> createState() => _MyShiftsTabState();
}

class _MyShiftsTabState extends State<MyShiftsTab> {
  DateTime _selectedDate = DateTime.now();
  int _weekOffset = 0;

  @override
  void initState() {
    super.initState();
    if (widget.initialDate != null) {
      _applyInitialDate(widget.initialDate!);
    }
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadShiftsForCurrentWeek();
    });
  }

  @override
  void didUpdateWidget(MyShiftsTab oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.initialDate != null &&
        widget.initialDate != oldWidget.initialDate) {
      _applyInitialDate(widget.initialDate!);
    }
  }

  void _applyInitialDate(DateTime date) {
    _selectedDate = date;

    final now = DateTime.now();
    int reactDayIndex = now.weekday == 7 ? 0 : now.weekday;
    int daysSinceFriday = (reactDayIndex + 2) % 7;

    // Base Friday
    final baseStart = DateTime(
      now.year,
      now.month,
      now.day,
    ).subtract(Duration(days: daysSinceFriday));

    final target = DateTime(date.year, date.month, date.day);
    final diff = target.difference(baseStart).inDays;

    setState(() {
      _weekOffset = (diff / 7).floor();
    });
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadShiftsForCurrentWeek();
    });
  }

  List<DateTime> _getCalendarDays() {
    final now = DateTime.now();
    int reactDayIndex = now.weekday == 7 ? 0 : now.weekday;
    int daysSinceFriday = (reactDayIndex + 2) % 7;
    final start = now
        .subtract(Duration(days: daysSinceFriday))
        .add(Duration(days: _weekOffset * 7));
    final startDate = DateTime(start.year, start.month, start.day);
    return List.generate(7, (index) => startDate.add(Duration(days: index)));
  }

  void _loadShiftsForCurrentWeek() {
    final List<DateTime> calendarDays = _getCalendarDays();
    context.read<ShiftsBloc>().add(
          LoadShiftsForRangeEvent(
            start: calendarDays.first,
            end: calendarDays.last,
          ),
        );
  }

  bool _isSameDay(DateTime a, DateTime b) {
    return a.year == b.year && a.month == b.month && a.day == b.day;
  }

  void _confirmShift(String id) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(t.staff_shifts.my_shifts_tab.confirm_dialog.title),
        content: Text(t.staff_shifts.my_shifts_tab.confirm_dialog.message),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text(t.common.cancel),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              context.read<ShiftsBloc>().add(AcceptShiftEvent(id));
              UiSnackbar.show(
                context,
                message: t.staff_shifts.my_shifts_tab.confirm_dialog.success,
                type: UiSnackbarType.success,
              );
            },
            style: TextButton.styleFrom(
              foregroundColor: UiColors.success,
            ),
            child: Text(t.staff_shifts.shift_details.accept_shift),
          ),
        ],
      ),
    );
  }

  void _declineShift(String id) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(t.staff_shifts.my_shifts_tab.decline_dialog.title),
        content: Text(
          t.staff_shifts.my_shifts_tab.decline_dialog.message,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text(t.common.cancel),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              context.read<ShiftsBloc>().add(DeclineShiftEvent(id));
              UiSnackbar.show(
                context,
                message: t.staff_shifts.my_shifts_tab.decline_dialog.success,
                type: UiSnackbarType.error,
              );
            },
            style: TextButton.styleFrom(
              foregroundColor: UiColors.destructive,
            ),
            child: Text(t.staff_shifts.shift_details.decline),
          ),
        ],
      ),
    );
  }

  String _formatDateStr(String dateStr) {
    try {
      final date = DateTime.parse(dateStr);
      final now = DateTime.now();
      if (_isSameDay(date, now)) return t.staff_shifts.my_shifts_tab.date.today;
      final tomorrow = now.add(const Duration(days: 1));
      if (_isSameDay(date, tomorrow)) return t.staff_shifts.my_shifts_tab.date.tomorrow;
      return DateFormat('EEE, MMM d').format(date);
    } catch (_) {
      return dateStr;
    }
  }

  @override
  Widget build(BuildContext context) {
    final calendarDays = _getCalendarDays();
    final weekStartDate = calendarDays.first;
    final weekEndDate = calendarDays.last;

    final visibleMyShifts = widget.myShifts.where((s) {
      try {
        final date = DateTime.parse(s.date);
        return _isSameDay(date, _selectedDate);
      } catch (_) {
        return false;
      }
    }).toList();

    final visibleCancelledShifts = widget.cancelledShifts.where((s) {
      try {
        final date = DateTime.parse(s.date);
        return date.isAfter(
              weekStartDate.subtract(const Duration(seconds: 1)),
            ) &&
            date.isBefore(weekEndDate.add(const Duration(days: 1)));
      } catch (_) {
        return false;
      }
    }).toList();

    return Column(
      children: [
        // Calendar Selector
        Container(
          color: UiColors.white,
          padding: const EdgeInsets.symmetric(
            vertical: UiConstants.space4,
            horizontal: UiConstants.space4,
          ),
          child: Column(
            children: [
              Padding(
                padding: const EdgeInsets.only(bottom: UiConstants.space3),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    IconButton(
                      icon: const Icon(
                        UiIcons.chevronLeft,
                        size: 20,
                        color: UiColors.textPrimary,
                      ),
                      onPressed: () => setState(() {
                        _weekOffset--;
                        _selectedDate = _getCalendarDays().first;
                        _loadShiftsForCurrentWeek();
                      }),
                      constraints: const BoxConstraints(),
                      padding: EdgeInsets.zero,
                    ),
                    Text(
                      DateFormat('MMMM yyyy').format(weekStartDate),
                      style: UiTypography.title1m.textPrimary,
                    ),
                    IconButton(
                      icon: const Icon(
                        UiIcons.chevronRight,
                        size: 20,
                        color: UiColors.textPrimary,
                      ),
                      onPressed: () => setState(() {
                        _weekOffset++;
                        _selectedDate = _getCalendarDays().first;
                        _loadShiftsForCurrentWeek();
                      }),
                      constraints: const BoxConstraints(),
                      padding: EdgeInsets.zero,
                    ),
                  ],
                ),
              ),
              // Days Grid
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: calendarDays.map((date) {
                  final isSelected = _isSameDay(date, _selectedDate);
                  // ignore: unused_local_variable
                  final dateStr = DateFormat('yyyy-MM-dd').format(date);
                  final hasShifts = widget.myShifts.any((s) {
                    try {
                      return _isSameDay(DateTime.parse(s.date), date);
                    } catch (_) {
                      return false;
                    }
                  });

                  return GestureDetector(
                    onTap: () => setState(() => _selectedDate = date),
                    child: Column(
                      children: [
                        Container(
                          width: 44,
                          height: 60,
                          decoration: BoxDecoration(
                            color: isSelected
                                ? UiColors.primary
                                : UiColors.white,
                            borderRadius: BorderRadius.circular(UiConstants.radiusBase),
                            border: Border.all(
                              color: isSelected
                                  ? UiColors.primary
                                  : UiColors.border,
                              width: 1,
                            ),
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text(
                                date.day.toString().padLeft(2, '0'),
                                style: isSelected
                                    ? UiTypography.body1b.white
                                    : UiTypography.body1b.textPrimary,
                              ),
                              Text(
                                DateFormat('E').format(date),
                                style: (isSelected
                                    ? UiTypography.footnote2m.white
                                    : UiTypography.footnote2m.textSecondary).copyWith(
                                  color: isSelected ? UiColors.white.withValues(alpha: 0.8) : null,
                                ),
                              ),
                              if (hasShifts && !isSelected)
                                Container(
                                  margin: const EdgeInsets.only(top: UiConstants.space1),
                                  width: 4,
                                  height: 4,
                                  decoration: const BoxDecoration(
                                    color: UiColors.primary,
                                    shape: BoxShape.circle,
                                  ),
                                ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  );
                }).toList(),
              ),
            ],
          ),
        ),
        const Divider(height: 1, color: UiColors.border),

        Expanded(
          child: SingleChildScrollView(
            padding: const EdgeInsets.symmetric(horizontal: UiConstants.space5),
            child: Column(
              children: [
                const SizedBox(height: UiConstants.space5),
                if (widget.pendingAssignments.isNotEmpty) ...[
                  _buildSectionHeader(
                    t.staff_shifts.my_shifts_tab.sections.awaiting,
                    UiColors.textWarning,
                  ),
                  ...widget.pendingAssignments.map(
                    (shift) => Padding(
                      padding: const EdgeInsets.only(bottom: UiConstants.space4),
                      child: ShiftAssignmentCard(
                        shift: shift,
                        onConfirm: () => _confirmShift(shift.id),
                        onDecline: () => _declineShift(shift.id),
                        isConfirming: true,
                      ),
                    ),
                  ),
                  const SizedBox(height: UiConstants.space3),
                ],

                if (visibleCancelledShifts.isNotEmpty) ...[
                  _buildSectionHeader(t.staff_shifts.my_shifts_tab.sections.cancelled, UiColors.textSecondary),
                  ...visibleCancelledShifts.map(
                    (shift) => Padding(
                      padding: const EdgeInsets.only(bottom: UiConstants.space4),
                      child: _buildCancelledCard(
                        title: shift.title,
                        client: shift.clientName,
                        pay: "\$${(shift.hourlyRate * 8).toStringAsFixed(0)}",
                        rate: "\$${shift.hourlyRate}/hr · 8h",
                        date: _formatDateStr(shift.date),
                        time: "${shift.startTime} - ${shift.endTime}",
                        address: shift.locationAddress,
                        isLastMinute: true,
                        onTap: () {},
                      ),
                    ),
                  ),
                  const SizedBox(height: UiConstants.space3),
                ],

                // Confirmed Shifts
                if (visibleMyShifts.isNotEmpty) ...[
                  _buildSectionHeader(t.staff_shifts.my_shifts_tab.sections.confirmed, UiColors.textSecondary),
                  ...visibleMyShifts.map(
                    (shift) => Padding(
                      padding: const EdgeInsets.only(bottom: UiConstants.space3),
                      child: MyShiftCard(
                        shift: shift,
                        onDecline: () => _declineShift(shift.id),
                        onRequestSwap: () {
                          UiSnackbar.show(
                            context,
                            message: "Swap functionality coming soon!", // Todo: Localization
                            type: UiSnackbarType.message,
                          );
                        },
                      ),
                    ),
                  ),
                ],

                if (visibleMyShifts.isEmpty &&
                    widget.pendingAssignments.isEmpty &&
                    widget.cancelledShifts.isEmpty)
                  EmptyStateView(
                    icon: UiIcons.calendar,
                    title: t.staff_shifts.my_shifts_tab.empty.title,
                    subtitle: t.staff_shifts.my_shifts_tab.empty.subtitle,
                  ),

                const SizedBox(height: UiConstants.space32),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildSectionHeader(String title, Color dotColor) {
    return Padding(
      padding: const EdgeInsets.only(bottom: UiConstants.space4),
      child: Row(
        children: [
          Container(
            width: 8,
            height: 8,
            decoration: BoxDecoration(color: dotColor, shape: BoxShape.circle),
          ),
          const SizedBox(width: UiConstants.space2),
          Text(
            title,
            style: (dotColor == UiColors.textSecondary
                    ? UiTypography.body2b.textSecondary
                    : UiTypography.body2b.copyWith(color: dotColor)),
          ),
        ],
      ),
    );
  }

  Widget _buildCancelledCard({
    required String title,
    required String client,
    required String pay,
    required String rate,
    required String date,
    required String time,
    required String address,
    required bool isLastMinute,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.all(UiConstants.space4),
        decoration: BoxDecoration(
          color: UiColors.white,
          borderRadius: BorderRadius.circular(UiConstants.radiusBase + 4),
          border: Border.all(color: UiColors.border),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Container(
                  width: 6,
                  height: 6,
                  decoration: const BoxDecoration(
                    color: UiColors.destructive,
                    shape: BoxShape.circle,
                  ),
                ),
                const SizedBox(width: 6),
                Text(
                  t.staff_shifts.my_shifts_tab.card.cancelled,
                  style: UiTypography.footnote2b.textError,
                ),
                if (isLastMinute) ...[
                  const SizedBox(width: 4),
                  Text(
                    t.staff_shifts.my_shifts_tab.card.compensation,
                    style: UiTypography.footnote2m.textSuccess,
                  ),
                ],
              ],
            ),
            const SizedBox(height: UiConstants.space3),
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  width: 44,
                  height: 44,
                  decoration: BoxDecoration(
                    color: UiColors.primary.withValues(alpha: 0.05),
                    borderRadius: BorderRadius.circular(UiConstants.radiusBase),
                  ),
                  child: const Center(
                    child: Icon(
                      UiIcons.briefcase,
                      color: UiColors.primary,
                      size: 20,
                    ),
                  ),
                ),
                const SizedBox(width: UiConstants.space3),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  title,
                                  style: UiTypography.body2b.textPrimary,
                                ),
                                Text(
                                  client,
                                  style: UiTypography.footnote1r.textSecondary,
                                ),
                              ],
                            ),
                          ),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              Text(
                                pay,
                                style: UiTypography.headline4m.textPrimary,
                              ),
                              Text(
                                rate,
                                style: UiTypography.footnote2r.textSecondary,
                              ),
                            ],
                          ),
                        ],
                      ),
                      const SizedBox(height: UiConstants.space2),
                      Row(
                        children: [
                          const Icon(
                            UiIcons.calendar,
                            size: 12,
                            color: UiColors.textSecondary,
                          ),
                          const SizedBox(width: 4),
                          Text(
                            date,
                            style: UiTypography.footnote1r.textSecondary,
                          ),
                          const SizedBox(width: UiConstants.space3),
                          const Icon(
                            UiIcons.clock,
                            size: 12,
                            color: UiColors.textSecondary,
                          ),
                          const SizedBox(width: 4),
                          Text(
                            time,
                            style: UiTypography.footnote1r.textSecondary,
                          ),
                        ],
                      ),
                      const SizedBox(height: 4),
                      Row(
                        children: [
                          const Icon(
                            UiIcons.mapPin,
                            size: 12,
                            color: UiColors.textSecondary,
                          ),
                          const SizedBox(width: 4),
                          Expanded(
                            child: Text(
                              address,
                              style: UiTypography.footnote1r.textSecondary,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
