import 'dart:io';
import 'package:base_project/core/constants/ui_constants.dart';
import 'package:base_project/core/theme/color_scheme.dart';
import 'package:base_project/shared/widgets/app_bar/modern_app_bar.dart';
import 'package:base_project/shared/widgets/buttons/modern_button.dart';
import 'package:base_project/shared/widgets/forms/system_parameter_section.dart';
import 'package:base_project/shared/widgets/inputs/modern_image_picker.dart';
import 'package:base_project/shared/widgets/inputs/modern_text_field.dart';
import 'package:base_project/shared/widgets/theme_preview.dart';
import 'package:base_project/utils/managers/user_manager.dart';
import 'package:base_project/view_model/system_params/system_params_view_model.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:base_project/core/providers/dynamic_theme_provider.dart';

class SystemParametersView extends StatefulWidget {
  const SystemParametersView({super.key});

  @override
  _SystemParametersViewState createState() => _SystemParametersViewState();
}

class _SystemParametersViewState extends State<SystemParametersView>
    with TickerProviderStateMixin {
  final Map<String, String> formData = {};

  final TextEditingController schedulerTimerController =
      TextEditingController();
  final TextEditingController leaseTaxCodeController = TextEditingController();
  final TextEditingController vesselConfirmationController =
      TextEditingController();
  final TextEditingController rowToDisplayController = TextEditingController();
  final TextEditingController linkToDisplayController = TextEditingController();
  final TextEditingController rowToAddController = TextEditingController();
  final TextEditingController lovRowToDisplayController =
      TextEditingController();
  final TextEditingController lovLinkToDisplayController =
      TextEditingController();
  final TextEditingController oidServerNameController = TextEditingController();
  final TextEditingController oidBaseController = TextEditingController();
  final TextEditingController oidAdminUserController = TextEditingController();
  final TextEditingController oidServerPortController = TextEditingController();
  final TextEditingController userDefaultGroupController =
      TextEditingController();
  final TextEditingController defaultDepartmentController =
      TextEditingController();
  final TextEditingController defaultPositionController =
      TextEditingController();
  final TextEditingController singleChargeController = TextEditingController();
  final TextEditingController firstDayOfWeekController =
      TextEditingController();
  final TextEditingController hourPerShiftController = TextEditingController();
  final TextEditingController cnBillingFrequencyController =
      TextEditingController();
  final TextEditingController billingDepartmentCodeController =
      TextEditingController();
  final TextEditingController basePriceListController = TextEditingController();
  final TextEditingController nonContainerServiceController =
      TextEditingController();
  final TextEditingController ediMaeSchedulerController =
      TextEditingController();
  final TextEditingController ediSchedulerController = TextEditingController();
  final TextEditingController companynameController = TextEditingController();
  final TextEditingController uploadLogoController = TextEditingController();
  final TextEditingController uploadLogoNameController =
      TextEditingController();
  final TextEditingController uploadLogoPathController =
      TextEditingController();

  bool isRegistrationAllow = false;

  // Animation Controllers
  late AnimationController _pageAnimationController;
  late AnimationController _sectionsAnimationController;

  // Animations
  late Animation<double> _pageFadeAnimation;
  late Animation<Offset> _pageSlideAnimation;
  late Animation<double> _sectionsScaleAnimation;

  // Section Expansion States
  Map<String, bool> _sectionExpansions = {
    'general': true,
    'display': false,
    'lov': false,
    'oid': false,
    'user': false,
    'billing': false,
    'edi': false,
    'company': false,
  };

  @override
  void initState() {
    super.initState();
    _initializeAnimations();
    // Fetch system params; initialize controllers after data arrives
    final vm = Provider.of<SystemParamsViewModel>(context, listen: false);
    vm.getSystemParams().then((_) {
      if (mounted) {
        _initializeControllers();
      }
    });
    _startPageAnimation();
  }

  void _initializeAnimations() {
    // Page Animation Controller
    _pageAnimationController = AnimationController(
      duration: UIConstants.durationSlow,
      vsync: this,
    );

    // Sections Animation Controller
    _sectionsAnimationController = AnimationController(
      duration: UIConstants.durationNormal,
      vsync: this,
    );

    // Page Animations
    _pageFadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _pageAnimationController,
      curve: UIConstants.curveNormal,
    ));

    _pageSlideAnimation = Tween<Offset>(
      begin: const Offset(0, 0.3),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _pageAnimationController,
      curve: UIConstants.curveNormal,
    ));

    // Sections Animations
    _sectionsScaleAnimation = Tween<double>(
      begin: 0.8,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _sectionsAnimationController,
      curve: UIConstants.curveElastic,
    ));
  }

  void _startPageAnimation() async {
    await Future.delayed(const Duration(milliseconds: 300));
    _pageAnimationController.forward();

    await Future.delayed(const Duration(milliseconds: 400));
    _sectionsAnimationController.forward();
  }

  @override
  void dispose() {
    _pageAnimationController.dispose();
    _sectionsAnimationController.dispose();
    super.dispose();
  }

  void _initializeControllers() {
    final sysparameter =
        Provider.of<SystemParamsViewModel>(context, listen: false)
            .systemParamsList;

    schedulerTimerController.text =
        sysparameter['schedulerTime']?.toString() ?? '';
    leaseTaxCodeController.text =
        sysparameter['leaseTaxCode']?.toString() ?? '';
    vesselConfirmationController.text =
        sysparameter['vesselConfProcessLimit']?.toString() ?? '';
    rowToDisplayController.text =
        sysparameter['rowToDisplay']?.toString() ?? '';
    linkToDisplayController.text =
        sysparameter['linkToDisplay']?.toString() ?? '';
    rowToAddController.text = sysparameter['rowToAdd']?.toString() ?? '';
    lovRowToDisplayController.text =
        sysparameter['lovRowToDisplay']?.toString() ?? '';
    lovLinkToDisplayController.text =
        sysparameter['lovLinkToDisplay']?.toString() ?? '';
    oidServerNameController.text =
        sysparameter['oidserverName']?.toString() ?? '';
    oidBaseController.text = sysparameter['oidBase']?.toString() ?? '';
    oidAdminUserController.text =
        sysparameter['oidAdminUser']?.toString() ?? '';
    oidServerPortController.text =
        sysparameter['oidServerPort']?.toString() ?? '';
    userDefaultGroupController.text =
        sysparameter['userDefaultGroup']?.toString() ?? '';
    defaultDepartmentController.text =
        sysparameter['defaultDepartment']?.toString() ?? '';
    defaultPositionController.text =
        sysparameter['defaultPosition']?.toString() ?? '';
    singleChargeController.text =
        sysparameter['singleCharge']?.toString() ?? '';
    firstDayOfWeekController.text =
        sysparameter['firstDayOftheWeek']?.toString() ?? '';
    hourPerShiftController.text =
        sysparameter['hourPerShift']?.toString() ?? '';
    cnBillingFrequencyController.text =
        sysparameter['cnBillingFrequency']?.toString() ?? '';
    billingDepartmentCodeController.text =
        sysparameter['billingDepartmentCode']?.toString() ?? '';
    basePriceListController.text =
        sysparameter['basePriceList']?.toString() ?? '';
    nonContainerServiceController.text =
        sysparameter['nonContainerServiceOrder']?.toString() ?? '';
    ediMaeSchedulerController.text =
        sysparameter['ediMaeSchedulerONOFF']?.toString() ?? '';
    ediSchedulerController.text =
        sysparameter['ediSchedulerONOFF']?.toString() ?? '';
    companynameController.text =
        sysparameter['Company_Display_Name']?.toString() ?? '';
    uploadLogoController.text =
        sysparameter['Company_Logo_Path']?.toString() ?? '';
    uploadLogoNameController.text =
        sysparameter['Company_Logo_Name']?.toString() ?? '';
    uploadLogoPathController.text =
        sysparameter['Company_Logo_Path']?.toString() ?? '';

    isRegistrationAllow = sysparameter['isRegitrationAllowed'] ?? false;
  }

  void _handleOnChanged(String key, String value) {
    formData[key] = value;
  }

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

    return Scaffold(
      backgroundColor: colorScheme.background,
      appBar: ModernAppBar(
        title: 'System Parameters',
        userAvatar: null,
        userName: userName,
        onProfilePressed: () {},
        automaticallyImplyLeading: true,
        onMenuPressed: () {
          Scaffold.of(context).openDrawer();
        },
        actions: [
          IconButton(
            icon: Icon(Icons.arrow_back),
            onPressed: () => Navigator.of(context).pop(),
            tooltip: 'Go Back',
          ),
          const SizedBox(width: UIConstants.spacing8),
        ],
      ),
      drawer: _buildDrawer(context, theme, colorScheme),
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              colorScheme.background,
              colorScheme.surfaceVariant.withOpacity(0.1),
              colorScheme.primaryContainer.withOpacity(0.05),
            ],
          ),
        ),
        child: Stack(
          children: [
            SafeArea(
              child: AnimatedBuilder(
                animation: _pageAnimationController,
                builder: (context, child) {
                  return FadeTransition(
                    opacity: _pageFadeAnimation,
                    child: SlideTransition(
                      position: _pageSlideAnimation,
                      child: SingleChildScrollView(
                        padding: UIConstants.getResponsivePadding(
                          context,
                          mobile: const EdgeInsets.all(UIConstants.spacing24),
                          tablet: const EdgeInsets.all(UIConstants.spacing32),
                          desktop: const EdgeInsets.all(UIConstants.spacing40),
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            _buildHeaderSection(theme, colorScheme),
                            const SizedBox(height: UIConstants.spacing32),
                            AnimatedBuilder(
                              animation: _sectionsAnimationController,
                              builder: (context, child) {
                                return Transform.scale(
                                  scale: _sectionsScaleAnimation.value,
                                  child: Column(
                                    children: [
                                      _buildGeneralSection(),
                                      _buildDisplaySection(),
                                      _buildLOVSection(),
                                      _buildOIDSection(),
                                      _buildUserSection(),
                                      _buildBillingSection(),
                                      _buildEDISection(),
                                      _buildCompanySection(),
                                      _buildLogoSection(),
                                      _buildThemePreviewSection(),
                                      _buildThemeEditorSection(),
                                      const SizedBox(
                                          height: UIConstants.spacing40),
                                      _buildSaveButton(),
                                      const SizedBox(
                                          height: UIConstants.spacing24),
                                    ],
                                  ),
                                );
                              },
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),
            // Non-blocking loading overlays (uploading logo or generating theme)
            Positioned(
              left: 0,
              right: 0,
              top: 0,
              child: Consumer2<SystemParamsViewModel, DynamicThemeProvider>(
                builder: (context, sysVm, dynTheme, _) {
                  final isBusy = sysVm.loading || dynTheme.isLoading;
                  if (!isBusy) return const SizedBox.shrink();
                  return LinearProgressIndicator(
                    minHeight: 3,
                    backgroundColor: Colors.transparent,
                    valueColor: AlwaysStoppedAnimation<Color>(
                        colorScheme.primary.withOpacity(0.8)),
                  );
                },
              ),
            ),
            Positioned(
              left: 0,
              right: 0,
              bottom: UIConstants.spacing16,
              child: Consumer2<SystemParamsViewModel, DynamicThemeProvider>(
                builder: (context, sysVm, dynTheme, _) {
                  final isBusy = sysVm.loading || dynTheme.isLoading;
                  if (!isBusy) return const SizedBox.shrink();
                  return Center(
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: UIConstants.spacing16,
                        vertical: UIConstants.spacing8,
                      ),
                      decoration: BoxDecoration(
                        color: colorScheme.surface.withOpacity(0.95),
                        borderRadius:
                            BorderRadius.circular(UIConstants.radius24),
                        border: Border.all(
                            color: colorScheme.outline.withOpacity(0.2)),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.08),
                            blurRadius: 12,
                            offset: const Offset(0, 6),
                          ),
                        ],
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          SizedBox(
                            width: 16,
                            height: 16,
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                              valueColor: AlwaysStoppedAnimation<Color>(
                                  colorScheme.primary),
                            ),
                          ),
                          const SizedBox(width: UIConstants.spacing8),
                          Text(
                            dynTheme.isLoading
                                ? 'Applying dynamic theme...'
                                : 'Uploading logo...',
                            style: theme.textTheme.bodySmall?.copyWith(
                              color: colorScheme.onSurface,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildHeaderSection(ThemeData theme, ColorScheme colorScheme) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'System Configuration',
          style: theme.textTheme.headlineMedium?.copyWith(
            color: colorScheme.onBackground,
            fontWeight: FontWeight.w700,
          ),
        ),
        const SizedBox(height: UIConstants.spacing8),
        Text(
          'Configure system-wide parameters and settings',
          style: theme.textTheme.bodyLarge?.copyWith(
            color: colorScheme.onSurfaceVariant,
          ),
        ),
      ],
    );
  }

  Widget _buildGeneralSection() {
    return SystemParameterSection(
      title: 'General Settings',
      subtitle: 'Basic system configuration',
      icon: Icons.settings,
      iconColor: AppColorScheme.primary,
      isExpanded: _sectionExpansions['general']!,
      onToggle: () {
        setState(() {
          _sectionExpansions['general'] = !_sectionExpansions['general']!;
        });
      },
      children: [
        _buildModernTextField(
            "Scheduler Timer", schedulerTimerController, Icon(Icons.timer)),
        const SizedBox(height: UIConstants.spacing16),
        _buildModernTextField(
            "Lease Tax Code", leaseTaxCodeController, Icon(Icons.receipt)),
        const SizedBox(height: UIConstants.spacing16),
        _buildModernTextField("Vessel Confirmation",
            vesselConfirmationController, Icon(Icons.confirmation_number)),
        const SizedBox(height: UIConstants.spacing16),
        _buildRegistrationCheckbox(),
      ],
    );
  }

  Widget _buildDisplaySection() {
    return SystemParameterSection(
      title: 'Display Settings',
      subtitle: 'Configure display and pagination',
      icon: Icons.display_settings,
      iconColor: AppColorScheme.secondary,
      isExpanded: _sectionExpansions['display']!,
      onToggle: () {
        setState(() {
          _sectionExpansions['display'] = !_sectionExpansions['display']!;
        });
      },
      children: [
        _buildModernTextField(
            "Row to Display", rowToDisplayController, Icon(Icons.table_rows)),
        const SizedBox(height: UIConstants.spacing16),
        _buildModernTextField(
            "Link to Display", linkToDisplayController, Icon(Icons.link)),
        const SizedBox(height: UIConstants.spacing16),
        _buildModernTextField(
            "Row to Add", rowToAddController, Icon(Icons.add_box)),
      ],
    );
  }

  Widget _buildLOVSection() {
    return SystemParameterSection(
      title: 'LOV Settings',
      subtitle: 'List of Values configuration',
      icon: Icons.list_alt,
      iconColor: AppColorScheme.tertiary,
      isExpanded: _sectionExpansions['lov']!,
      onToggle: () {
        setState(() {
          _sectionExpansions['lov'] = !_sectionExpansions['lov']!;
        });
      },
      children: [
        _buildModernTextField("LOV Row to Display", lovRowToDisplayController,
            Icon(Icons.view_list)),
        const SizedBox(height: UIConstants.spacing16),
        _buildModernTextField("LOV Link to Display", lovLinkToDisplayController,
            Icon(Icons.link_off)),
      ],
    );
  }

  Widget _buildOIDSection() {
    return SystemParameterSection(
      title: 'OID Configuration',
      subtitle: 'Oracle Internet Directory settings',
      icon: Icons.security,
      iconColor: AppColorScheme.warning,
      isExpanded: _sectionExpansions['oid']!,
      onToggle: () {
        setState(() {
          _sectionExpansions['oid'] = !_sectionExpansions['oid']!;
        });
      },
      children: [
        _buildModernTextField(
            "OID Server Name", oidServerNameController, Icon(Icons.dns)),
        const SizedBox(height: UIConstants.spacing16),
        _buildModernTextField(
            "OID Base", oidBaseController, Icon(Icons.foundation)),
        const SizedBox(height: UIConstants.spacing16),
        _buildModernTextField("OID Admin User", oidAdminUserController,
            Icon(Icons.admin_panel_settings)),
        const SizedBox(height: UIConstants.spacing16),
        _buildModernTextField(
            "OID Server Port", oidServerPortController, Icon(Icons.router)),
      ],
    );
  }

  Widget _buildUserSection() {
    return SystemParameterSection(
      title: 'User Defaults',
      subtitle: 'Default user configuration',
      icon: Icons.person_outline,
      iconColor: AppColorScheme.info,
      isExpanded: _sectionExpansions['user']!,
      onToggle: () {
        setState(() {
          _sectionExpansions['user'] = !_sectionExpansions['user']!;
        });
      },
      children: [
        _buildModernTextField("User Default Group", userDefaultGroupController,
            Icon(Icons.group)),
        const SizedBox(height: UIConstants.spacing16),
        _buildModernTextField("Default Department", defaultDepartmentController,
            Icon(Icons.business)),
        const SizedBox(height: UIConstants.spacing16),
        _buildModernTextField("Default Position", defaultPositionController,
            Icon(Icons.work_outline)),
      ],
    );
  }

  Widget _buildBillingSection() {
    return SystemParameterSection(
      title: 'Billing Configuration',
      subtitle: 'Financial and billing settings',
      icon: Icons.payment,
      iconColor: AppColorScheme.success,
      isExpanded: _sectionExpansions['billing']!,
      onToggle: () {
        setState(() {
          _sectionExpansions['billing'] = !_sectionExpansions['billing']!;
        });
      },
      children: [
        _buildModernTextField("Single Charge", singleChargeController,
            Icon(Icons.monetization_on)),
        const SizedBox(height: UIConstants.spacing16),
        _buildModernTextField("First Day of the Week", firstDayOfWeekController,
            Icon(Icons.calendar_today)),
        const SizedBox(height: UIConstants.spacing16),
        _buildModernTextField(
            "Hours Per Shift", hourPerShiftController, Icon(Icons.schedule)),
        const SizedBox(height: UIConstants.spacing16),
        _buildModernTextField("CN Billing Frequency",
            cnBillingFrequencyController, Icon(Icons.repeat)),
        const SizedBox(height: UIConstants.spacing16),
        _buildModernTextField("Billing Department Code",
            billingDepartmentCodeController, Icon(Icons.account_balance)),
        const SizedBox(height: UIConstants.spacing16),
        _buildModernTextField("Base Price List", basePriceListController,
            Icon(Icons.price_check)),
        const SizedBox(height: UIConstants.spacing16),
        _buildModernTextField("Non-Container Service Order",
            nonContainerServiceController, Icon(Icons.inventory)),
      ],
    );
  }

  Widget _buildEDISection() {
    return SystemParameterSection(
      title: 'EDI Configuration',
      subtitle: 'Electronic Data Interchange settings',
      icon: Icons.swap_horiz,
      iconColor: AppColorScheme.warning,
      isExpanded: _sectionExpansions['edi']!,
      onToggle: () {
        setState(() {
          _sectionExpansions['edi'] = !_sectionExpansions['edi']!;
        });
      },
      children: [
        _buildModernTextField("EDI MAE Scheduler", ediMaeSchedulerController,
            Icon(Icons.schedule)),
        const SizedBox(height: UIConstants.spacing16),
        _buildModernTextField(
            "EDI Scheduler", ediSchedulerController, Icon(Icons.sync)),
      ],
    );
  }

  Widget _buildCompanySection() {
    return SystemParameterSection(
      title: 'Company Information',
      subtitle: 'Company details and branding',
      icon: Icons.business,
      iconColor: AppColorScheme.primary,
      isExpanded: _sectionExpansions['company']!,
      onToggle: () {
        setState(() {
          _sectionExpansions['company'] = !_sectionExpansions['company']!;
        });
      },
      children: [
        _buildModernTextField(
            "Company Name", companynameController, Icon(Icons.business)),
      ],
    );
  }

  Widget _buildLogoSection() {
    return SystemParameterSection(
      title: 'Company Logo',
      subtitle: 'Upload and manage company logo',
      icon: Icons.image,
      iconColor: AppColorScheme.tertiary,
      isExpanded: true,
      children: [
        Consumer<SystemParamsViewModel>(
          builder: (context, provider, child) {
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Logo Display and Upload
                ModernImagePicker(
                  label: 'Company Logo',
                  hint: 'Upload your company logo (JPG, PNG, GIF up to 10MB)',
                  imageBytes: provider.profileImageBytes,
                  imageFile: provider.profileImg != null
                      ? File(provider.profileImg!.path)
                      : null,
                  onPickImage: () => provider.pickImg(context),
                  onRemoveImage: () {
                    provider.setImage(null);
                    provider.setProfileImageBytes(null);
                  },
                  isLoading: provider.loading,
                  height: 200,
                  placeholderIcon: Icons.business,
                  placeholderText: 'Upload company logo',
                ),

                const SizedBox(height: UIConstants.spacing16),

                // Theme Status Indicator
                Consumer<DynamicThemeProvider>(
                  builder: (context, dynamicTheme, child) {
                    if (dynamicTheme.isLoading) {
                      return Container(
                        padding: const EdgeInsets.all(UIConstants.spacing12),
                        decoration: BoxDecoration(
                          color: Colors.blue.withOpacity(0.1),
                          borderRadius:
                              BorderRadius.circular(UIConstants.radius8),
                          border:
                              Border.all(color: Colors.blue.withOpacity(0.3)),
                        ),
                        child: Row(
                          children: [
                            SizedBox(
                              width: 16,
                              height: 16,
                              child: CircularProgressIndicator(
                                strokeWidth: 2,
                                valueColor:
                                    AlwaysStoppedAnimation<Color>(Colors.blue),
                              ),
                            ),
                            const SizedBox(width: UIConstants.spacing8),
                            Text(
                              'Generating dynamic theme...',
                              style: TextStyle(
                                color: Colors.blue,
                                fontSize: 12,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                      );
                    } else if (dynamicTheme.isUsingDynamicTheme) {
                      return Container(
                        padding: const EdgeInsets.all(UIConstants.spacing12),
                        decoration: BoxDecoration(
                          color: Colors.green.withOpacity(0.1),
                          borderRadius:
                              BorderRadius.circular(UIConstants.radius8),
                          border:
                              Border.all(color: Colors.green.withOpacity(0.3)),
                        ),
                        child: Row(
                          children: [
                            Icon(
                              Icons.check_circle,
                              color: Colors.green,
                              size: 16,
                            ),
                            const SizedBox(width: UIConstants.spacing8),
                            Text(
                              'Dynamic theme applied! Colors extracted from logo.',
                              style: TextStyle(
                                color: Colors.green,
                                fontSize: 12,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                      );
                    }
                    return const SizedBox.shrink();
                  },
                ),

                const SizedBox(height: UIConstants.spacing16),

                // Upload Button
                if (provider.profileImg != null) ...[
                  SizedBox(
                    width: double.infinity,
                    child: ModernButton(
                      text: 'Upload Logo',
                      type: ModernButtonType.primary,
                      size: ModernButtonSize.medium,
                      icon: Icon(Icons.upload),
                      onPressed: () => provider.uploadLogo(context),
                      isLoading: provider.loading,
                    ),
                  ),

                  const SizedBox(height: UIConstants.spacing12),

                  // Clear Logo Button
                  SizedBox(
                    width: double.infinity,
                    child: ModernButton(
                      text: 'Clear Logo',
                      type: ModernButtonType.outline,
                      size: ModernButtonSize.medium,
                      icon: Icon(Icons.delete_outline),
                      onPressed: () => provider.clearLogo(context),
                      isLoading: provider.loading,
                    ),
                  ),

                  const SizedBox(height: UIConstants.spacing12),

                  // Info Text
                  Container(
                    padding: const EdgeInsets.all(UIConstants.spacing12),
                    decoration: BoxDecoration(
                      color: AppColorScheme.info.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(UIConstants.radius8),
                      border: Border.all(
                        color: AppColorScheme.info.withOpacity(0.3),
                      ),
                    ),
                    child: Row(
                      children: [
                        Icon(
                          Icons.info_outline,
                          color: AppColorScheme.info,
                          size: UIConstants.iconSizeMedium,
                        ),
                        const SizedBox(width: UIConstants.spacing8),
                        Expanded(
                          child: Text(
                            'Theme is applied immediately! Click "Upload Logo" to save the logo permanently to the database. The dynamic theme will work even if upload fails.',
                            style: TextStyle(
                              color: AppColorScheme.info,
                              fontSize: 12,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ] else if (provider.profileImageBytes != null) ...[
                  // Show existing logo with options
                  const SizedBox(height: UIConstants.spacing12),

                  // Upload New Logo Button
                  SizedBox(
                    width: double.infinity,
                    child: ModernButton(
                      text: 'Upload New Logo',
                      type: ModernButtonType.primary,
                      size: ModernButtonSize.medium,
                      icon: Icon(Icons.upload),
                      onPressed: () => provider.pickImg(context),
                      isLoading: provider.loading,
                    ),
                  ),

                  const SizedBox(height: UIConstants.spacing12),

                  // Clear Logo Button
                  SizedBox(
                    width: double.infinity,
                    child: ModernButton(
                      text: 'Remove Logo',
                      type: ModernButtonType.danger,
                      size: ModernButtonSize.medium,
                      icon: Icon(Icons.delete_outline),
                      onPressed: () => provider.clearLogo(context),
                      isLoading: provider.loading,
                    ),
                  ),

                  const SizedBox(height: UIConstants.spacing12),

                  // Info Text for existing logo
                  Container(
                    padding: const EdgeInsets.all(UIConstants.spacing12),
                    decoration: BoxDecoration(
                      color: AppColorScheme.success.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(UIConstants.radius8),
                      border: Border.all(
                        color: AppColorScheme.success.withOpacity(0.3),
                      ),
                    ),
                    child: Row(
                      children: [
                        Icon(
                          Icons.check_circle_outline,
                          color: AppColorScheme.success,
                          size: UIConstants.iconSizeMedium,
                        ),
                        const SizedBox(width: UIConstants.spacing8),
                        Expanded(
                          child: Text(
                            'Company logo is already uploaded and saved in the system. You can upload a new one or remove the existing logo.',
                            style: TextStyle(
                              color: AppColorScheme.success,
                              fontSize: 12,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ],
            );
          },
        ),
      ],
    );
  }

  Widget _buildThemePreviewSection() {
    return SystemParameterSection(
      title: 'Theme Preview',
      subtitle: 'Preview the current theme colors',
      icon: Icons.palette,
      iconColor: AppColorScheme.primary,
      isExpanded: true,
      children: [
        const ThemePreview(),
      ],
    );
  }

  Widget _buildThemeEditorSection() {
    return SystemParameterSection(
      title: 'Theme Editor',
      subtitle: 'Manually override primary, secondary, tertiary',
      icon: Icons.tune,
      iconColor: AppColorScheme.secondary,
      isExpanded: true,
      children: [
        Consumer<DynamicThemeProvider>(
          builder: (context, dynamicTheme, child) {
            final theme = Theme.of(context);
            final cs = theme.colorScheme;
            final effectivePrimary = dynamicTheme.useManualOverride
                ? (dynamicTheme.manualPrimary ?? cs.primary)
                : cs.primary;
            final effectiveSecondary = dynamicTheme.useManualOverride
                ? (dynamicTheme.manualSecondary ?? effectivePrimary)
                : cs.secondary;
            final effectiveTertiary = dynamicTheme.useManualOverride
                ? (dynamicTheme.manualTertiary ?? effectiveSecondary)
                : cs.tertiary;

            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      'Enable Manual Override',
                      style: theme.textTheme.titleMedium?.copyWith(
                        color: cs.onSurface,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    Switch(
                      value: dynamicTheme.useManualOverride,
                      onChanged: (v) {
                        if (v) {
                          dynamicTheme.enableManualOverride(
                            primary: effectivePrimary,
                            secondary: effectiveSecondary,
                            tertiary: effectiveTertiary,
                          );
                        } else {
                          dynamicTheme.disableManualOverride();
                        }
                      },
                      activeColor: cs.primary,
                    ),
                  ],
                ),
                const SizedBox(height: UIConstants.spacing12),
                _buildColorRow(
                  label: 'Primary',
                  color: effectivePrimary,
                  onPick: () async {
                    final picked = await _pickColor(context, effectivePrimary);
                    if (picked != null) {
                      dynamicTheme.setManualColors(primary: picked);
                    }
                  },
                ),
                const SizedBox(height: UIConstants.spacing12),
                _buildColorRow(
                  label: 'Secondary',
                  color: effectiveSecondary,
                  onPick: () async {
                    final picked =
                        await _pickColor(context, effectiveSecondary);
                    if (picked != null) {
                      dynamicTheme.setManualColors(secondary: picked);
                    }
                  },
                ),
                const SizedBox(height: UIConstants.spacing12),
                _buildColorRow(
                  label: 'Tertiary',
                  color: effectiveTertiary,
                  onPick: () async {
                    final picked = await _pickColor(context, effectiveTertiary);
                    if (picked != null) {
                      dynamicTheme.setManualColors(tertiary: picked);
                    }
                  },
                ),
                const SizedBox(height: UIConstants.spacing16),
                Row(
                  children: [
                    Expanded(
                      child: ModernButton(
                        text: 'Reset to Logo Colors',
                        type: ModernButtonType.outline,
                        size: ModernButtonSize.medium,
                        icon: Icon(Icons.refresh),
                        onPressed: () {
                          dynamicTheme.disableManualOverride();
                        },
                      ),
                    ),
                    const SizedBox(width: UIConstants.spacing12),
                    Expanded(
                      child: ModernButton(
                        text: 'Reset to Default',
                        type: ModernButtonType.danger,
                        size: ModernButtonSize.medium,
                        icon: Icon(Icons.settings_backup_restore),
                        onPressed: () {
                          dynamicTheme.resetToDefaultTheme();
                        },
                      ),
                    ),
                  ],
                ),
              ],
            );
          },
        ),
      ],
    );
  }

  Widget _buildColorRow(
      {required String label,
      required Color color,
      required Future<Color?> Function() onPick}) {
    final theme = Theme.of(context);
    final cs = theme.colorScheme;
    return Container(
      padding: const EdgeInsets.all(UIConstants.spacing12),
      decoration: BoxDecoration(
        color: cs.surfaceVariant.withOpacity(0.3),
        borderRadius: BorderRadius.circular(UIConstants.radius12),
        border: Border.all(color: cs.outline.withOpacity(0.2)),
      ),
      child: Row(
        children: [
          Container(
            width: 28,
            height: 28,
            decoration: BoxDecoration(
              color: color,
              borderRadius: BorderRadius.circular(6),
              border: Border.all(color: Colors.black.withOpacity(0.1)),
            ),
          ),
          const SizedBox(width: UIConstants.spacing12),
          Expanded(
            child: Text(
              label,
              style: theme.textTheme.titleMedium?.copyWith(
                color: cs.onSurface,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
          ModernButton(
            text: 'Edit',
            type: ModernButtonType.text,
            size: ModernButtonSize.small,
            onPressed: () async {
              await onPick();
            },
          )
        ],
      ),
    );
  }

  Future<Color?> _pickColor(BuildContext context, Color current) async {
    final swatches = <Color>[
      const Color(0xFF2563EB),
      const Color(0xFF7C3AED),
      const Color(0xFF0D9488),
      const Color(0xFFEF4444),
      const Color(0xFFF59E0B),
      const Color(0xFF10B981),
      const Color(0xFF3B82F6),
      const Color(0xFF8B5CF6),
      const Color(0xFF14B8A6),
      const Color(0xFF111827),
      const Color(0xFF374151),
      const Color(0xFFF3F4F6),
    ];
    Color? selected;
    await showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('Pick a color'),
          content: SizedBox(
            width: 320,
            child: GridView.builder(
              shrinkWrap: true,
              itemCount: swatches.length,
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 6,
                mainAxisSpacing: 8,
                crossAxisSpacing: 8,
              ),
              itemBuilder: (context, index) {
                final c = swatches[index];
                return InkWell(
                  onTap: () {
                    selected = c;
                    Navigator.of(context).pop();
                  },
                  child: Container(
                    decoration: BoxDecoration(
                      color: c,
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(color: Colors.black.withOpacity(0.1)),
                    ),
                  ),
                );
              },
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('Cancel'),
            ),
          ],
        );
      },
    );
    return selected;
  }

  Widget _buildModernTextField(
      String label, TextEditingController controller, Widget icon) {
    return ModernTextField(
      label: label,
      controller: controller,
      prefixIcon: icon,
      onChanged: (value) => _handleOnChanged(label, value),
      validator: (value) {
        if (value == null || value.isEmpty) {
          return 'This field is required';
        }
        return null;
      },
    );
  }

  Widget _buildRegistrationCheckbox() {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;

    return Container(
      padding: const EdgeInsets.all(UIConstants.spacing16),
      decoration: BoxDecoration(
        color: colorScheme.surfaceVariant.withOpacity(0.3),
        borderRadius: BorderRadius.circular(UIConstants.radius12),
        border: Border.all(
          color: colorScheme.outline.withOpacity(0.2),
        ),
      ),
      child: Row(
        children: [
          Icon(
            Icons.app_registration,
            color: colorScheme.primary,
            size: UIConstants.iconSizeMedium,
          ),
          const SizedBox(width: UIConstants.spacing12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'User Registration',
                  style: theme.textTheme.titleMedium?.copyWith(
                    color: colorScheme.onSurface,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                const SizedBox(height: UIConstants.spacing4),
                Text(
                  'Allow new users to register accounts',
                  style: theme.textTheme.bodySmall?.copyWith(
                    color: colorScheme.onSurfaceVariant,
                  ),
                ),
              ],
            ),
          ),
          Switch(
            value: isRegistrationAllow,
            onChanged: (bool value) {
              setState(() {
                isRegistrationAllow = value;
              });
              _handleOnChanged(
                  'Registration Allowed', isRegistrationAllow.toString());
            },
            activeColor: colorScheme.primary,
          ),
        ],
      ),
    );
  }

  Widget _buildSaveButton() {
    return Consumer<SystemParamsViewModel>(
      builder: (context, provider, child) {
        return SizedBox(
          width: double.infinity,
          child: ModernButton(
            text: 'Save Configuration',
            type: ModernButtonType.primary,
            size: ModernButtonSize.large,
            icon: Icon(Icons.save),
            onPressed: () {
              print(formData);
              provider.updateSystemParams(formData);
            },
            isLoading: provider.loading,
          ),
        );
      },
    );
  }

  Widget _buildDrawer(
      BuildContext context, ThemeData theme, ColorScheme colorScheme) {
    return Drawer(
      backgroundColor: colorScheme.surface,
      child: Column(
        children: [
          // Header
          Container(
            padding: const EdgeInsets.all(UIConstants.spacing24),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  colorScheme.primary,
                  colorScheme.secondary,
                  colorScheme.tertiary,
                ],
              ),
            ),
            child: SafeArea(
              child: Column(
                children: [
                  CircleAvatar(
                    radius: UIConstants.logoSizeLarge / 2,
                    backgroundColor: Colors.white.withOpacity(0.2),
                    child: Icon(
                      Icons.person,
                      size: UIConstants.iconSizeLarge,
                      color: Colors.white,
                    ),
                  ),
                  const SizedBox(height: UIConstants.spacing16),
                  Text(
                    UserManager().userName ?? 'User',
                    style: theme.textTheme.titleLarge?.copyWith(
                      color: Colors.white,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  Text(
                    UserManager().email ?? 'user@example.com',
                    style: theme.textTheme.bodyMedium?.copyWith(
                      color: Colors.white.withOpacity(0.8),
                    ),
                  ),
                ],
              ),
            ),
          ),

          // Navigation Items
          Expanded(
            child: ListView(
              padding: EdgeInsets.zero,
              children: [
                _buildDrawerItem(
                    context, theme, colorScheme, Icons.home, 'Home', () {
                  Navigator.of(context).pushReplacementNamed('/');
                }),
                _buildDrawerItem(context, theme, colorScheme, Icons.settings,
                    'System Parameters', () {
                  Navigator.of(context)
                      .pushReplacementNamed('/system_parameters');
                }, isSelected: true),
                _buildDrawerItem(
                    context, theme, colorScheme, Icons.people, 'Users', () {
                  Navigator.of(context).pushReplacementNamed('/users');
                }),
                _buildDrawerItem(
                    context, theme, colorScheme, Icons.security, 'Roles', () {
                  Navigator.of(context).pushReplacementNamed('/roles');
                }),
                _buildDrawerItem(
                    context, theme, colorScheme, Icons.business, 'Departments',
                    () {
                  Navigator.of(context).pushReplacementNamed('/departments');
                }),
                _buildDrawerItem(
                    context, theme, colorScheme, Icons.work, 'Positions', () {
                  Navigator.of(context).pushReplacementNamed('/positions');
                }),
                _buildDrawerItem(context, theme, colorScheme,
                    Icons.monetization_on, 'Charges', () {
                  Navigator.of(context).pushReplacementNamed('/charges');
                }),
                _buildDrawerItem(
                    context, theme, colorScheme, Icons.calendar_today, 'Weeks',
                    () {
                  Navigator.of(context).pushReplacementNamed('/weeks');
                }),
                _buildDrawerItem(
                    context, theme, colorScheme, Icons.schedule, 'Shifts', () {
                  Navigator.of(context).pushReplacementNamed('/shifts');
                }),
                _buildDrawerItem(
                    context, theme, colorScheme, Icons.payment, 'Billing', () {
                  Navigator.of(context).pushReplacementNamed('/billing');
                }),
                _buildDrawerItem(context, theme, colorScheme, Icons.swap_horiz,
                    'EDI Settings', () {
                  Navigator.of(context).pushReplacementNamed('/edi_settings');
                }),
                _buildDrawerItem(context, theme, colorScheme,
                    Icons.business_center, 'Company', () {
                  Navigator.of(context).pushReplacementNamed('/company');
                }),
                _buildDrawerItem(
                    context, theme, colorScheme, Icons.image, 'Logo', () {
                  Navigator.of(context).pushReplacementNamed('/logo');
                }),
              ],
            ),
          ),

          // Logout Section
          Container(
            padding: const EdgeInsets.all(UIConstants.spacing24),
            child: ModernButton(
              text: 'Logout',
              type: ModernButtonType.danger,
              size: ModernButtonSize.medium,
              icon: Icon(Icons.logout),
              onPressed: () async {
                await UserManager().clearUser();
                if (context.mounted) {
                  Navigator.pushReplacementNamed(context, '/splash');
                }
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDrawerItem(
    BuildContext context,
    ThemeData theme,
    ColorScheme colorScheme,
    IconData icon,
    String title,
    VoidCallback onTap, {
    bool isSelected = false,
  }) {
    return Container(
      margin: const EdgeInsets.symmetric(
        horizontal: UIConstants.spacing16,
        vertical: UIConstants.spacing4,
      ),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(UIConstants.radius12),
        color: isSelected
            ? colorScheme.primaryContainer.withOpacity(0.3)
            : Colors.transparent,
      ),
      child: ListTile(
        leading: Container(
          padding: const EdgeInsets.all(UIConstants.spacing8),
          decoration: BoxDecoration(
            color: isSelected
                ? colorScheme.primaryContainer
                : colorScheme.surfaceVariant.withOpacity(0.3),
            borderRadius: BorderRadius.circular(UIConstants.radius8),
          ),
          child: Icon(
            icon,
            color: isSelected
                ? colorScheme.onPrimaryContainer
                : colorScheme.onSurfaceVariant,
            size: UIConstants.iconSizeMedium,
          ),
        ),
        title: Text(
          title,
          style: theme.textTheme.titleMedium?.copyWith(
            color: isSelected ? colorScheme.onSurface : colorScheme.onSurface,
            fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500,
          ),
        ),
        onTap: onTap,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(UIConstants.radius12),
        ),
      ),
    );
  }
}
