import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:krow_domain/krow_domain.dart';
import 'package:design_system/design_system.dart';

class ShiftAssignmentCard extends StatelessWidget {
  final Shift shift;
  final VoidCallback onConfirm;
  final VoidCallback onDecline;
  final bool isConfirming;

  const ShiftAssignmentCard({
    super.key,
    required this.shift,
    required this.onConfirm,
    required this.onDecline,
    this.isConfirming = 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: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 _calculateHours(String start, String end) {
    if (start.isEmpty || end.isEmpty) return 0;
    try {
      final s = start.split(':').map(int.parse).toList();
      final e = end.split(':').map(int.parse).toList();
      return ((e[0] * 60 + e[1]) - (s[0] * 60 + s[1])) / 60;
    } catch (_) {
      return 0;
    }
  }

  @override
  Widget build(BuildContext context) {
    final hours = _calculateHours(shift.startTime, shift.endTime);
    final totalPay = shift.hourlyRate * hours;

    return Container(
      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: Column(
        children: [
          // Header
          Padding(
            padding: const EdgeInsets.all(UiConstants.space4),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Card content starts directly as per prototype

                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: shift.logoUrl != null
                          ? ClipRRect(
                              borderRadius: BorderRadius.circular(UiConstants.radiusBase),
                              child: Image.network(
                                shift.logoUrl!,
                                fit: BoxFit.contain,
                              ),
                            )
                          : const Center(
                              child: Icon(
                                UiIcons.briefcase,
                                color: UiColors.primary,
                                size: 20,
                              ),
                            ),
                    ),
                    const SizedBox(width: UiConstants.space3),

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

                          // Date & Time
                          Row(
                            children: [
                              const Icon(
                                UiIcons.calendar,
                                size: 12,
                                color: UiColors.iconSecondary,
                              ),
                              const SizedBox(width: 4),
                              Text(
                                _formatDate(shift.date),
                                style: UiTypography.footnote1r.textSecondary,
                              ),
                              const SizedBox(width: UiConstants.space3),
                              const Icon(
                                UiIcons.clock,
                                size: 12,
                                color: UiColors.iconSecondary,
                              ),
                              const SizedBox(width: 4),
                              Text(
                                "${_formatTime(shift.startTime)} - ${_formatTime(shift.endTime)}",
                                style: UiTypography.footnote1r.textSecondary,
                              ),
                            ],
                          ),
                          const SizedBox(height: 4),

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

          // Actions
          Container(
            padding: const EdgeInsets.all(UiConstants.space2),
            decoration: const BoxDecoration(
              color: UiColors.secondary,
              borderRadius: BorderRadius.only(
                bottomLeft: Radius.circular(UiConstants.radiusBase),
                bottomRight: Radius.circular(UiConstants.radiusBase),
              ),
            ),
            child: Row(
              children: [
                Expanded(
                  child: TextButton(
                    onPressed: onDecline,
                    style: TextButton.styleFrom(
                      foregroundColor: UiColors.destructive,
                    ),
                    child: Text(
                      "Decline", // Fallback if translation is broken
                      style: UiTypography.body2m.textError,
                    ),
                  ),
                ),
                const SizedBox(width: UiConstants.space2),
                Expanded(
                  child: ElevatedButton(
                    onPressed: isConfirming ? null : onConfirm,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: UiColors.primary,
                      foregroundColor: UiColors.white,
                      elevation: 0,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(UiConstants.radiusMdValue),
                      ),
                    ),
                    child: isConfirming
                        ? const SizedBox(
                            height: 16,
                            width: 16,
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                              color: UiColors.white,
                            ),
                          )
                        : Text(
                            "Accept", // Fallback
                            style: UiTypography.body2m.white,
                          ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
