import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../models/models.dart';
import '../storage/local_storage.dart';
import '../theme.dart';
import 'about_screen.dart';
import 'lifestyle_screen.dart';

class BehavioralScreen extends StatefulWidget {
  final UserProfile profile;
  final bool readOnly;
  final BehavioralInputs? initialBehaviors;

  const BehavioralScreen({
    super.key,
    required this.profile,
    this.readOnly = false,
    this.initialBehaviors,
  });

  @override
  State<BehavioralScreen> createState() => _BehavioralScreenState();
}

class _BehavioralScreenState extends State<BehavioralScreen> {
  SmokingStatus _smoking = SmokingStatus.never;
  int _cigarettesPerDay = 0;
  AlcoholLevel _alcohol = AlcoholLevel.none;
  double _sleepHours = 7.5;
  bool _sleepConsistent = true;
  ActivityLevel _activity = ActivityLevel.moderate;

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

  Future<void> _loadInitialData() async {
    // If initial behaviors provided, use those
    if (widget.initialBehaviors != null) {
      _applyBehaviors(widget.initialBehaviors!);
      return;
    }

    // Otherwise load from storage
    final behaviors = await LocalStorage.getBehaviors();
    if (behaviors != null) {
      _applyBehaviors(behaviors);
    }
  }

  void _applyBehaviors(BehavioralInputs behaviors) {
    setState(() {
      _smoking = behaviors.smoking;
      _cigarettesPerDay = behaviors.cigarettesPerDay;
      _alcohol = behaviors.alcohol;
      _sleepHours = behaviors.sleepHours;
      _sleepConsistent = behaviors.sleepConsistent;
      _activity = behaviors.activity;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.readOnly ? 'Habits (View Only)' : 'Habits'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.pop(context),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.info_outline),
            onPressed: () => Navigator.push(
              context,
              MaterialPageRoute(builder: (_) => const AboutScreen()),
            ),
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(24),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Daily Habits',
              style: Theme.of(context).textTheme.headlineSmall,
            ),
            const SizedBox(height: 8),
            Text(
              'Substances, sleep, and activity levels.',
              style: Theme.of(context).textTheme.bodyMedium,
            ),
            const SizedBox(height: 32),

            // Smoking
            _buildSectionLabel('Smoking'),
            const SizedBox(height: 12),
            _buildSmokingSelector(),
            if (_smoking == SmokingStatus.current) ...[
              const SizedBox(height: 16),
              _buildCigarettesSlider(),
            ],
            const SizedBox(height: 28),

            // Alcohol
            _buildSectionLabel('Alcohol'),
            const SizedBox(height: 12),
            _buildAlcoholSelector(),
            const SizedBox(height: 28),

            // Sleep
            _buildSectionLabel('Sleep'),
            const SizedBox(height: 12),
            _buildSleepSlider(),
            const SizedBox(height: 12),
            _buildSleepConsistentToggle(),
            const SizedBox(height: 28),

            // Physical Activity
            _buildSectionLabel('Physical Activity'),
            const SizedBox(height: 12),
            _buildActivitySelector(),
            const SizedBox(height: 40),

            // Continue button (hidden in readOnly mode)
            if (!widget.readOnly)
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: _continue,
                  child: const Text('Continue'),
                ),
              ),
            const SizedBox(height: 16),
          ],
        ),
      ),
    );
  }

  Widget _buildSectionLabel(String label) {
    return Text(
      label,
      style: Theme.of(context).textTheme.labelLarge,
    );
  }

  Widget _buildSmokingSelector() {
    return _buildSegmentedControl<SmokingStatus>(
      value: _smoking,
      options: [
        (SmokingStatus.never, 'Never'),
        (SmokingStatus.former, 'Former'),
        (SmokingStatus.current, 'Current'),
      ],
      onChanged: widget.readOnly ? null : (value) => setState(() => _smoking = value),
    );
  }

  Widget _buildCigarettesSlider() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Cigarettes per day',
          style: Theme.of(context).textTheme.bodyMedium,
        ),
        const SizedBox(height: 8),
        Row(
          children: [
            Expanded(
              child: Slider(
                value: _cigarettesPerDay.toDouble(),
                min: 1,
                max: 40,
                divisions: 39,
                onChanged: widget.readOnly
                    ? null
                    : (value) {
                        if (value.round() == 20 && _cigarettesPerDay != 20) {
                          HapticFeedback.mediumImpact();
                        }
                        setState(() => _cigarettesPerDay = value.round());
                      },
              ),
            ),
            SizedBox(
              width: 50,
              child: Text(
                '$_cigarettesPerDay',
                style: Theme.of(context).textTheme.headlineMedium,
                textAlign: TextAlign.center,
              ),
            ),
          ],
        ),
        Text(
          _cigarettesPerDay <= 20
              ? '${(_cigarettesPerDay / 20).toStringAsFixed(1)} pack/day'
              : '${(_cigarettesPerDay / 20).toStringAsFixed(1)} packs/day',
          style: Theme.of(context).textTheme.bodySmall,
        ),
      ],
    );
  }

  Widget _buildAlcoholSelector() {
    return _buildSegmentedControl<AlcoholLevel>(
      value: _alcohol,
      options: [
        (AlcoholLevel.none, 'None'),
        (AlcoholLevel.light, '1-7/wk'),
        (AlcoholLevel.moderate, '8-14'),
        (AlcoholLevel.heavy, '15-21'),
        (AlcoholLevel.veryHeavy, '21+'),
      ],
      onChanged: widget.readOnly ? null : (value) => setState(() => _alcohol = value),
    );
  }

  Widget _buildSleepSlider() {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              'Average hours per night',
              style: Theme.of(context).textTheme.bodyMedium,
            ),
            Text(
              _sleepHours.toStringAsFixed(1),
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
        Slider(
          value: _sleepHours,
          min: 4,
          max: 12,
          divisions: 16,
          onChanged: widget.readOnly
              ? null
              : (value) => setState(() => _sleepHours = value),
        ),
      ],
    );
  }

  Widget _buildSleepConsistentToggle() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          'Consistent schedule',
          style: Theme.of(context).textTheme.bodyLarge,
        ),
        Switch(
          value: _sleepConsistent,
          onChanged: widget.readOnly
              ? null
              : (value) => setState(() => _sleepConsistent = value),
        ),
      ],
    );
  }

  Widget _buildActivitySelector() {
    return _buildSegmentedControl<ActivityLevel>(
      value: _activity,
      options: [
        (ActivityLevel.sedentary, 'Sedentary'),
        (ActivityLevel.light, 'Light'),
        (ActivityLevel.moderate, 'Moderate'),
        (ActivityLevel.high, 'High'),
      ],
      onChanged: widget.readOnly ? null : (value) => setState(() => _activity = value),
    );
  }

  Widget _buildSegmentedControl<T>({
    required T value,
    required List<(T, String)> options,
    required ValueChanged<T>? onChanged,
  }) {
    return Container(
      decoration: BoxDecoration(
        color: AppColors.surfaceVariant,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        children: options.map((option) {
          final isSelected = value == option.$1;
          return Expanded(
            child: GestureDetector(
              onTap: onChanged == null ? null : () => onChanged(option.$1),
              child: Container(
                padding: const EdgeInsets.symmetric(vertical: 12),
                decoration: BoxDecoration(
                  color: isSelected ? AppColors.primary : Colors.transparent,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Text(
                  option.$2,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w600,
                    color: isSelected ? Colors.white : AppColors.textSecondary,
                  ),
                ),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  void _continue() {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (_) => LifestyleScreen(
          profile: widget.profile,
          smoking: _smoking,
          cigarettesPerDay: _cigarettesPerDay,
          alcohol: _alcohol,
          sleepHours: _sleepHours,
          sleepConsistent: _sleepConsistent,
          activity: _activity,
        ),
      ),
    );
  }

}
