/// Business Unit Selection Page
///
/// Allows users to select a business unit during registration or after login
/// when they have access to multiple units.
library;

import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:go_router/go_router.dart';
import 'package:worker/core/constants/ui_constants.dart';
import 'package:worker/core/router/app_router.dart';
import 'package:worker/core/theme/colors.dart';
import 'package:worker/features/auth/domain/entities/business_unit.dart';

/// Business Unit Selection Page
///
/// Flow:
/// 1. During registration: User selects unit before going to register page
/// 2. After login: User selects unit if they have multiple units
class BusinessUnitSelectionPage extends StatefulWidget {
  const BusinessUnitSelectionPage({
    super.key,
    this.businessUnits,
    this.isRegistrationFlow = false,
    this.onUnitSelected,
  });

  /// List of available business units
  final List<BusinessUnit>? businessUnits;

  /// Whether this is part of registration flow
  final bool isRegistrationFlow;

  /// Callback when business unit is selected (for registration flow)
  final void Function(BusinessUnit)? onUnitSelected;

  @override
  State<BusinessUnitSelectionPage> createState() =>
      _BusinessUnitSelectionPageState();
}

class _BusinessUnitSelectionPageState extends State<BusinessUnitSelectionPage> {
  BusinessUnit? _selectedUnit;
  late List<BusinessUnit> _availableUnits;

  @override
  void initState() {
    super.initState();
    // Use provided units or mock data for registration flow
    _availableUnits = widget.businessUnits ?? _getMockBusinessUnits();
  }

  /// Mock business units for registration flow
  /// TODO: Replace with actual API data when backend is ready
  List<BusinessUnit> _getMockBusinessUnits() {
    return [
      const BusinessUnit(
        id: '1',
        code: 'VIKD',
        name: 'VIKD',
        description: 'Đơn vị kinh doanh VIKD',
      ),
      const BusinessUnit(
        id: '2',
        code: 'HSKD',
        name: 'HSKD',
        description: 'Đơn vị kinh doanh HSKD',
      ),
      const BusinessUnit(
        id: '3',
        code: 'LPKD',
        name: 'LPKD',
        description: 'Đơn vị kinh doanh LPKD',
      ),
    ];
  }

  void _handleContinue() {
    if (_selectedUnit == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Vui lòng chọn đơn vị kinh doanh'),
          backgroundColor: AppColors.danger,
        ),
      );
      return;
    }

    if (widget.isRegistrationFlow) {
      // Registration flow: pass selected unit to register page
      widget.onUnitSelected?.call(_selectedUnit!);
      context.pushNamed(
        RouteNames.register,
        extra: {'businessUnit': _selectedUnit},
      );
    } else {
      // Login flow: save selected unit and navigate to home
      // TODO: Save selected unit to local storage/state
      context.goNamed(RouteNames.home);
    }
  }

  void _showInfoDialog() {
    showDialog<void>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Đơn vị kinh doanh'),
        content: const Text(
          'Chọn đơn vị kinh doanh mà bạn muốn truy cập. '
          'Bạn có thể thay đổi đơn vị sau khi đăng nhập.',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Đóng'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    return Scaffold(
      backgroundColor: colorScheme.surface,
      appBar: AppBar(
        backgroundColor: colorScheme.surface,
        elevation: AppBarSpecs.elevation,
        leading: IconButton(
          icon: FaIcon(FontAwesomeIcons.arrowLeft, color: colorScheme.onSurface, size: 20),
          onPressed: () => context.pop(),
        ),
        title: Text(
          'Đơn vị kinh doanh',
          style: TextStyle(
            color: colorScheme.onSurface,
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
        centerTitle: false,
        actions: [
          IconButton(
            icon: FaIcon(FontAwesomeIcons.circleInfo, color: colorScheme.onSurface, size: 20),
            onPressed: _showInfoDialog,
          ),
          const SizedBox(width: AppSpacing.sm),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(AppSpacing.lg),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // Logo Section
            Center(
              child: Container(
                padding: const EdgeInsets.all(20),
                decoration: BoxDecoration(
                  gradient: const LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [AppColors.primaryBlue, AppColors.lightBlue],
                  ),
                  borderRadius: BorderRadius.circular(20),
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      'DBIZ',
                      style: TextStyle(
                        color: colorScheme.onPrimary,
                        fontSize: 32,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                    Text(
                      'Worker App',
                      style: TextStyle(color: colorScheme.onPrimary, fontSize: 12),
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: AppSpacing.xl),

            // Welcome Message
            Text(
              'Chọn đơn vị kinh doanh để tiếp tục',
              textAlign: TextAlign.center,
              style: TextStyle(color: colorScheme.onSurfaceVariant, fontSize: 14),
            ),

            const SizedBox(height: 40),

            Padding(
              padding: const EdgeInsets.symmetric(horizontal: AppSpacing.sm),
              child: Text(
                'Đơn vị kinh doanh',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                  color: colorScheme.onSurface,
                ),
              ),
            ),
            const SizedBox(height: AppSpacing.md),

            // Business Unit Selection List
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Business Unit List Tiles
                    ...(_availableUnits.asMap().entries.map((entry) {
                      final index = entry.key;
                      final unit = entry.value;
                      final isSelected = _selectedUnit?.id == unit.id;
                      final isFirst = index == 0;
                      final isLast = index == _availableUnits.length - 1;
                
                      return Container(
                        margin: EdgeInsets.only(
                          bottom: isLast ? 0 : AppSpacing.xs,
                        ),
                        decoration: BoxDecoration(
                          color: colorScheme.surface,
                          border: Border.all(
                            color: isSelected
                                ? colorScheme.primary
                                : colorScheme.surfaceContainerHighest,
                            width: isSelected ? 2 : 1,
                          ),
                          borderRadius: BorderRadius.vertical(
                            top: isFirst
                                ? const Radius.circular(
                                    InputFieldSpecs.borderRadius,
                                  )
                                : Radius.zero,
                            bottom: isLast
                                ? const Radius.circular(
                                    InputFieldSpecs.borderRadius,
                                  )
                                : Radius.zero,
                          ),
                          boxShadow: isSelected
                              ? [
                                  BoxShadow(
                                    color: colorScheme.primary.withValues(
                                      alpha: 0.1,
                                    ),
                                    blurRadius: 8,
                                    offset: const Offset(0, 2),
                                  ),
                                ]
                              : null,
                        ),
                        child: InkWell(
                          onTap: () {
                            setState(() {
                              _selectedUnit = unit;
                            });
                          },
                          borderRadius: BorderRadius.vertical(
                            top: isFirst
                                ? const Radius.circular(
                                    InputFieldSpecs.borderRadius,
                                  )
                                : Radius.zero,
                            bottom: isLast
                                ? const Radius.circular(
                                    InputFieldSpecs.borderRadius,
                                  )
                                : Radius.zero,
                          ),
                          child: Padding(
                            padding: const EdgeInsets.symmetric(
                              horizontal: AppSpacing.lg,
                              vertical: AppSpacing.md,
                            ),
                            child: Row(
                              children: [
                                // Icon
                                Container(
                                  width: 40,
                                  height: 40,
                                  decoration: BoxDecoration(
                                    color: isSelected
                                        ? colorScheme.primary.withValues(
                                            alpha: 0.1,
                                          )
                                        : colorScheme.surfaceContainerLowest,
                                    borderRadius: BorderRadius.circular(8),
                                  ),
                                  child: Icon(
                                    FontAwesomeIcons.building,
                                    color: isSelected
                                        ? colorScheme.primary
                                        : colorScheme.onSurfaceVariant,
                                    size: 20,
                                  ),
                                ),
                                const SizedBox(width: AppSpacing.md),
                                // Unit Name
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        unit.name,
                                        style: TextStyle(
                                          fontSize: 16,
                                          fontWeight: isSelected
                                              ? FontWeight.w600
                                              : FontWeight.w500,
                                          color: isSelected
                                              ? colorScheme.primary
                                              : colorScheme.onSurface,
                                        ),
                                      ),
                                      if (unit.description != null) ...[
                                        const SizedBox(height: 2),
                                        Text(
                                          unit.description!,
                                          style: TextStyle(
                                            fontSize: 12,
                                            color: colorScheme.onSurfaceVariant,
                                          ),
                                        ),
                                      ],
                                    ],
                                  ),
                                ),
                                // Radio indicator
                                Container(
                                  width: 20,
                                  height: 20,
                                  decoration: BoxDecoration(
                                    shape: BoxShape.circle,
                                    border: Border.all(
                                      color: isSelected
                                          ? colorScheme.primary
                                          : colorScheme.onSurfaceVariant,
                                      width: 2,
                                    ),
                                    color: isSelected
                                        ? colorScheme.primary
                                        : Colors.transparent,
                                  ),
                                  child: isSelected
                                      ? Icon(
                                          FontAwesomeIcons.solidCircle,
                                          size: 10,
                                          color: colorScheme.onPrimary,
                                        )
                                      : null,
                                ),
                              ],
                            ),
                          ),
                        ),
                      );
                    }).toList()),
                  ],
                ),
              ),
            ),

            const SizedBox(height: AppSpacing.xl),
            // Continue Button
            SizedBox(
              height: ButtonSpecs.height,
              child: ElevatedButton(
                onPressed: _handleContinue,
                style: ElevatedButton.styleFrom(
                  backgroundColor: colorScheme.primary,
                  foregroundColor: colorScheme.onPrimary,
                  elevation: 0,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(
                      ButtonSpecs.borderRadius,
                    ),
                  ),
                ),
                child: const Text(
                  'Tiếp tục',
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
                ),
              ),
            ),
            const SizedBox(height: AppSpacing.xl),
          ],
        ),
      ),
    );
  }
}
