import 'package:core_localization/core_localization.dart';
import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:krow_domain/krow_domain.dart';
import '../../blocs/one_time_order_state.dart';

/// A card widget for editing a specific position in a one-time order.
/// Matches the prototype layout while using design system tokens.
class OneTimeOrderPositionCard extends StatelessWidget {
  /// Creates a [OneTimeOrderPositionCard].
  const OneTimeOrderPositionCard({
    required this.index,
    required this.position,
    required this.isRemovable,
    required this.onUpdated,
    required this.onRemoved,
    required this.positionLabel,
    required this.roleLabel,
    required this.workersLabel,
    required this.startLabel,
    required this.endLabel,
    required this.lunchLabel,
    required this.roles,
    super.key,
  });

  /// The index of the position in the list.
  final int index;

  /// The position entity data.
  final OneTimeOrderPosition position;

  /// Whether this position can be removed (usually if there's more than one).
  final bool isRemovable;

  /// Callback when the position data is updated.
  final ValueChanged<OneTimeOrderPosition> onUpdated;

  /// Callback when the position is removed.
  final VoidCallback onRemoved;

  /// Label for positions (e.g., "Position").
  final String positionLabel;

  /// Label for the role selection.
  final String roleLabel;

  /// Label for the worker count.
  final String workersLabel;

  /// Label for the start time.
  final String startLabel;

  /// Label for the end time.
  final String endLabel;

  /// Label for the lunch break.
  final String lunchLabel;

  /// Available roles for the selected vendor.
  final List<OneTimeOrderRoleOption> roles;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(UiConstants.space4),
      decoration: BoxDecoration(
        color: UiColors.white,
        borderRadius: UiConstants.radiusLg,
        border: Border.all(color: UiColors.border),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text(
                '$positionLabel #${index + 1}',
                style: UiTypography.footnote1m.textSecondary,
              ),
              if (isRemovable)
                GestureDetector(
                  onTap: onRemoved,
                  child: Text(
                    t.client_create_order.one_time.remove,
                    style: UiTypography.footnote1m.copyWith(
                      color: UiColors.destructive,
                    ),
                  ),
                ),
            ],
          ),
          const SizedBox(height: UiConstants.space3),

          // Role (Dropdown)
          Container(
            padding: const EdgeInsets.symmetric(horizontal: UiConstants.space3),
            height: 44,
            decoration: BoxDecoration(
              borderRadius: UiConstants.radiusMd,
              border: Border.all(color: UiColors.border),
            ),
            child: DropdownButtonHideUnderline(
              child: DropdownButton<String>(
                isExpanded: true,
                hint: Text(
                  roleLabel,
                  style: UiTypography.body2r.textPlaceholder,
                ),
                value: position.role.isEmpty ? null : position.role,
                icon: const Icon(
                  UiIcons.chevronDown,
                  size: 18,
                  color: UiColors.iconSecondary,
                ),
                onChanged: (String? val) {
                  if (val != null) {
                    onUpdated(position.copyWith(role: val));
                  }
                },
                items: _buildRoleItems(),
              ),
            ),
          ),
          const SizedBox(height: UiConstants.space3),

          // Start/End/Workers Row
          Row(
            children: <Widget>[
              // Start Time
              Expanded(
                child: _buildTimeInput(
                  context: context,
                  label: startLabel,
                  value: position.startTime,
                  onTap: () async {
                    final TimeOfDay? picked = await showTimePicker(
                      context: context,
                      initialTime: TimeOfDay.now(),
                    );
                    if (picked != null && context.mounted) {
                      onUpdated(
                        position.copyWith(startTime: picked.format(context)),
                      );
                    }
                  },
                ),
              ),
              const SizedBox(width: UiConstants.space2),
              // End Time
              Expanded(
                child: _buildTimeInput(
                  context: context,
                  label: endLabel,
                  value: position.endTime,
                  onTap: () async {
                    final TimeOfDay? picked = await showTimePicker(
                      context: context,
                      initialTime: TimeOfDay.now(),
                    );
                    if (picked != null && context.mounted) {
                      onUpdated(
                        position.copyWith(endTime: picked.format(context)),
                      );
                    }
                  },
                ),
              ),
              const SizedBox(width: UiConstants.space2),
              // Workers Count
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      workersLabel,
                      style: UiTypography.footnote2r.textSecondary,
                    ),
                    const SizedBox(height: UiConstants.space1),
                    Container(
                      height: 40,
                      decoration: BoxDecoration(
                        color: UiColors.bgSecondary,
                        borderRadius: UiConstants.radiusSm,
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: <Widget>[
                          GestureDetector(
                            onTap: () {
                              if (position.count > 1) {
                                onUpdated(
                                  position.copyWith(count: position.count - 1),
                                );
                              }
                            },
                            child: const Icon(UiIcons.minus, size: 12),
                          ),
                          Text(
                            '${position.count}',
                            style: UiTypography.body2b.textPrimary,
                          ),
                          GestureDetector(
                            onTap: () {
                              onUpdated(
                                position.copyWith(count: position.count + 1),
                              );
                            },
                            child: const Icon(UiIcons.add, size: 12),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: UiConstants.space4),

          // Lunch Break
          Text(lunchLabel, style: UiTypography.footnote2r.textSecondary),
          const SizedBox(height: UiConstants.space1),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: UiConstants.space3),
            height: 44,
            decoration: BoxDecoration(
              borderRadius: UiConstants.radiusMd,
              border: Border.all(color: UiColors.border),
            ),
            child: DropdownButtonHideUnderline(
              child: DropdownButton<String>(
                isExpanded: true,
                value: position.lunchBreak,
                icon: const Icon(
                  UiIcons.chevronDown,
                  size: 18,
                  color: UiColors.iconSecondary,
                ),
                onChanged: (String? val) {
                  if (val != null) {
                    onUpdated(position.copyWith(lunchBreak: val));
                  }
                },
                items: <String>['NO_BREAK', 'MIN_15', 'MIN_30'].map((
                  String value,
                ) {
                  final String label = switch (value) {
                    'NO_BREAK' => 'No Break',
                    'MIN_15' => '15 min',
                    _ => '30 min',
                  };
                  return DropdownMenuItem<String>(
                    value: value,
                    child: Text(
                      label,
                      style: UiTypography.body2r.textPrimary,
                    ),
                  );
                }).toList(),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTimeInput({
    required BuildContext context,
    required String label,
    required String value,
    required VoidCallback onTap,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(label, style: UiTypography.footnote2r.textSecondary),
        const SizedBox(height: UiConstants.space1),
        GestureDetector(
          onTap: onTap,
          child: Container(
            height: 40,
            padding: const EdgeInsets.symmetric(horizontal: UiConstants.space3),
            decoration: BoxDecoration(
              borderRadius: UiConstants.radiusSm,
              border: Border.all(color: UiColors.border),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text(
                  value.isEmpty ? '--:--' : value,
                  style: UiTypography.body2r.textPrimary,
                ),
                const Icon(
                  UiIcons.clock,
                  size: 14,
                  color: UiColors.iconSecondary,
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  List<DropdownMenuItem<String>> _buildRoleItems() {
    final List<DropdownMenuItem<String>> items = roles
        .map(
          (OneTimeOrderRoleOption role) => DropdownMenuItem<String>(
            value: role.id,
            child: Text(
              '${role.name} - \$${role.costPerHour.toStringAsFixed(0)}',
              style: UiTypography.body2r.textPrimary,
            ),
          ),
        )
        .toList();

    final bool hasSelected = roles.any((OneTimeOrderRoleOption role) => role.id == position.role);
    if (position.role.isNotEmpty && !hasSelected) {
      items.add(
        DropdownMenuItem<String>(
          value: position.role,
          child: Text(
            position.role,
            style: UiTypography.body2r.textPrimary,
          ),
        ),
      );
    }

    return items;
  }
}
