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:staff_shifts/src/presentation/navigation/shifts_navigator.dart';

class MyShiftCard extends StatefulWidget {
  final Shift shift;

  const MyShiftCard({
    super.key,
    required this.shift,
  });

  @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]);
      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() {
    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;
  }

  @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;

    if (status == 'confirmed') {
      statusText = t.staff_shifts.status.confirmed;
      statusColor = UiColors.textLink;
      statusBg = UiColors.primary;
    } 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;
    }

    return GestureDetector(
      onTap: () {
        Modular.to.pushShiftDetails(widget.shift);
      },
      child: Container(
        margin: const EdgeInsets.only(bottom: 12),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: UiConstants.radiusLg,
          border: Border.all(color: UiColors.border),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 2,
              offset: const Offset(0, 1),
            ),
          ],
        ),
        child: Column(
          children: [
            // Collapsed Content
            Padding(
              padding: const EdgeInsets.all(UiConstants.space4),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Status Badge
                  if (statusText.isNotEmpty)
                    Padding(
                      padding: const EdgeInsets.only(bottom: 8),
                      child: Row(
                        children: [
                          if (statusIcon != null)
                            Padding(
                              padding: const EdgeInsets.only(right: 6),
                              child: Icon(
                                statusIcon,
                                size: 12,
                                color: statusColor,
                              ),
                            )
                          else
                            Container(
                              width: 6,
                              height: 6,
                              margin: const EdgeInsets.only(right: 6),
                              decoration: BoxDecoration(
                                color: statusBg,
                                shape: BoxShape.circle,
                              ),
                            ),
                          Text(
                            statusText,
                            style: UiTypography.footnote2b.copyWith(
                              color: statusColor,
                              letterSpacing: 0.5,
                            ),
                          ),
                          // Shift Type Badge for available/pending shifts
                          if (status == 'open' || status == 'pending') ...[
                            const SizedBox(width: 8),
                            Container(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 6,
                                vertical: 2,
                              ),
                              decoration: BoxDecoration(
                                color: UiColors.primary.withOpacity(0.1),
                                borderRadius: BorderRadius.circular(4),
                              ),
                              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.withOpacity(0.09),
                              UiColors.primary.withOpacity(0.03),
                            ],
                            begin: Alignment.topLeft,
                            end: Alignment.bottomRight,
                          ),
                          borderRadius: BorderRadius.circular(12),
                          border: Border.all(
                            color: UiColors.primary.withOpacity(0.09),
                          ),
                        ),
                        child: widget.shift.logoUrl != null
                            ? ClipRRect(
                                borderRadius: BorderRadius.circular(12),
                                child: Image.network(
                                  widget.shift.logoUrl!,
                                  fit: BoxFit.contain,
                                ),
                              )
                            : const Center(
                                child: Icon(
                                  UiIcons.briefcase,
                                  color: UiColors.primary,
                                  size: 20,
                                ),
                              ),
                      ),
                      const SizedBox(width: 12),

                      // 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.copyWith(
                                          color: UiColors.textPrimary,
                                        ),
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                      Text(
                                        widget.shift.clientName,
                                        style: UiTypography.body3r.copyWith(
                                          color: UiColors.textSecondary,
                                        ),
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ],
                                  ),
                                ),
                                const SizedBox(width: 8),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.end,
                                  children: [
                                    Text(
                                      "\$${estimatedTotal.toStringAsFixed(0)}",
                                      style: UiTypography.title1m.copyWith(
                                        color: UiColors.textPrimary,
                                      ),
                                    ),
                                    Text(
                                      "\$${widget.shift.hourlyRate.toInt()}/hr · ${duration.toInt()}h",
                                      style: UiTypography.footnote2r.copyWith(
                                        color: UiColors.textSecondary,
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                            const SizedBox(height: 8),

                            // Date & Time - Multi-Day or Single Day
                            if (widget.shift.durationDays != null &&
                                widget.shift.durationDays! > 1) ...[
                              // Multi-Day Schedule Display
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    children: [
                                      const Icon(
                                        UiIcons.clock,
                                        size: 12,
                                        color: UiColors.primary,
                                      ),
                                      const SizedBox(width: 4),
                                      Text(
                                        t.staff_shifts.details.days(
                                          days: widget.shift.durationDays!,
                                        ),
                                        style: UiTypography.footnote2m.copyWith(
                                          color: UiColors.primary,
                                        ),
                                      ),
                                    ],
                                  ),
                                  const SizedBox(height: 4),
                                  Text(
                                    "Showing first schedule...",
                                    style: UiTypography.footnote2r.copyWith(
                                      color: UiColors.primary,
                                    ),
                                  ),
                                ],
                              ),
                            ] else ...[
                              // Single Day Display
                              Row(
                                children: [
                                  const Icon(
                                    UiIcons.calendar,
                                    size: 12,
                                    color: UiColors.iconSecondary,
                                  ),
                                  const SizedBox(width: 4),
                                  Text(
                                    _formatDate(widget.shift.date),
                                    style: UiTypography.footnote1r.copyWith(
                                      color: UiColors.textSecondary,
                                    ),
                                  ),
                                  const SizedBox(width: 12),
                                  const Icon(
                                    UiIcons.clock,
                                    size: 12,
                                    color: UiColors.iconSecondary,
                                  ),
                                  const SizedBox(width: 4),
                                  Text(
                                    "${_formatTime(widget.shift.startTime)} - ${_formatTime(widget.shift.endTime)}",
                                    style: UiTypography.footnote1r.copyWith(
                                      color: UiColors.textSecondary,
                                    ),
                                  ),
                                ],
                              ),
                            ],
                            const SizedBox(height: 4),

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