import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:lucide_icons/lucide_icons.dart';
import 'package:design_system/design_system.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';
import '../../styles/shifts_styles.dart';

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

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

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

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

  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)));
  }

  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: const Text('Accept Shift'),
        content: const Text(
          'Are you sure you want to accept this shift?',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              context.read<ShiftsBloc>().add(AcceptShiftEvent(id));
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('Shift confirmed!'),
                  backgroundColor: Color(0xFF10B981),
                ),
              );
            },
            style: TextButton.styleFrom(
              foregroundColor: const Color(0xFF10B981),
            ),
            child: const Text('Accept'),
          ),
        ],
      ),
    );
  }

  void _declineShift(String id) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Decline Shift'),
        content: const Text(
          'Are you sure you want to decline this shift? This action cannot be undone.',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              context.read<ShiftsBloc>().add(DeclineShiftEvent(id));
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('Shift declined.'),
                  backgroundColor: Color(0xFFEF4444),
                ),
              );
            },
            style: TextButton.styleFrom(
              foregroundColor: const Color(0xFFEF4444),
            ),
            child: const Text('Decline'),
          ),
        ],
      ),
    );
  }

  String _formatDateStr(String dateStr) {
    try {
      final date = DateTime.parse(dateStr);
      final now = DateTime.now();
      if (_isSameDay(date, now)) return "Today";
      final tomorrow = now.add(const Duration(days: 1));
      if (_isSameDay(date, tomorrow)) return "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 date.isAfter(
              weekStartDate.subtract(const Duration(seconds: 1)),
            ) &&
            date.isBefore(weekEndDate.add(const Duration(days: 1)));
      } 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: Colors.white,
          padding: const EdgeInsets.symmetric(
            vertical: 16,
            horizontal: 16,
          ),
          child: Column(
            children: [
              Padding(
                padding: const EdgeInsets.only(bottom: 12),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    IconButton(
                      icon: const Icon(
                        UiIcons.chevronLeft,
                        size: 20,
                        color: AppColors.krowCharcoal,
                      ),
                      onPressed: () => setState(() => _weekOffset--),
                      constraints: const BoxConstraints(),
                      padding: EdgeInsets.zero,
                    ),
                    Text(
                      DateFormat('MMMM yyyy').format(weekStartDate),
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                        color: AppColors.krowCharcoal,
                      ),
                    ),
                    IconButton(
                      icon: const Icon(
                        UiIcons.chevronRight,
                        size: 20,
                        color: AppColors.krowCharcoal,
                      ),
                      onPressed: () => setState(() => _weekOffset++),
                      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 ? AppColors.krowBlue : Colors.white,
                            borderRadius: BorderRadius.circular(12),
                            border: Border.all(
                              color: isSelected
                                  ? AppColors.krowBlue
                                  : AppColors.krowBorder,
                              width: 1,
                            ),
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text(
                                date.day.toString().padLeft(2, '0'),
                                style: TextStyle(
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold,
                                  color: isSelected
                                      ? Colors.white
                                      : AppColors.krowCharcoal,
                                ),
                              ),
                              Text(
                                DateFormat('E').format(date),
                                style: TextStyle(
                                  fontSize: 10,
                                  fontWeight: FontWeight.w500,
                                  color: isSelected
                                      ? Colors.white.withOpacity(0.8)
                                      : AppColors.krowMuted,
                                ),
                              ),
                              if (hasShifts && !isSelected)
                                Container(
                                  margin: const EdgeInsets.only(top: 4),
                                  width: 4,
                                  height: 4,
                                  decoration: const BoxDecoration(
                                    color: AppColors.krowBlue,
                                    shape: BoxShape.circle,
                                  ),
                                ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  );
                }).toList(),
              ),
            ],
          ),
        ),
        const Divider(height: 1, color: AppColors.krowBorder),

        Expanded(
          child: SingleChildScrollView(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: Column(
              children: [
                const SizedBox(height: 20),
                if (widget.pendingAssignments.isNotEmpty) ...[
                  _buildSectionHeader(
                    "Awaiting Confirmation",
                    const Color(0xFFF59E0B),
                  ),
                  ...widget.pendingAssignments.map(
                    (shift) => Padding(
                      padding: const EdgeInsets.only(bottom: 16),
                      child: ShiftAssignmentCard(
                        shift: shift,
                        onConfirm: () => _confirmShift(shift.id),
                        onDecline: () => _declineShift(shift.id),
                        isConfirming: true,
                      ),
                    ),
                  ),
                  const SizedBox(height: 12),
                ],

                if (visibleCancelledShifts.isNotEmpty) ...[
                  _buildSectionHeader(
                    "Cancelled Shifts",
                    AppColors.krowMuted,
                  ),
                  ...visibleCancelledShifts.map(
                    (shift) => Padding(
                      padding: const EdgeInsets.only(bottom: 16),
                      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: 12),
                ],

                // Confirmed Shifts
                if (visibleMyShifts.isNotEmpty) ...[
                  _buildSectionHeader(
                    "Confirmed Shifts",
                    AppColors.krowMuted,
                  ),
                  ...visibleMyShifts.map(
                    (shift) => Padding(
                      padding: const EdgeInsets.only(bottom: 12),
                      child: MyShiftCard(shift: shift),
                    ),
                  ),
                ],

                if (visibleMyShifts.isEmpty &&
                    widget.pendingAssignments.isEmpty &&
                    widget.cancelledShifts.isEmpty)
                  const EmptyStateView(
                    icon: UiIcons.calendar,
                    title: "No shifts this week",
                    subtitle: "Try finding new jobs in the Find tab",
                  ),
                
                 const SizedBox(height: 40),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildSectionHeader(String title, Color dotColor) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16),
      child: Row(
        children: [
          Container(
            width: 8,
            height: 8,
            decoration: BoxDecoration(color: dotColor, shape: BoxShape.circle),
          ),
          const SizedBox(width: 8),
          Text(
            title,
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w600,
              color: dotColor == AppColors.krowMuted
                  ? AppColors.krowMuted
                  : 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(16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: AppColors.krowBorder),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Container(
                  width: 6,
                  height: 6,
                  decoration: const BoxDecoration(
                    color: Color(0xFFEF4444),
                    shape: BoxShape.circle,
                  ),
                ),
                const SizedBox(width: 6),
                const Text(
                  "CANCELLED",
                  style: TextStyle(
                    fontSize: 10,
                    fontWeight: FontWeight.bold,
                    color: Color(0xFFEF4444),
                  ),
                ),
                if (isLastMinute) ...[
                  const SizedBox(width: 4),
                  const Text(
                    "• 4hr compensation",
                    style: TextStyle(
                      fontSize: 10,
                      fontWeight: FontWeight.w500,
                      color: Color(0xFF10B981),
                    ),
                  ),
                ],
              ],
            ),
            const SizedBox(height: 12),
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  width: 44,
                  height: 44,
                  decoration: BoxDecoration(
                    color: AppColors.krowBlue.withOpacity(0.05),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: const Center(
                    child: Icon(
                      LucideIcons.briefcase,
                      color: AppColors.krowBlue,
                      size: 20,
                    ),
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  title,
                                  style: const TextStyle(
                                    fontSize: 14,
                                    fontWeight: FontWeight.w600,
                                    color: AppColors.krowCharcoal,
                                  ),
                                ),
                                Text(
                                  client,
                                  style: const TextStyle(
                                    fontSize: 12,
                                    color: AppColors.krowMuted,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              Text(
                                pay,
                                style: const TextStyle(
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold,
                                  color: AppColors.krowCharcoal,
                                ),
                              ),
                              Text(
                                rate,
                                style: const TextStyle(
                                  fontSize: 10,
                                  color: AppColors.krowMuted,
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                      const SizedBox(height: 8),
                      Row(
                        children: [
                          const Icon(
                            LucideIcons.calendar,
                            size: 12,
                            color: AppColors.krowMuted,
                          ),
                          const SizedBox(width: 4),
                          Text(
                            date,
                            style: const TextStyle(
                              fontSize: 12,
                              color: AppColors.krowMuted,
                            ),
                          ),
                          const SizedBox(width: 12),
                          const Icon(
                            LucideIcons.clock,
                            size: 12,
                            color: AppColors.krowMuted,
                          ),
                          const SizedBox(width: 4),
                          Text(
                            time,
                            style: const TextStyle(
                              fontSize: 12,
                              color: AppColors.krowMuted,
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 4),
                      Row(
                        children: [
                          const Icon(
                            LucideIcons.mapPin,
                            size: 12,
                            color: AppColors.krowMuted,
                          ),
                          const SizedBox(width: 4),
                          Expanded(
                            child: Text(
                              address,
                              style: const TextStyle(
                                fontSize: 12,
                                color: AppColors.krowMuted,
                              ),
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
