import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:krow_domain/krow_domain.dart';
import 'package:design_system/design_system.dart'; // Re-added for UiIcons/Colors as they are used in expanded logic
import 'package:intl/intl.dart';
import '../blocs/shift_details/shift_details_bloc.dart';
import '../blocs/shift_details/shift_details_event.dart';
import '../blocs/shift_details/shift_details_state.dart';

class ShiftDetailsPage extends StatelessWidget {
  final String shiftId;
  final Shift? shift;

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

  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);
      return DateFormat('EEEE, MMMM d, y').format(date);
    } catch (e) {
      return dateStr;
    }
  }

  double _calculateDuration(Shift shift) {
    if (shift.startTime.isEmpty || shift.endTime.isEmpty) {
      return 0;
    }
    try {
      final s = shift.startTime.split(':').map(int.parse).toList();
      final e = 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;
    }
  }

  Widget _buildStatCard(IconData icon, String value, String label) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 16),
      decoration: BoxDecoration(
        color: const Color(0xFFF8FAFC),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: UiColors.border),
      ),
      child: Column(
        children: [
          Container(
            width: 40,
            height: 40,
            decoration: const BoxDecoration(
              color: Colors.white,
              shape: BoxShape.circle,
            ),
            child: Icon(icon, size: 20, color: UiColors.iconSecondary),
          ),
          const SizedBox(height: 8),
          Text(
            value,
            style: UiTypography.title1m.copyWith(color: UiColors.textPrimary),
          ),
          Text(
            label,
            style: UiTypography.footnote2r.copyWith(
              color: UiColors.textSecondary,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTimeBox(String label, String time) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0xFFF8FAFC),
        borderRadius: BorderRadius.circular(16),
      ),
      child: Column(
        children: [
          Text(
            label,
            style: const TextStyle(
              fontSize: 10,
              fontWeight: FontWeight.bold,
              color: UiColors.textSecondary,
              letterSpacing: 0.5,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            _formatTime(time),
            style: UiTypography.display2m.copyWith(
              fontSize: 20,
              color: UiColors.textPrimary,
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider<ShiftDetailsBloc>(
      create: (_) =>
          Modular.get<ShiftDetailsBloc>()..add(LoadShiftDetailsEvent(shiftId)),
      child: BlocListener<ShiftDetailsBloc, ShiftDetailsState>(
        listener: (context, state) {
          if (state is ShiftActionSuccess) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text(state.message),
                backgroundColor: const Color(0xFF10B981),
              ),
            );
            Modular.to.pop(true); // Return outcome
          } else if (state is ShiftDetailsError) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text(state.message),
                backgroundColor: const Color(0xFFEF4444),
              ),
            );
          }
        },
        child: BlocBuilder<ShiftDetailsBloc, ShiftDetailsState>(
          builder: (context, state) {
            if (state is ShiftDetailsLoading) {
              return const Scaffold(
                body: Center(child: CircularProgressIndicator()),
              );
            }

            Shift? displayShift;
            if (state is ShiftDetailsLoaded) {
              displayShift = state.shift;
            } else {
              displayShift = shift;
            }

            if (displayShift == null) {
              return const Scaffold(
                body: Center(child: Text("Shift not found")),
              );
            }

            final duration = _calculateDuration(displayShift);
            final estimatedTotal = (displayShift.hourlyRate) * duration;
            final openSlots =
                (displayShift.requiredSlots ?? 0) -
                (displayShift.filledSlots ?? 0);

            return Scaffold(
              appBar: UiAppBar(
                title: displayShift.title,
                showBackButton: true,
                centerTitle: false,
              ),
              body: Column(
                children: [
                  Expanded(
                    child: SingleChildScrollView(
                      padding: const EdgeInsets.all(20.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // Vendor Section
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const Text(
                                "VENDOR",
                                style: TextStyle(
                                  fontSize: 10,
                                  fontWeight: FontWeight.bold,
                                  color: UiColors.textSecondary,
                                  letterSpacing: 0.5,
                                ),
                              ),
                              const SizedBox(height: 8),
                              Row(
                                children: [
                                  Container(
                                    width: 24,
                                    height: 24,
                                    child: displayShift.logoUrl != null
                                        ? ClipRRect(
                                            borderRadius: BorderRadius.circular(
                                              6,
                                            ),
                                            child: Image.network(
                                              displayShift.logoUrl!,
                                              fit: BoxFit.cover,
                                            ),
                                          )
                                        : const Center(
                                            child: Icon(
                                              UiIcons.briefcase,
                                              color: UiColors.primary,
                                              size: 20,
                                            ),
                                          ),
                                  ),
                                  const SizedBox(width: 8),
                                  Text(
                                    displayShift.clientName,
                                    style: UiTypography.headline5m.copyWith(
                                      color: UiColors.textPrimary,
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                          const SizedBox(height: 24),

                          // Date Section
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const Text(
                                "SHIFT DATE",
                                style: TextStyle(
                                  fontSize: 10,
                                  fontWeight: FontWeight.bold,
                                  color: UiColors.textSecondary,
                                  letterSpacing: 0.5,
                                ),
                              ),
                              const SizedBox(height: 8),
                              Row(
                                children: [
                                  const Icon(
                                    UiIcons.calendar,
                                    size: 20,
                                    color: UiColors.primary,
                                  ),
                                  const SizedBox(width: 8),
                                  Text(
                                    _formatDate(displayShift.date),
                                    style: UiTypography.headline5m.copyWith(
                                      color: UiColors.textPrimary,
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                          const SizedBox(height: 24),

                          // Worker Capacity / Open Slots
                          if ((displayShift.requiredSlots ?? 0) > 0)
                            Container(
                              padding: const EdgeInsets.all(16),
                              decoration: BoxDecoration(
                                color: const Color(0xFFF0FDF4), // green-50
                                borderRadius: BorderRadius.circular(12),
                                border: Border.all(
                                  color: const Color(0xFFBBF7D0),
                                ), // green-200
                              ),
                              child: Row(
                                children: [
                                  const Icon(
                                    Icons.people_alt_outlined,
                                    size: 20,
                                    color: Color(0xFF15803D),
                                  ), // green-700, using Material Icon as generic fallback
                                  const SizedBox(width: 12),
                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          "$openSlots spots remaining",
                                          style: UiTypography.body2b.copyWith(
                                            color: const Color(0xFF15803D),
                                          ),
                                        ),
                                        Text(
                                          "${displayShift.filledSlots ?? 0} filled out of ${displayShift.requiredSlots}",
                                          style: UiTypography.body3r.copyWith(
                                            color: const Color(0xFF166534),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  SizedBox(
                                    width: 60,
                                    child: LinearProgressIndicator(
                                      value: (displayShift.requiredSlots! > 0)
                                          ? (displayShift.filledSlots ?? 0) /
                                                displayShift.requiredSlots!
                                          : 0,
                                      backgroundColor: Colors.white,
                                      color: const Color(0xFF15803D),
                                      minHeight: 6,
                                      borderRadius: BorderRadius.circular(3),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          const SizedBox(height: 24),

                          // Stats Grid
                          GridView.count(
                            shrinkWrap: true,
                            physics: const NeverScrollableScrollPhysics(),
                            crossAxisCount: 3,
                            crossAxisSpacing: 12,
                            childAspectRatio: 0.85,
                            children: [
                              _buildStatCard(
                                UiIcons.dollar,
                                "\$${estimatedTotal.toStringAsFixed(0)}",
                                "Total Pay",
                              ),
                              _buildStatCard(
                                UiIcons.dollar,
                                "\$${displayShift.hourlyRate.toInt()}",
                                "Per Hour",
                              ),
                              _buildStatCard(
                                UiIcons.clock,
                                "${duration.toInt()}h",
                                "Duration",
                              ),
                            ],
                          ),
                          const SizedBox(height: 24),

                          // Shift Timing
                          Row(
                            children: [
                              Expanded(
                                child: _buildTimeBox(
                                  "START TIME",
                                  displayShift.startTime,
                                ),
                              ),
                              const SizedBox(width: 12),
                              Expanded(
                                child: _buildTimeBox(
                                  "END TIME",
                                  displayShift.endTime,
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(height: 24),

                          // Location
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const Text(
                                "LOCATION",
                                style: TextStyle(
                                  fontSize: 10,
                                  fontWeight: FontWeight.bold,
                                  color: UiColors.textSecondary,
                                  letterSpacing: 0.5,
                                ),
                              ),
                              const SizedBox(height: 8),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    displayShift.location.isEmpty
                                        ? "TBD"
                                        : displayShift.location,
                                    style: UiTypography.title1m.copyWith(
                                      color: UiColors.textPrimary,
                                    ),
                                  ),
                                   Text(
                                displayShift.location.isEmpty
                                    ? "TBD"
                                    : displayShift.locationAddress,
                                style: UiTypography.title1m.copyWith(
                                  color: UiColors.textPrimary,
                                ),
                              ),
                                ],
                              ),
                            ],
                          ),
                          const SizedBox(height: 24),

                          // Additional Info
                          if (displayShift.description != null) ...[
                            SizedBox(
                              width: double.infinity,
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  const Text(
                                    "ADDITIONAL INFO",
                                    style: TextStyle(
                                      fontSize: 10,
                                      fontWeight: FontWeight.bold,
                                      color: UiColors.textSecondary,
                                      letterSpacing: 0.5,
                                    ),
                                  ),
                                  const SizedBox(height: 8),
                                  Text(
                                    displayShift.description!,
                                    style: UiTypography.body2m.copyWith(
                                      color: UiColors.textPrimary,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                          const SizedBox(height: 20),
                          Row(
                            children: [
                              Expanded(
                                child: OutlinedButton(
                                  onPressed: () =>
                                      _declineShift(context, displayShift!.id),
                                  style: OutlinedButton.styleFrom(
                                    foregroundColor: const Color(0xFFEF4444),
                                    side: const BorderSide(
                                      color: Color(0xFFEF4444),
                                    ),
                                    padding: const EdgeInsets.symmetric(
                                      vertical: 16,
                                    ),
                                  ),
                                  child: const Text("Decline"),
                                ),
                              ),
                              const SizedBox(width: 16),
                              Expanded(
                                child: ElevatedButton(
                                  onPressed: () =>
                                      _bookShift(context, displayShift!.id),
                                  style: ElevatedButton.styleFrom(
                                    backgroundColor: const Color(0xFF10B981),
                                    foregroundColor: Colors.white,
                                    padding: const EdgeInsets.symmetric(
                                      vertical: 16,
                                    ),
                                  ),
                                  child: const Text("Book Shift"),
                                ),
                              ),
                            ],
                          ),
                          SizedBox(
                            height: MediaQuery.of(context).padding.bottom + 10,
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            );
          },
        ),
      ),
    );
  }

  void _bookShift(BuildContext context, String id) {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('Book Shift'),
        content: const Text('Do you want to instantly book this shift?'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(),
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(ctx).pop();
              BlocProvider.of<ShiftDetailsBloc>(
                context,
              ).add(BookShiftDetailsEvent(id));
            },
            style: TextButton.styleFrom(
              foregroundColor: const Color(0xFF10B981),
            ),
            child: const Text('Book'),
          ),
        ],
      ),
    );
  }

  void _declineShift(BuildContext context, String id) {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('Decline Shift'),
        content: const Text(
          'Are you sure you want to decline this shift? It will be hidden from your available jobs.',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(),
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(ctx).pop();
              BlocProvider.of<ShiftDetailsBloc>(
                context,
              ).add(DeclineShiftDetailsEvent(id));
            },
            style: TextButton.styleFrom(
              foregroundColor: const Color(0xFFEF4444),
            ),
            child: const Text('Decline'),
          ),
        ],
      ),
    );
  }
}
