import 'package:core_localization/core_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';

import 'package:intl/intl.dart';

import 'package:design_system/design_system.dart';
import 'package:krow_domain/krow_domain.dart';
import 'package:krow_core/core.dart';

class ShiftCard extends StatefulWidget {
  final Shift shift;
  final VoidCallback? onApply;
  final VoidCallback? onDecline;
  final bool compact;
  final bool disableTapNavigation; // Added property

  const ShiftCard({
    super.key,
    required this.shift,
    this.onApply,
    this.onDecline,
    this.compact = false,
    this.disableTapNavigation = false,
  });

  @override
  State<ShiftCard> createState() => _ShiftCardState();
}

class _ShiftCardState extends State<ShiftCard> {
  bool isExpanded = false;

  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]);
      final dt = DateTime(2022, 1, 1, hour, minute);
      return DateFormat('h:mma').format(dt).toLowerCase();
    } catch (e) {
      return time;
    }
  }

  String _formatDate(String dateStr) {
    if (dateStr.isEmpty) return '';
    try {
      final date = DateTime.parse(dateStr);
      return DateFormat('MMMM d').format(date);
    } catch (e) {
      return dateStr;
    }
  }

  String _getTimeAgo(String dateStr) {
    if (dateStr.isEmpty) return '';
    try {
      final date = DateTime.parse(dateStr);
      final diff = DateTime.now().difference(date);
      if (diff.inHours < 1) return t.staff_shifts.card.just_now;
      if (diff.inHours < 24) return t.staff_shifts.details.pending_time(time: '${diff.inHours}h');
      return t.staff_shifts.details.pending_time(time: '${diff.inDays}d');
    } catch (e) {
      return '';
    }
  }

  @override
  Widget build(BuildContext context) {
    if (widget.compact) {
      return GestureDetector(
        onTap: widget.disableTapNavigation
            ? null
            : () {
                setState(() => isExpanded = !isExpanded);
                Modular.to.pushShiftDetails(widget.shift);
              },
        child: Container(
          margin: const EdgeInsets.only(bottom: UiConstants.space3),
          padding: const EdgeInsets.all(UiConstants.space4),
          decoration: BoxDecoration(
            color: UiColors.white,
            borderRadius: BorderRadius.circular(UiConstants.radiusBase),
            border: Border.all(color: UiColors.border),
          ),
          child: Row(
            children: [
              Container(
                width: UiConstants.space12,
                height: UiConstants.space12,
                decoration: BoxDecoration(
                  color: UiColors.white,
                  borderRadius: BorderRadius.circular(UiConstants.radiusBase),
                  border: Border.all(color: UiColors.border),
                ),
                child: widget.shift.logoUrl != null
                    ? ClipRRect(
                        borderRadius:
                            BorderRadius.circular(UiConstants.radiusBase),
                        child: Image.network(
                          widget.shift.logoUrl!,
                          fit: BoxFit.contain,
                        ),
                      )
                    : Icon(
                        UiIcons.building,
                        color: UiColors.mutedForeground,
                      ),
              ),
              const SizedBox(width: UiConstants.space3),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Flexible(
                          child: Text(
                            widget.shift.title,
                            style: UiTypography.body1m.textPrimary,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        Text.rich(
                          TextSpan(
                            text: '\$${widget.shift.hourlyRate}',
                            style: UiTypography.body1b.textPrimary,
                            children: [
                              TextSpan(
                                text: '/h',
                                style: UiTypography.body3r,
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                    Text(
                      widget.shift.clientName,
                      style: UiTypography.body2r.textSecondary,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: UiConstants.space1),
                    Text(
                      '${_formatTime(widget.shift.startTime)} • ${widget.shift.location}',
                      style: UiTypography.body3r.textSecondary,
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      );
    }

    return Container(
      margin: const EdgeInsets.only(bottom: UiConstants.space4),
      decoration: BoxDecoration(
        color: UiColors.white,
        borderRadius: BorderRadius.circular(UiConstants.radiusBase),
        border: Border.all(color: UiColors.border),
        boxShadow: [
          BoxShadow(
            color: UiColors.black.withValues(alpha: 0.05),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(UiConstants.space5),
            child: Column(
              children: [
                // Header
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      width: UiConstants.space14,
                      height: UiConstants.space14,
                      decoration: BoxDecoration(
                        color: UiColors.white,
                        borderRadius: BorderRadius.circular(UiConstants.radiusBase),
                        border: Border.all(color: UiColors.border),
                      ),
                      child: widget.shift.logoUrl != null
                          ? ClipRRect(
                              borderRadius:
                                  BorderRadius.circular(UiConstants.radiusBase),
                              child: Image.network(
                                widget.shift.logoUrl!,
                                fit: BoxFit.contain,
                              ),
                            )
                          : Icon(
                              UiIcons.building,
                              size: UiConstants.iconXl - 4, // 28px
                              color: UiColors.primary,
                            ),
                    ),
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: UiConstants.space4,
                        vertical: 6,
                      ),
                      decoration: BoxDecoration(
                        color: UiColors.primary,
                        borderRadius: UiConstants.radiusFull,
                      ),
                      child: Text(
                        t.staff_shifts.card.assigned(
                          time: _getTimeAgo(widget.shift.createdDate)
                              .replaceAll('Pending ', '')
                              .replaceAll('Just now', 'just now'),
                        ),
                        style: UiTypography.body3m.white,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: UiConstants.space4),

                // Title and Rate
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            widget.shift.title,
                            style: UiTypography.headline3m.textPrimary,
                          ),
                          Text(
                            widget.shift.clientName,
                            style: UiTypography.body2r.textSecondary,
                          ),
                        ],
                      ),
                    ),
                    Text.rich(
                      TextSpan(
                        text: '\$${widget.shift.hourlyRate}',
                        style: UiTypography.headline3m.textPrimary,
                        children: [
                          TextSpan(
                            text: '/h',
                            style: UiTypography.body1r,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: UiConstants.space4),

                // Location and Date
                Row(
                  children: [
                    Icon(
                      UiIcons.mapPin,
                      size: UiConstants.iconSm,
                      color: UiColors.mutedForeground,
                    ),
                    const SizedBox(width: 6),
                    Expanded(
                      child: Text(
                        widget.shift.location,
                        style: UiTypography.body2r.textSecondary,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    const SizedBox(width: UiConstants.space4),
                    Icon(
                      UiIcons.calendar,
                      size: UiConstants.iconSm,
                      color: UiColors.mutedForeground,
                    ),
                    const SizedBox(width: 6),
                    Text(
                      '${_formatDate(widget.shift.date)}, ${_formatTime(widget.shift.startTime)}',
                      style: UiTypography.body2r.textSecondary,
                    ),
                  ],
                ),
                const SizedBox(height: UiConstants.space4),

                // Tags
                Wrap(
                  spacing: 8,
                  runSpacing: 8,
                  children: [
                    _buildTag(
                      UiIcons.zap,
                      t.staff_shifts.tags.immediate_start,
                      UiColors.accent.withValues(alpha: 0.3),
                      UiColors.foreground,
                    ),
                    _buildTag(
                      UiIcons.timer,
                      t.staff_shifts.tags.no_experience,
                      UiColors.tagError,
                      UiColors.textError,
                    ),
                  ],
                ),

                const SizedBox(height: UiConstants.space4),
              ],
            ),
          ),

          // Actions
          if (!widget.compact)
            Padding(
              padding: const EdgeInsets.symmetric(
                horizontal: UiConstants.space5,
              ),
              child: Column(
                children: [
                  SizedBox(
                    width: double.infinity,
                    height: UiConstants.space12,
                    child: ElevatedButton(
                      onPressed: widget.onApply,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: UiColors.primary,
                        foregroundColor: UiColors.white,
                        elevation: 0,
                        shape: RoundedRectangleBorder(
                          borderRadius:
                              BorderRadius.circular(UiConstants.radiusBase),
                        ),
                      ),
                      child: Text(t.staff_shifts.card.accept_shift),
                    ),
                  ),
                  const SizedBox(height: UiConstants.space2),
                  SizedBox(
                    width: double.infinity,
                    height: UiConstants.space12,
                    child: OutlinedButton(
                      onPressed: widget.onDecline,
                      style: OutlinedButton.styleFrom(
                        foregroundColor: UiColors.destructive,
                        side: BorderSide(
                          color: UiColors.destructive.withValues(alpha: 0.3),
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius:
                              BorderRadius.circular(UiConstants.radiusBase),
                        ),
                      ),
                      child: Text(t.staff_shifts.card.decline_shift),
                    ),
                  ),
                  const SizedBox(height: UiConstants.space5),
                ],
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildTag(IconData icon, String label, Color bg, Color text) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      decoration: BoxDecoration(
        color: bg,
        borderRadius: UiConstants.radiusFull,
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: UiConstants.iconSm - 2, color: text),
          const SizedBox(width: UiConstants.space1),
          Flexible(
            child: Text(
              label,
              style: UiTypography.body3m.copyWith(color: text),
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }
}
