import 'package:core_localization/core_localization.dart';
import 'package:design_system/design_system.dart';
import 'package:firebase_data_connect/firebase_data_connect.dart' as fdc;
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:krow_data_connect/krow_data_connect.dart' as dc;

class _RoleOption {
  const _RoleOption({
    required this.id,
    required this.name,
    required this.costPerHour,
  });

  final String id;
  final String name;
  final double costPerHour;
}

class _VendorOption {
  const _VendorOption({required this.id, required this.name});

  final String id;
  final String name;
}

/// A bottom sheet form for creating or reordering shifts.
///
/// This widget provides a comprehensive form matching the design patterns
/// used in view_order_card.dart for consistency across the app.
class ShiftOrderFormSheet extends StatefulWidget {

  /// Creates a [ShiftOrderFormSheet].
  const ShiftOrderFormSheet({
    super.key,
    this.initialData,
    required this.onSubmit,
    this.isLoading = false,
  });
  /// Initial data for the form (e.g. from a reorder action).
  final Map<String, dynamic>? initialData;

  /// Callback when the form is submitted.
  final Function(Map<String, dynamic> data) onSubmit;

  /// Whether the submission is loading.
  final bool isLoading;

  @override
  State<ShiftOrderFormSheet> createState() => _ShiftOrderFormSheetState();
}

class _ShiftOrderFormSheetState extends State<ShiftOrderFormSheet> {
  late TextEditingController _dateController;
  late TextEditingController _globalLocationController;
  late TextEditingController _orderNameController;

  late List<Map<String, dynamic>> _positions;

  final dc.ExampleConnector _dataConnect = dc.ExampleConnector.instance;
  List<_VendorOption> _vendors = const <_VendorOption>[];
  List<_RoleOption> _roles = const <_RoleOption>[];
  String? _selectedVendorId;
  List<dc.ListTeamHubsByOwnerIdTeamHubs> _hubs = const <dc.ListTeamHubsByOwnerIdTeamHubs>[];
  dc.ListTeamHubsByOwnerIdTeamHubs? _selectedHub;
  bool _showSuccess = false;
  Map<String, dynamic>? _submitData;
  bool _isSubmitting = false;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();

    // Initialize date controller (always today for reorder sheet)
    final DateTime today = DateTime.now();
    final String initialDate = today.toIso8601String().split('T')[0];
    _dateController = TextEditingController(text: initialDate);

    // Initialize location controller
    _globalLocationController = TextEditingController(
      text: widget.initialData?['location'] ??
          widget.initialData?['locationAddress'] ??
          '',
    );
    _orderNameController = TextEditingController(
      text: widget.initialData?['eventName']?.toString() ?? '',
    );

    // Initialize positions
    _positions = <Map<String, dynamic>>[
      <String, dynamic>{
        'roleId': widget.initialData?['roleId'] ?? '',
        'roleName': widget.initialData?['title'] ?? widget.initialData?['role'] ?? '',
        'count': widget.initialData?['workersNeeded'] ??
            widget.initialData?['workers_needed'] ??
            1,
        'start_time': widget.initialData?['startTime'] ??
            widget.initialData?['start_time'] ??
            '09:00',
        'end_time': widget.initialData?['endTime'] ??
            widget.initialData?['end_time'] ??
            '17:00',
        'lunch_break': 'NO_BREAK',
        'location': null,
      },
    ];

    _loadVendors();
    _loadHubs();
    _loadOrderDetails();
  }

  @override
  void dispose() {
    _dateController.dispose();
    _globalLocationController.dispose();
    _orderNameController.dispose();
    super.dispose();
  }

  void _addPosition() {
    setState(() {
      _positions.add(<String, dynamic>{
        'roleId': '',
        'roleName': '',
        'count': 1,
        'start_time': '09:00',
        'end_time': '17:00',
        'lunch_break': 'NO_BREAK',
        'location': null,
      });
    });
  }

  void _removePosition(int index) {
    if (_positions.length > 1) {
      setState(() => _positions.removeAt(index));
    }
  }

  void _updatePosition(int index, String key, dynamic value) {
    setState(() => _positions[index][key] = value);
  }

  double _calculateTotalCost() {
    double total = 0;
    for (final Map<String, dynamic> pos in _positions) {
      double hours = 8.0;
      try {
        final List<String> startParts = pos['start_time'].toString().split(':');
        final List<String> endParts = pos['end_time'].toString().split(':');
        final double startH =
            int.parse(startParts[0]) + int.parse(startParts[1]) / 60;
        final double endH =
            int.parse(endParts[0]) + int.parse(endParts[1]) / 60;
        hours = endH - startH;
        if (hours < 0) hours += 24;
      } catch (_) {}
      final String roleId = pos['roleId']?.toString() ?? '';
      final double rate = _rateForRole(roleId);
      total += hours * rate * (pos['count'] as int);
    }
    return total;
  }

  String _getShiftType() {
    final String? type = widget.initialData?['type']?.toString();
    if (type != null && type.isNotEmpty) {
      switch (type) {
        case 'PERMANENT':
          return 'Long Term';
        case 'RECURRING':
          return 'Multi-Day';
        case 'RAPID':
          return 'Rapid';
        case 'ONE_TIME':
          return 'One-Time Order';
      }
    }
    // Determine shift type based on initial data
    final dynamic initialData = widget.initialData;
    if (initialData != null) {
      if (initialData['permanent'] == true || initialData['duration_months'] != null) {
        return 'Long Term';
      }
      if (initialData['recurring'] == true || initialData['duration_days'] != null) {
        return 'Multi-Day';
      }
    }
    return 'One-Time Order';
  }

  Future<void> _handleSubmit() async {
    if (_isSubmitting) return;

    setState(() {
      _isSubmitting = true;
      _errorMessage = null;
    });

    try {
      await _submitNewOrder();
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _isSubmitting = false;
        _errorMessage = 'Failed to create order. Please try again.';
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(_errorMessage!)),
      );
    }
  }

  Future<void> _submitNewOrder() async {
    final String? businessId = dc.ClientSessionStore.instance.session?.business?.id;
    if (businessId == null || businessId.isEmpty) {
      return;
    }
    final dc.ListTeamHubsByOwnerIdTeamHubs? selectedHub = _selectedHub;
    if (selectedHub == null) {
      return;
    }

    final DateTime date = DateTime.parse(_dateController.text);
    final DateTime dateOnly = DateTime.utc(date.year, date.month, date.day);
    final fdc.Timestamp orderTimestamp = _toTimestamp(dateOnly);
    final dc.OrderType orderType =
        _orderTypeFromValue(widget.initialData?['type']?.toString());

    final fdc.OperationResult<dc.CreateOrderData, dc.CreateOrderVariables>
        orderResult = await _dataConnect
            .createOrder(
              businessId: businessId,
              orderType: orderType,
              teamHubId: selectedHub.id,
            )
            .vendorId(_selectedVendorId)
            .eventName(_orderNameController.text)
            .status(dc.OrderStatus.POSTED)
            .date(orderTimestamp)
            .execute();

    final String orderId = orderResult.data.order_insert.id;

    final int workersNeeded = _positions.fold<int>(
      0,
      (int sum, Map<String, dynamic> pos) => sum + (pos['count'] as int),
    );
    final String shiftTitle =
        'Shift 1 ${DateFormat('yyyy-MM-dd').format(date)}';
    final double shiftCost = _calculateTotalCost();

    final fdc.OperationResult<dc.CreateShiftData, dc.CreateShiftVariables>
        shiftResult = await _dataConnect
            .createShift(title: shiftTitle, orderId: orderId)
            .date(orderTimestamp)
            .location(selectedHub.hubName)
            .locationAddress(selectedHub.address)
            .latitude(selectedHub.latitude)
            .longitude(selectedHub.longitude)
            .placeId(selectedHub.placeId)
            .city(selectedHub.city)
            .state(selectedHub.state)
            .street(selectedHub.street)
            .country(selectedHub.country)
            .status(dc.ShiftStatus.PENDING)
            .workersNeeded(workersNeeded)
            .filled(0)
            .durationDays(1)
            .cost(shiftCost)
            .execute();

    final String shiftId = shiftResult.data.shift_insert.id;

    for (final Map<String, dynamic> pos in _positions) {
      final String roleId = pos['roleId']?.toString() ?? '';
      if (roleId.isEmpty) {
        continue;
      }
      final DateTime start = _parseTime(date, pos['start_time'].toString());
      final DateTime end = _parseTime(date, pos['end_time'].toString());
      final DateTime normalizedEnd =
          end.isBefore(start) ? end.add(const Duration(days: 1)) : end;
      final double hours = normalizedEnd.difference(start).inMinutes / 60.0;
      final int count = pos['count'] as int;
      final double rate = _rateForRole(roleId);
      final double totalValue = rate * hours * count;
      final String lunchBreak = pos['lunch_break'] as String;

      await _dataConnect
          .createShiftRole(
            shiftId: shiftId,
            roleId: roleId,
            count: count,
          )
          .startTime(_toTimestamp(start))
          .endTime(_toTimestamp(normalizedEnd))
          .hours(hours)
          .breakType(_breakDurationFromValue(lunchBreak))
          .isBreakPaid(_isBreakPaid(lunchBreak))
          .totalValue(totalValue)
          .execute();
    }

    await _dataConnect
        .updateOrder(id: orderId, teamHubId: selectedHub.id)
        .shifts(fdc.AnyValue(<String>[shiftId]))
        .execute();

    if (!mounted) return;
    setState(() {
      _submitData = <String, dynamic>{
        'orderId': orderId,
        'date': _dateController.text,
      };
      _showSuccess = true;
      _isSubmitting = false;
    });
  }

  Future<void> _loadVendors() async {
    try {
      final fdc.QueryResult<dc.ListVendorsData, void> result =
          await _dataConnect.listVendors().execute();
      final List<_VendorOption> vendors = result.data.vendors
          .map(
            (dc.ListVendorsVendors vendor) =>
                _VendorOption(id: vendor.id, name: vendor.companyName),
          )
          .toList();
      if (!mounted) return;
      setState(() {
        _vendors = vendors;
        final String? current = _selectedVendorId;
        if (current == null ||
            !vendors.any((_VendorOption v) => v.id == current)) {
          _selectedVendorId = vendors.isNotEmpty ? vendors.first.id : null;
        }
      });
      if (_selectedVendorId != null) {
        await _loadRolesForVendor(_selectedVendorId!);
      }
    } catch (_) {
      if (!mounted) return;
      setState(() {
        _vendors = const <_VendorOption>[];
        _roles = const <_RoleOption>[];
      });
    }
  }

  Future<void> _loadHubs() async {
    final String? businessId = dc.ClientSessionStore.instance.session?.business?.id;
    if (businessId == null || businessId.isEmpty) {
      return;
    }

    try {
      final fdc.QueryResult<
          dc.ListTeamHubsByOwnerIdData,
          dc.ListTeamHubsByOwnerIdVariables> result =
          await _dataConnect.listTeamHubsByOwnerId(ownerId: businessId).execute();
      final List<dc.ListTeamHubsByOwnerIdTeamHubs> hubs = result.data.teamHubs;
      if (!mounted) return;
      setState(() {
        _hubs = hubs;
        _selectedHub = hubs.isNotEmpty ? hubs.first : null;
        if (_selectedHub != null) {
          _globalLocationController.text = _selectedHub!.address;
        }
      });
    } catch (_) {
      if (!mounted) return;
      setState(() {
        _hubs = const <dc.ListTeamHubsByOwnerIdTeamHubs>[];
        _selectedHub = null;
      });
    }
  }

  Future<void> _loadRolesForVendor(String vendorId) async {
    try {
      final fdc.QueryResult<dc.ListRolesByVendorIdData, dc.ListRolesByVendorIdVariables>
          result =
          await _dataConnect.listRolesByVendorId(vendorId: vendorId).execute();
      final List<_RoleOption> roles = result.data.roles
          .map(
            (dc.ListRolesByVendorIdRoles role) => _RoleOption(
              id: role.id,
              name: role.name,
              costPerHour: role.costPerHour,
            ),
          )
          .toList();
      if (!mounted) return;
      setState(() => _roles = roles);
    } catch (_) {
      if (!mounted) return;
      setState(() => _roles = const <_RoleOption>[]);
    }
  }

  Future<void> _loadOrderDetails() async {
    final String? orderId = widget.initialData?['orderId']?.toString();
    if (orderId == null || orderId.isEmpty) {
      return;
    }

    final String? businessId = dc.ClientSessionStore.instance.session?.business?.id;
    if (businessId == null || businessId.isEmpty) {
      return;
    }

    try {
      final fdc.QueryResult<
          dc.ListShiftRolesByBusinessAndOrderData,
          dc.ListShiftRolesByBusinessAndOrderVariables> result = await _dataConnect
          .listShiftRolesByBusinessAndOrder(
            businessId: businessId,
            orderId: orderId,
          )
          .execute();

      final List<dc.ListShiftRolesByBusinessAndOrderShiftRoles> shiftRoles =
          result.data.shiftRoles;
      if (shiftRoles.isEmpty) {
        return;
      }

      final dc.ListShiftRolesByBusinessAndOrderShiftRolesShift firstShift =
          shiftRoles.first.shift;
      final dc.ListShiftRolesByBusinessAndOrderShiftRolesShiftOrderTeamHub
      teamHub = firstShift.order.teamHub;
      await _loadHubsAndSelect(
        placeId: teamHub.placeId,
        hubName: teamHub.hubName,
        address: teamHub.address,
      );
      _orderNameController.text = firstShift.order.eventName ?? '';

      final String? vendorId = firstShift.order.vendorId;
      if (mounted) {
        setState(() {
          _selectedVendorId = vendorId;
        });
      }
      if (vendorId != null && vendorId.isNotEmpty) {
        await _loadRolesForVendor(vendorId);
      }

      final List<Map<String, dynamic>> positions =
          shiftRoles.map((dc.ListShiftRolesByBusinessAndOrderShiftRoles role) {
        return <String, dynamic>{
          'roleId': role.roleId,
          'roleName': role.role.name,
          'count': role.count,
          'start_time': _formatTimeForField(role.startTime),
          'end_time': _formatTimeForField(role.endTime),
          'lunch_break': _breakValueFromDuration(role.breakType),
          'location': null,
        };
      }).toList();

      if (!mounted) return;
      setState(() {
        _positions = positions;
      });
    } catch (_) {
      // Keep defaults on failure.
    }
  }

  Future<void> _loadHubsAndSelect({
    String? placeId,
    String? hubName,
    String? address,
  }) async {
    final String? businessId = dc.ClientSessionStore.instance.session?.business?.id;
    if (businessId == null || businessId.isEmpty) {
      return;
    }

    try {
      final fdc.QueryResult<
          dc.ListTeamHubsByOwnerIdData,
          dc.ListTeamHubsByOwnerIdVariables> result =
          await _dataConnect.listTeamHubsByOwnerId(ownerId: businessId).execute();
      final List<dc.ListTeamHubsByOwnerIdTeamHubs> hubs = result.data.teamHubs;
      dc.ListTeamHubsByOwnerIdTeamHubs? selected;

      if (placeId != null && placeId.isNotEmpty) {
        for (final dc.ListTeamHubsByOwnerIdTeamHubs hub in hubs) {
          if (hub.placeId == placeId) {
            selected = hub;
            break;
          }
        }
      }

      if (selected == null && hubName != null && hubName.isNotEmpty) {
        for (final dc.ListTeamHubsByOwnerIdTeamHubs hub in hubs) {
          if (hub.hubName == hubName) {
            selected = hub;
            break;
          }
        }
      }

      if (selected == null && address != null && address.isNotEmpty) {
        for (final dc.ListTeamHubsByOwnerIdTeamHubs hub in hubs) {
          if (hub.address == address) {
            selected = hub;
            break;
          }
        }
      }

      selected ??= hubs.isNotEmpty ? hubs.first : null;

      if (!mounted) return;
      setState(() {
        _hubs = hubs;
        _selectedHub = selected;
        if (selected != null) {
          _globalLocationController.text = selected.address;
        }
      });
    } catch (_) {
      if (!mounted) return;
      setState(() {
        _hubs = const <dc.ListTeamHubsByOwnerIdTeamHubs>[];
        _selectedHub = null;
      });
    }
  }

  String _formatTimeForField(fdc.Timestamp? value) {
    if (value == null) return '';
    try {
      return DateFormat('HH:mm').format(value.toDateTime());
    } catch (_) {
      return '';
    }
  }

  String _breakValueFromDuration(dc.EnumValue<dc.BreakDuration>? breakType) {
    final dc.BreakDuration? value =
        breakType is dc.Known<dc.BreakDuration> ? breakType.value : null;
    switch (value) {
      case dc.BreakDuration.MIN_10:
        return 'MIN_10';
      case dc.BreakDuration.MIN_15:
        return 'MIN_15';
      case dc.BreakDuration.MIN_30:
        return 'MIN_30';
      case dc.BreakDuration.MIN_45:
        return 'MIN_45';
      case dc.BreakDuration.MIN_60:
        return 'MIN_60';
      case dc.BreakDuration.NO_BREAK:
      case null:
        return 'NO_BREAK';
    }
  }

  dc.BreakDuration _breakDurationFromValue(String value) {
    switch (value) {
      case 'MIN_10':
        return dc.BreakDuration.MIN_10;
      case 'MIN_15':
        return dc.BreakDuration.MIN_15;
      case 'MIN_30':
        return dc.BreakDuration.MIN_30;
      case 'MIN_45':
        return dc.BreakDuration.MIN_45;
      case 'MIN_60':
        return dc.BreakDuration.MIN_60;
      default:
        return dc.BreakDuration.NO_BREAK;
    }
  }

  bool _isBreakPaid(String value) {
    return value == 'MIN_10' || value == 'MIN_15';
  }

  dc.OrderType _orderTypeFromValue(String? value) {
    switch (value) {
      case 'PERMANENT':
        return dc.OrderType.PERMANENT;
      case 'RECURRING':
        return dc.OrderType.RECURRING;
      case 'RAPID':
        return dc.OrderType.RAPID;
      case 'ONE_TIME':
      default:
        return dc.OrderType.ONE_TIME;
    }
  }

  _RoleOption? _roleById(String roleId) {
    for (final _RoleOption role in _roles) {
      if (role.id == roleId) {
        return role;
      }
    }
    return null;
  }

  double _rateForRole(String roleId) {
    return _roleById(roleId)?.costPerHour ?? 0;
  }

  DateTime _parseTime(DateTime date, String time) {
    DateTime parsed;
    try {
      parsed = DateFormat.Hm().parse(time);
    } catch (_) {
      parsed = DateFormat.jm().parse(time);
    }
    return DateTime(
      date.year,
      date.month,
      date.day,
      parsed.hour,
      parsed.minute,
    );
  }

  fdc.Timestamp _toTimestamp(DateTime date) {
    final DateTime utc = date.toUtc();
    final int millis = utc.millisecondsSinceEpoch;
    final int seconds = millis ~/ 1000;
    final int nanos = (millis % 1000) * 1000000;
    return fdc.Timestamp(nanos, seconds);
  }

  @override
  Widget build(BuildContext context) {
    if (_showSuccess) {
      final TranslationsClientCreateOrderOneTimeEn labels =
          t.client_create_order.one_time;
      return _buildSuccessView(
        title: labels.success_title,
        message: labels.success_message,
        buttonLabel: labels.back_to_orders,
      );
    }

    return Container(
      height: MediaQuery.of(context).size.height * 0.95,
      decoration: BoxDecoration(
        color: UiColors.bgPrimary,
        borderRadius: const BorderRadius.vertical(top: Radius.circular(UiConstants.space6)),
      ),
      child: Column(
        children: <Widget>[
          _buildHeader(),
          Expanded(
            child: ListView(
              padding: const EdgeInsets.all(UiConstants.space5),
              children: <Widget>[
                Text(
                  widget.initialData != null ? 'Edit Your Order' : 'Create New Order',
                  style: UiTypography.headline3m.textPrimary,
                ),
                const SizedBox(height: UiConstants.space2),
                Text(
                  widget.initialData != null
                      ? 'Review and adjust the details below'
                      : 'Fill in the details for your staffing needs',
                  style: UiTypography.body2r.textSecondary,
                ),
                const SizedBox(height: UiConstants.space5),

                // Shift Type Badge
                Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: UiConstants.space3,
                    vertical: UiConstants.space2,
                  ),
                  decoration: BoxDecoration(
                    color: UiColors.primary.withValues(alpha: 0.1),
                    borderRadius: UiConstants.radiusFull,
                    border: Border.all(
                      color: UiColors.primary.withValues(alpha: 0.3),
                    ),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Container(
                        width: 8,
                        height: 8,
                        decoration: const BoxDecoration(
                          shape: BoxShape.circle,
                          color: UiColors.primary,
                        ),
                      ),
                      const SizedBox(width: UiConstants.space2),
                      Text(
                        _getShiftType(),
                        style: UiTypography.footnote1b.copyWith(
                          color: UiColors.primary,
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: UiConstants.space5),

                _buildSectionHeader('VENDOR'),
                _buildVendorDropdown(),
                const SizedBox(height: UiConstants.space4),

                _buildSectionHeader('ORDER NAME'),
                _buildOrderNameField(),
                const SizedBox(height: UiConstants.space4),

                _buildSectionHeader('DATE'),
                _buildDateField(),
                const SizedBox(height: UiConstants.space4),

                _buildSectionHeader('HUB'),
                _buildHubField(),
                const SizedBox(height: UiConstants.space5),

                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Text(
                      'POSITIONS',
                      style: UiTypography.footnote2r.textSecondary,
                    ),
                    GestureDetector(
                      onTap: _addPosition,
                      child: Row(
                        children: <Widget>[
                          const Icon(
                            UiIcons.add,
                            size: 16,
                            color: UiColors.primary,
                          ),
                          const SizedBox(width: UiConstants.space1),
                          Text(
                            'Add Position',
                            style: UiTypography.footnote1m.copyWith(
                              color: UiColors.primary,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: UiConstants.space3),

                ..._positions.asMap().entries.map((MapEntry<int, Map<String, dynamic>> entry) {
                  return _buildPositionCard(entry.key, entry.value);
                }),

                const SizedBox(height: UiConstants.space5),

                // Total Cost Display
                Container(
                  padding: const EdgeInsets.all(UiConstants.space4),
                  decoration: BoxDecoration(
                    color: UiColors.bgSecondary,
                    borderRadius: UiConstants.radiusLg,
                    border: Border.all(color: UiColors.border),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text(
                        'Estimated Total',
                        style: UiTypography.body1b.textPrimary,
                      ),
                      Text(
                        '\$${_calculateTotalCost().toStringAsFixed(2)}',
                        style: UiTypography.headline3m.copyWith(
                          color: UiColors.primary,
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: UiConstants.space5),

                UiButton.primary(
                  text: widget.initialData != null ? 'Update Order' : 'Post Order',
                  onPressed: (widget.isLoading || _isSubmitting) ? null : _handleSubmit,
                ),
                SizedBox(height: MediaQuery.of(context).padding.bottom + UiConstants.space5),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.all(UiConstants.space5),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: <Color>[
            UiColors.primary,
            UiColors.primary.withValues(alpha: 0.8),
          ],
        ),
        borderRadius: const BorderRadius.vertical(top: Radius.circular(UiConstants.space6)),
      ),
      child: Row(
        children: <Widget>[
          GestureDetector(
            onTap: () => Navigator.pop(context),
            child: Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: UiColors.white.withValues(alpha: 0.2),
                borderRadius: UiConstants.radiusMd,
              ),
              child: const Icon(
                UiIcons.chevronLeft,
                color: UiColors.white,
                size: 24,
              ),
            ),
          ),
          const SizedBox(width: UiConstants.space3),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                _getShiftType(),
                style: UiTypography.headline3m.copyWith(color: UiColors.white),
              ),
              Text(
                'Configure your staffing needs',
                style: UiTypography.footnote2r.copyWith(
                  color: UiColors.white.withValues(alpha: 0.8),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildSectionHeader(String title) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Text(title, style: UiTypography.footnote2r.textSecondary),
    );
  }

  Widget _buildVendorDropdown() {
    return Container(
      padding: const EdgeInsets.symmetric(
        horizontal: UiConstants.space3,
      ),
      height: 48,
      decoration: BoxDecoration(
        color: UiColors.white,
        borderRadius: UiConstants.radiusMd,
        border: Border.all(color: UiColors.border),
      ),
      child: DropdownButtonHideUnderline(
        child: DropdownButton<String>(
          isExpanded: true,
          value: _selectedVendorId,
          icon: const Icon(
            UiIcons.chevronDown,
            size: 18,
            color: UiColors.iconSecondary,
          ),
          style: UiTypography.body2r.textPrimary,
          items: _vendors.map((_VendorOption vendor) {
            return DropdownMenuItem<String>(
              value: vendor.id,
              child: Text(vendor.name),
            );
          }).toList(),
          onChanged: (String? newValue) {
            if (newValue != null) {
              setState(() {
                _selectedVendorId = newValue;
              });
              _loadRolesForVendor(newValue);
            }
          },
        ),
      ),
    );
  }

  Widget _buildDateField() {
    return GestureDetector(
      onTap: () async {
        final DateTime? selectedDate = await showDatePicker(
          context: context,
          initialDate: _dateController.text.isNotEmpty
              ? DateTime.parse(_dateController.text)
              : DateTime.now().add(const Duration(days: 1)),
          firstDate: DateTime.now(),
          lastDate: DateTime.now().add(const Duration(days: 365 * 2)),
        );
        if (selectedDate != null) {
          setState(() {
            _dateController.text =
                selectedDate.toIso8601String().split('T')[0];
          });
        }
      },
      child: Container(
        padding: const EdgeInsets.symmetric(
          horizontal: UiConstants.space3,
          vertical: UiConstants.space3,
        ),
        decoration: BoxDecoration(
          color: UiColors.white,
          borderRadius: UiConstants.radiusMd,
          border: Border.all(color: UiColors.border),
        ),
        child: Row(
          children: <Widget>[
            const Icon(UiIcons.calendar, size: 20, color: UiColors.iconSecondary),
            const SizedBox(width: UiConstants.space2),
            Expanded(
              child: Text(
                _dateController.text.isNotEmpty
                    ? DateFormat('EEEE, MMM d, y')
                        .format(DateTime.parse(_dateController.text))
                    : 'Select date',
                style: _dateController.text.isNotEmpty
                    ? UiTypography.body2r.textPrimary
                    : UiTypography.body2r.textSecondary,
              ),
            ),
            const Icon(
              UiIcons.chevronDown,
              size: 18,
              color: UiColors.iconSecondary,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildHubField() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: UiConstants.space3),
      decoration: BoxDecoration(
        color: UiColors.white,
        borderRadius: UiConstants.radiusMd,
        border: Border.all(color: UiColors.border),
      ),
      child: DropdownButtonHideUnderline(
        child: DropdownButton<dc.ListTeamHubsByOwnerIdTeamHubs>(
          isExpanded: true,
          value: _selectedHub,
          icon: const Icon(
            UiIcons.chevronDown,
            size: 18,
            color: UiColors.iconSecondary,
          ),
          onChanged: (dc.ListTeamHubsByOwnerIdTeamHubs? hub) {
            if (hub != null) {
              setState(() {
                _selectedHub = hub;
                _globalLocationController.text = hub.address;
              });
            }
          },
          items: _hubs.map((dc.ListTeamHubsByOwnerIdTeamHubs hub) {
            return DropdownMenuItem<dc.ListTeamHubsByOwnerIdTeamHubs>(
              value: hub,
              child: Text(
                hub.hubName,
                style: UiTypography.body2r.textPrimary,
              ),
            );
          }).toList(),
        ),
      ),
    );
  }

  Widget _buildOrderNameField() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: UiConstants.space3),
      decoration: BoxDecoration(
        color: UiColors.white,
        borderRadius: UiConstants.radiusMd,
        border: Border.all(color: UiColors.border),
      ),
      child: TextField(
        controller: _orderNameController,
        decoration: const InputDecoration(
          hintText: 'Order name',
          border: InputBorder.none,
        ),
        style: UiTypography.body2r.textPrimary,
      ),
    );
  }

  Widget _buildPositionCard(int index, Map<String, dynamic> pos) {
    return Container(
      margin: const EdgeInsets.only(bottom: UiConstants.space3),
      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(
                'POSITION #${index + 1}',
                style: UiTypography.footnote1m.textSecondary,
              ),
              if (_positions.length > 1)
                GestureDetector(
                  onTap: () => _removePosition(index),
                  child: Text(
                    'Remove',
                    style: UiTypography.footnote1m.copyWith(
                      color: UiColors.destructive,
                    ),
                  ),
                ),
            ],
          ),
          const SizedBox(height: UiConstants.space3),

          _buildDropdownField(
            hint: 'Select role',
            value: pos['roleId'],
            items: <String>[
              ..._roles.map((_RoleOption role) => role.id),
              if (pos['roleId'] != null &&
                  pos['roleId'].toString().isNotEmpty &&
                  !_roles.any(
                    (_RoleOption role) => role.id == pos['roleId'].toString(),
                  ))
                pos['roleId'].toString(),
            ],
            itemBuilder: (dynamic roleId) {
              final _RoleOption? role = _roleById(roleId.toString());
              if (role == null) {
                final String fallback = pos['roleName']?.toString() ?? '';
                return fallback.isEmpty ? roleId.toString() : fallback;
              }
              return '${role.name} - \$${role.costPerHour.toStringAsFixed(0)}/hr';
            },
            onChanged: (dynamic val) {
              final String roleId = val?.toString() ?? '';
              final _RoleOption? role = _roleById(roleId);
              setState(() {
                _positions[index]['roleId'] = roleId;
                _positions[index]['roleName'] = role?.name ?? '';
              });
            },
          ),

          const SizedBox(height: UiConstants.space3),

          Row(
            children: <Widget>[
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      'Lunch Break',
                      style: UiTypography.footnote2r.textSecondary,
                    ),
                    const SizedBox(height: UiConstants.space1),
                    _buildDropdownField(
                      hint: 'No Break',
                      value: pos['lunch_break'],
                      items: <String>[
                        'NO_BREAK',
                        'MIN_10',
                        'MIN_15',
                        'MIN_30',
                        'MIN_45',
                        'MIN_60',
                      ],
                      itemBuilder: (dynamic value) {
                        switch (value.toString()) {
                          case 'MIN_10':
                            return '10 min (Paid)';
                          case 'MIN_15':
                            return '15 min (Paid)';
                          case 'MIN_30':
                            return '30 min (Unpaid)';
                          case 'MIN_45':
                            return '45 min (Unpaid)';
                          case 'MIN_60':
                            return '60 min (Unpaid)';
                          default:
                            return 'No Break';
                        }
                      },
                      onChanged: (dynamic val) => _updatePosition(index, 'lunch_break', val),
                    ),
                  ],
                ),
              ),
            ],
          ),

          const SizedBox(height: UiConstants.space3),

          Row(
            children: <Widget>[
              Expanded(
                child: _buildInlineTimeInput(
                  label: 'Start',
                  value: pos['start_time'],
                  onTap: () async {
                    final TimeOfDay? time = await showTimePicker(
                      context: context,
                      initialTime: TimeOfDay.now(),
                    );
                    if (time != null) {
                      _updatePosition(
                        index,
                        'start_time',
                        '${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}',
                      );
                    }
                  },
                ),
              ),
              const SizedBox(width: UiConstants.space2),
              Expanded(
                child: _buildInlineTimeInput(
                  label: 'End',
                  value: pos['end_time'],
                  onTap: () async {
                    final TimeOfDay? time = await showTimePicker(
                      context: context,
                      initialTime: TimeOfDay.now(),
                    );
                    if (time != null) {
                      _updatePosition(
                        index,
                        'end_time',
                        '${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}',
                      );
                    }
                  },
                ),
              ),
              const SizedBox(width: UiConstants.space2),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      'Workers',
                      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 ((pos['count'] as int) > 1) {
                                _updatePosition(
                                  index,
                                  'count',
                                  (pos['count'] as int) - 1,
                                );
                              }
                            },
                            child: const Icon(UiIcons.minus, size: 12),
                          ),
                          Text(
                            '${pos['count']}',
                            style: UiTypography.body2b.textPrimary,
                          ),
                          GestureDetector(
                            onTap: () => _updatePosition(
                              index,
                              'count',
                              (pos['count'] as int) + 1,
                            ),
                            child: const Icon(UiIcons.add, size: 12),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: UiConstants.space4),

          if (pos['location'] == null)
            GestureDetector(
              onTap: () => _updatePosition(index, 'location', ''),
              child: Row(
                children: <Widget>[
                  const Icon(UiIcons.mapPin, size: 14, color: UiColors.primary),
                  const SizedBox(width: UiConstants.space1),
                  Text(
                    'Use different location for this position',
                    style: UiTypography.footnote1m.copyWith(
                      color: UiColors.primary,
                    ),
                  ),
                ],
              ),
            )
          else
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Text(
                      'Custom Location',
                      style: UiTypography.footnote2r.textSecondary,
                    ),
                    GestureDetector(
                      onTap: () => _updatePosition(index, 'location', null),
                      child: Text(
                        'Remove',
                        style: UiTypography.footnote1m.copyWith(
                          color: UiColors.destructive,
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: UiConstants.space2),
                Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: UiConstants.space3,
                    vertical: UiConstants.space2,
                  ),
                  decoration: BoxDecoration(
                    color: UiColors.bgSecondary,
                    borderRadius: UiConstants.radiusSm,
                    border: Border.all(color: UiColors.border),
                  ),
                  child: TextField(
                    controller: TextEditingController(text: pos['location']),
                    decoration: const InputDecoration(
                      hintText: 'Enter custom location',
                      border: InputBorder.none,
                      isDense: true,
                      contentPadding: EdgeInsets.zero,
                    ),
                    style: UiTypography.body2r.textPrimary,
                    onChanged: (String value) =>
                        _updatePosition(index, 'location', value),
                  ),
                ),
              ],
            ),
        ],
      ),
    );
  }

  Widget _buildDropdownField<T>({
    required String hint,
    required dynamic value,
    required List<T> items,
    required String Function(T) itemBuilder,
    required void Function(T?) onChanged,
  }) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: UiConstants.space3),
      height: 48,
      decoration: BoxDecoration(
        color: UiColors.bgSecondary,
        borderRadius: UiConstants.radiusMd,
        border: Border.all(color: UiColors.border),
      ),
      child: DropdownButtonHideUnderline(
        child: DropdownButton<T>(
          isExpanded: true,
          value: value.toString().isEmpty ? null : value as T?,
          hint: Text(hint, style: UiTypography.body2r.textSecondary),
          icon: const Icon(UiIcons.chevronDown, size: 18),
          style: UiTypography.body2r.textPrimary,
          items: items
              .map(
                (T item) => DropdownMenuItem<T>(
                  value: item,
                  child: Text(itemBuilder(item)),
                ),
              )
              .toList(),
          onChanged: onChanged,
        ),
      ),
    );
  }

  Widget _buildSuccessView({
    required String title,
    required String message,
    required String buttonLabel,
  }) {
    return Container(
      width: double.infinity,
      height: MediaQuery.of(context).size.height * 0.95,
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: <Color>[UiColors.primary, UiColors.buttonPrimaryHover],
        ),
        borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
      ),
      child: SafeArea(
        child: Center(
          child: Container(
            margin: const EdgeInsets.symmetric(horizontal: 40),
            padding: const EdgeInsets.all(UiConstants.space8),
            decoration: BoxDecoration(
              color: UiColors.white,
              borderRadius: UiConstants.radiusLg * 1.5,
              boxShadow: <BoxShadow>[
                BoxShadow(
                  color: Colors.black.withValues(alpha: 0.2),
                  blurRadius: 20,
                  offset: const Offset(0, 10),
                ),
              ],
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Container(
                  width: 64,
                  height: 64,
                  decoration: const BoxDecoration(
                    color: UiColors.accent,
                    shape: BoxShape.circle,
                  ),
                  child: const Center(
                    child: Icon(
                      UiIcons.check,
                      color: UiColors.black,
                      size: 32,
                    ),
                  ),
                ),
                const SizedBox(height: UiConstants.space6),
                Text(
                  title,
                  style: UiTypography.headline2m.textPrimary,
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: UiConstants.space3),
                Text(
                  message,
                  textAlign: TextAlign.center,
                  style: UiTypography.body2r.textSecondary.copyWith(
                    height: 1.5,
                  ),
                ),
                const SizedBox(height: UiConstants.space8),
                SizedBox(
                  width: double.infinity,
                  child: UiButton.primary(
                    text: buttonLabel,
                    onPressed: () {
                      widget.onSubmit(_submitData ?? <String, dynamic>{});
                      Navigator.pop(context);
                    },
                    size: UiButtonSize.large,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildInlineTimeInput({
    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.space2),
            decoration: BoxDecoration(
              color: UiColors.bgSecondary,
              borderRadius: UiConstants.radiusSm,
              border: Border.all(color: UiColors.border),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                const Icon(UiIcons.clock, size: 14, color: UiColors.iconSecondary),
                const SizedBox(width: UiConstants.space1),
                Text(
                  value.isEmpty ? '--:--' : value,
                  style: UiTypography.body2r.textPrimary,
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}
