import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:intl/intl.dart';
import 'package:krow_domain/krow_domain.dart';
import 'package:design_system/design_system.dart';
import 'package:core_localization/core_localization.dart';
import 'package:krow_core/core.dart'; // For modular navigation

class MyShiftCard extends StatefulWidget {
  final Shift shift;
  final bool historyMode;
  final VoidCallback? onAccept;
  final VoidCallback? onDecline;
  final VoidCallback? onRequestSwap;

  const MyShiftCard({
    super.key,
    required this.shift,
    this.historyMode = false,
    this.onAccept,
    this.onDecline,
    this.onRequestSwap,
  });

  @override
  State<MyShiftCard> createState() => _MyShiftCardState();
}

class _MyShiftCardState extends State<MyShiftCard> {

  String _formatTime(String time) {
    if (time.isEmpty) return '';
    try {
      final parts = time.split(':');
      final hour = int.parse(parts[0]);
      final minute = int.parse(parts[1]);
      // Date doesn't matter for time formatting
      final dt = DateTime(2022, 1, 1, hour, minute);
      return DateFormat('h:mm a').format(dt);
    } catch (e) {
      return time;
    }
  }

  String _formatDate(String dateStr) {
    if (dateStr.isEmpty) return '';
    try {
      final date = DateTime.parse(dateStr);
      final now = DateTime.now();
      final today = DateTime(now.year, now.month, now.day);
      final tomorrow = today.add(const Duration(days: 1));
      final d = DateTime(date.year, date.month, date.day);

      if (d == today) return 'Today';
      if (d == tomorrow) return 'Tomorrow';
      return DateFormat('EEE, MMM d').format(date);
    } catch (e) {
      return dateStr;
    }
  }

  double _calculateDuration() {
    if (widget.shift.startTime.isEmpty || widget.shift.endTime.isEmpty) {
      return 0;
    }
    try {
      final s = widget.shift.startTime.split(':').map(int.parse).toList();
      final e = widget.shift.endTime.split(':').map(int.parse).toList();
      double hours = ((e[0] * 60 + e[1]) - (s[0] * 60 + s[1])) / 60;
      if (hours < 0) hours += 24;
      return hours.roundToDouble();
    } catch (_) {
      return 0;
    }
  }

  String _getShiftType() {
    // Handling potential localization key availability
    try {
        if (widget.shift.durationDays != null && widget.shift.durationDays! > 30) {
          return t.staff_shifts.filter.long_term;
        }
        if (widget.shift.durationDays != null && widget.shift.durationDays! > 1) {
          return t.staff_shifts.filter.multi_day;
        }
        return t.staff_shifts.filter.one_day;
    } catch (_) {
        return "One Day";
    }
  }

  @override
  Widget build(BuildContext context) {
    final duration = _calculateDuration();
    final estimatedTotal = (widget.shift.hourlyRate) * duration;

    // Status Logic
    String? status = widget.shift.status;
    Color statusColor = UiColors.primary;
    Color statusBg = UiColors.primary;
    String statusText = '';
    IconData? statusIcon;

    // Fallback localization if keys missing
    try {
        if (status == 'confirmed') {
          statusText = t.staff_shifts.status.confirmed;
          statusColor = UiColors.textLink;
          statusBg = UiColors.primary;
        } else if (status == 'checked_in') {
          statusText = 'Checked in';
          statusColor = UiColors.textSuccess;
          statusBg = UiColors.iconSuccess;
        } else if (status == 'pending' || status == 'open') {
          statusText = t.staff_shifts.status.act_now;
          statusColor = UiColors.destructive;
          statusBg = UiColors.destructive;
        } else if (status == 'swap') {
          statusText = t.staff_shifts.status.swap_requested;
          statusColor = UiColors.textWarning;
          statusBg = UiColors.textWarning;
          statusIcon = UiIcons.swap;
        } else if (status == 'completed') {
          statusText = t.staff_shifts.status.completed;
          statusColor = UiColors.textSuccess;
          statusBg = UiColors.iconSuccess;
        } else if (status == 'no_show') {
          statusText = t.staff_shifts.status.no_show;
          statusColor = UiColors.destructive;
          statusBg = UiColors.destructive;
        }
    } catch (_) {
        statusText = status?.toUpperCase() ?? "";
    }

    return GestureDetector(
      onTap: () {
        Modular.to.pushNamed(
          StaffPaths.shiftDetails(widget.shift.id),
          arguments: widget.shift,
        );
      },
      child: Container(
        margin: const EdgeInsets.only(bottom: UiConstants.space3),
        decoration: BoxDecoration(
          color: UiColors.white,
          borderRadius: UiConstants.radiusLg,
          border: Border.all(color: UiColors.border),
          boxShadow: [
            BoxShadow(
              color: UiColors.black.withValues(alpha: 0.05),
              blurRadius: 2,
              offset: const Offset(0, 1),
            ),
          ],
        ),
        child: Padding(
          padding: const EdgeInsets.all(UiConstants.space4),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Status Badge
              if (statusText.isNotEmpty)
                Padding(
                  padding: const EdgeInsets.only(bottom: UiConstants.space2),
                  child: Row(
                    children: [
                      if (statusIcon != null)
                        Padding(
                          padding: const EdgeInsets.only(right: UiConstants.space2),
                          child: Icon(
                            statusIcon,
                            size: UiConstants.iconXs,
                            color: statusColor,
                          ),
                        )
                      else
                        Container(
                          width: 8,
                          height: 8,
                          margin: const EdgeInsets.only(right: UiConstants.space2),
                          decoration: BoxDecoration(
                            color: statusBg,
                            shape: BoxShape.circle,
                          ),
                        ),
                      Text(
                        statusText,
                        style: UiTypography.footnote2b.copyWith(
                          color: statusColor,
                          letterSpacing: 0.5,
                        ),
                      ),
                      // Shift Type Badge
                      if (status == 'open' || status == 'pending') ...[
                        const SizedBox(width: UiConstants.space2),
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: UiConstants.space2,
                            vertical: 2,
                          ),
                          decoration: BoxDecoration(
                            color: UiColors.primary.withValues(alpha: 0.1),
                            borderRadius: UiConstants.radiusSm,
                          ),
                          child: Text(
                            _getShiftType(),
                            style: UiTypography.footnote2m.copyWith(
                              color: UiColors.primary,
                            ),
                          ),
                        ),
                      ],
                    ],
                  ),
                ),

              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Logo
                  Container(
                    width: 44,
                    height: 44,
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [
                          UiColors.primary.withValues(alpha: 0.09),
                          UiColors.primary.withValues(alpha: 0.03),
                        ],
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                      ),
                      borderRadius: BorderRadius.circular(UiConstants.radiusBase),
                      border: Border.all(
                        color: UiColors.primary.withValues(alpha: 0.09),
                      ),
                    ),
                    child: widget.shift.logoUrl != null
                        ? ClipRRect(
                            borderRadius: BorderRadius.circular(UiConstants.radiusBase),
                            child: Image.network(
                              widget.shift.logoUrl!,
                              fit: BoxFit.contain,
                            ),
                          )
                        : const Center(
                            child: Icon(
                              UiIcons.briefcase,
                              color: UiColors.primary,
                              size: UiConstants.iconMd,
                            ),
                          ),
                  ),
                  const SizedBox(width: UiConstants.space3),

                  // Consensed Details
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Expanded(
                              child: Column(
                                crossAxisAlignment:
                                    CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    widget.shift.title,
                                    style: UiTypography.body2m.textPrimary,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                  Text(
                                    widget.shift.clientName,
                                    style: UiTypography.body3r.textSecondary,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ],
                              ),
                            ),
                            const SizedBox(width: UiConstants.space2),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: [
                                Text(
                                  "\$${estimatedTotal.toStringAsFixed(0)}",
                                  style: UiTypography.title1m.textPrimary,
                                ),
                                Text(
                                  "\$${widget.shift.hourlyRate.toInt()}/hr · ${duration.toInt()}h",
                                  style: UiTypography.footnote2r.textSecondary,
                                ),
                              ],
                            ),
                          ],
                        ),
                        const SizedBox(height: UiConstants.space2),

                        // Date & Time
                        if (widget.shift.durationDays != null &&
                            widget.shift.durationDays! > 1) ...[
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  const Icon(
                                    UiIcons.clock,
                                    size: UiConstants.iconXs,
                                    color: UiColors.primary,
                                  ),
                                  const SizedBox(width: UiConstants.space1),
                                  Text(
                                    t.staff_shifts.details.days(
                                      days: widget.shift.durationDays!,
                                    ),
                                    style: UiTypography.footnote2m.copyWith(
                                      color: UiColors.primary,
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: UiConstants.space1),
                              Padding(
                                  padding: const EdgeInsets.only(bottom: 2),
                                  child: Text(
                                      '${_formatDate(widget.shift.date)}, ${_formatTime(widget.shift.startTime)} – ${_formatTime(widget.shift.endTime)}',
                                      style: UiTypography.footnote2r.copyWith(color: UiColors.primary),
                                  ),
                              ),
                              if (widget.shift.durationDays! > 1)
                                  Text(
                                      '... +${widget.shift.durationDays! - 1} more days',
                                      style: UiTypography.footnote2r.copyWith(color: UiColors.primary.withOpacity(0.7)),
                                  )
                            ],
                          ),
                        ] else ...[
                          Row(
                            children: [
                              const Icon(
                                UiIcons.calendar,
                                size: UiConstants.iconXs,
                                color: UiColors.iconSecondary,
                              ),
                              const SizedBox(width: UiConstants.space1),
                              Text(
                                _formatDate(widget.shift.date),
                                style: UiTypography.footnote1r.textSecondary,
                              ),
                              const SizedBox(width: UiConstants.space3),
                              const Icon(
                                UiIcons.clock,
                                size: UiConstants.iconXs,
                                color: UiColors.iconSecondary,
                              ),
                              const SizedBox(width: UiConstants.space1),
                              Text(
                                "${_formatTime(widget.shift.startTime)} - ${_formatTime(widget.shift.endTime)}",
                                style: UiTypography.footnote1r.textSecondary,
                              ),
                            ],
                          ),
                        ],
                        const SizedBox(height: UiConstants.space1),

                        // Location
                        Row(
                          children: [
                            const Icon(
                              UiIcons.mapPin,
                              size: UiConstants.iconXs,
                              color: UiColors.iconSecondary,
                            ),
                            const SizedBox(width: UiConstants.space1),
                            Expanded(
                              child: Text(
                                widget.shift.locationAddress.isNotEmpty
                                    ? widget.shift.locationAddress
                                    : widget.shift.location,
                                style: UiTypography.footnote1r.textSecondary,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
