import 'package:flutter/material.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';

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

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

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

class _MyShiftCardState extends State<MyShiftCard> {
  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: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() {
    // Check title for type indicators (for mock data)
    if (widget.shift.title.contains('Long Term')) return t.staff_shifts.filter.long_term;
    if (widget.shift.title.contains('Multi-Day')) return t.staff_shifts.filter.multi_day;
    return t.staff_shifts.filter.one_day;
  }

  @override
  Widget build(BuildContext context) {
    // ignore: unused_local_variable
    final duration = _calculateDuration();

    // 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: () => setState(() => _isExpanded = !_isExpanded),
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 300),
        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.display3r.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.display3r.copyWith(
                                  color: UiColors.primary,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ),
                          ],
                        ],
                      ),
                    ),
                  
                  // Main Content
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // Date/Time Column
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                Text(
                                  _formatDate(widget.shift.date),
                                  style: UiTypography.display2m.copyWith(
                                    color: UiColors.textPrimary,
                                  ),
                                ),
                                if (widget.shift.durationDays != null) ...[
                                  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(
                                      t.staff_shifts.details.days(days: widget.shift.durationDays!),
                                      style: UiTypography.display3r.copyWith(
                                        color: UiColors.primary,
                                        fontWeight: FontWeight.w600,
                                      ),
                                    ),
                                  ),
                                ],
                              ],
                            ),
                            const SizedBox(height: 4),
                            Text(
                              '${_formatTime(widget.shift.startTime)} - ${_formatTime(widget.shift.endTime)}',
                              style: UiTypography.body2r.copyWith(
                                color: UiColors.textSecondary,
                              ),
                            ),
                            const SizedBox(height: 12),
                            Text(
                              widget.shift.title,
                              style: UiTypography.body2m.copyWith(
                                color: UiColors.textPrimary,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                            Row(
                              children: [
                                const Icon(
                                  UiIcons.mapPin,
                                  size: 12,
                                  color: UiColors.iconSecondary,
                                ),
                                const SizedBox(width: 4),
                                Text(
                                  widget.shift.clientName,
                                  style: UiTypography.display3r.copyWith(
                                    color: UiColors.textSecondary,
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                      
                      // Logo Box
                      Container(
                        width: 48,
                        height: 48,
                        decoration: BoxDecoration(
                          color: UiColors.background,
                          borderRadius: BorderRadius.circular(8),
                          border: Border.all(color: UiColors.border),
                        ),
                        child: widget.shift.logoUrl != null
                            ? ClipRRect(
                                borderRadius: BorderRadius.circular(8),
                                child: Image.network(
                                  widget.shift.logoUrl!,
                                  fit: BoxFit.cover,
                                ),
                              )
                            : Center(
                                child: Text(
                                  widget.shift.clientName.isNotEmpty 
                                    ? widget.shift.clientName[0] 
                                    : 'K',
                                  style: UiTypography.title1m.textLink,
                                ),
                              ),
                      ),
                    ],
                  ),
                ],
              ),
            ),

            // Expanded Actions
            AnimatedCrossFade(
              firstChild: const SizedBox(height: 0),
              secondChild: Container(
                decoration: const BoxDecoration(
                  border: Border(
                    top: BorderSide(color: UiColors.border),
                  ),
                ),
                child: Column(
                  children: [
                    // Warning for Pending
                    if (status == 'pending' || status == 'open')
                      Container(
                        width: double.infinity,
                        padding: const EdgeInsets.symmetric(
                          vertical: 8,
                          horizontal: 16,
                        ),
                        color: UiColors.accent.withOpacity(0.1),
                        child: Row(
                          children: [
                            const Icon(
                              UiIcons.warning,
                              size: 14,
                              color: UiColors.textWarning, 
                            ),
                            const SizedBox(width: 8),
                            Text(
                              t.staff_shifts.status.pending_warning,
                              style: UiTypography.display3r.copyWith(
                                color: UiColors.textWarning,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                      ),

                    Padding(
                      padding: const EdgeInsets.all(12),
                      child: Row(
                        children: [
                          if (status == 'pending' || status == 'open') ...[
                            Expanded(
                              child: OutlinedButton(
                                onPressed: widget.onDecline,
                                style: OutlinedButton.styleFrom(
                                  foregroundColor: UiColors.destructive,
                                  side: const BorderSide(color: UiColors.border),
                                  padding: const EdgeInsets.symmetric(vertical: 12),
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(8),
                                  ),
                                ),
                                child: Text(t.staff_shifts.action.decline),
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: ElevatedButton(
                                onPressed: widget.onAccept,
                                style: ElevatedButton.styleFrom(
                                  backgroundColor: UiColors.primary,
                                  foregroundColor: Colors.white,
                                  elevation: 0,
                                  padding: const EdgeInsets.symmetric(vertical: 12),
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(8),
                                  ),
                                ),
                                child: Text(t.staff_shifts.action.confirm),
                              ),
                            ),
                          ] else if (status == 'confirmed') ...[
                            Expanded(
                              child: OutlinedButton.icon(
                                onPressed: widget.onRequestSwap,
                                icon: const Icon(UiIcons.swap, size: 16),
                                label: Text(t.staff_shifts.action.request_swap),
                                style: OutlinedButton.styleFrom(
                                  foregroundColor: UiColors.textPrimary,
                                  side: const BorderSide(color: UiColors.border),
                                  padding: const EdgeInsets.symmetric(vertical: 12),
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(8),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              crossFadeState: _isExpanded
                  ? CrossFadeState.showSecond
                  : CrossFadeState.showFirst,
              duration: const Duration(milliseconds: 200),
            ),
          ],
        ),
      ),
    );
  }
}
