import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';
import '../../providers/user_provider.dart';

class CycleSettingsScreen extends ConsumerStatefulWidget {
  const CycleSettingsScreen({super.key});

  @override
  ConsumerState<CycleSettingsScreen> createState() =>
      _CycleSettingsScreenState();
}

class _CycleSettingsScreenState extends ConsumerState<CycleSettingsScreen> {
  final _formKey = GlobalKey<FormState>();
  late TextEditingController _cycleLengthController;
  late TextEditingController _periodLengthController;
  DateTime? _lastPeriodStartDate;
  bool _isIrregularCycle = false;
  bool _isPadTrackingEnabled = false;

  @override
  void initState() {
    super.initState();
    final userProfile = ref.read(userProfileProvider);
    _cycleLengthController = TextEditingController(
        text: userProfile?.averageCycleLength.toString() ?? '28');
    _periodLengthController = TextEditingController(
        text: userProfile?.averagePeriodLength.toString() ?? '5');
    _lastPeriodStartDate = userProfile?.lastPeriodStartDate;
    _isIrregularCycle = userProfile?.isIrregularCycle ?? false;
    _isPadTrackingEnabled = userProfile?.isPadTrackingEnabled ?? false;
  }

  @override
  void dispose() {
    _cycleLengthController.dispose();
    _periodLengthController.dispose();
    super.dispose();
  }

  void _saveSettings() {
    if (_formKey.currentState!.validate()) {
      final userProfile = ref.read(userProfileProvider);
      if (userProfile != null) {
        final updatedProfile = userProfile.copyWith(
          averageCycleLength: int.tryParse(_cycleLengthController.text) ??
              userProfile.averageCycleLength,
          averagePeriodLength: int.tryParse(_periodLengthController.text) ??
              userProfile.averagePeriodLength,
          lastPeriodStartDate: _lastPeriodStartDate,
          isIrregularCycle: _isIrregularCycle,
          isPadTrackingEnabled: _isPadTrackingEnabled,
        );
        ref.read(userProfileProvider.notifier).updateProfile(updatedProfile);
        Navigator.of(context).pop();
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Cycle settings saved!')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Cycle Settings'),
      ),
      body: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(24.0),
          children: [
            TextFormField(
              controller: _cycleLengthController,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                labelText: 'Average Cycle Length (days)',
                hintText: 'e.g., 28',
              ),
              validator: (value) {
                if (value == null || int.tryParse(value) == null) {
                  return 'Please enter a valid number';
                }
                return null;
              },
            ),
            const SizedBox(height: 24),
            TextFormField(
              controller: _periodLengthController,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                labelText: 'Average Period Length (days)',
                hintText: 'e.g., 5',
              ),
              validator: (value) {
                if (value == null || int.tryParse(value) == null) {
                  return 'Please enter a valid number';
                }
                return null;
              },
            ),
            const SizedBox(height: 24),
            ListTile(
              contentPadding: EdgeInsets.zero,
              title: const Text('Last Period Start Date'),
              subtitle: Text(_lastPeriodStartDate == null
                  ? 'Not set'
                  : DateFormat.yMMMMd().format(_lastPeriodStartDate!)),
              trailing: const Icon(Icons.calendar_today),
              onTap: () async {
                final pickedDate = await showDatePicker(
                  context: context,
                  initialDate: _lastPeriodStartDate ?? DateTime.now(),
                  firstDate: DateTime(DateTime.now().year - 1),
                  lastDate: DateTime.now(),
                );
                if (pickedDate != null) {
                  setState(() {
                    _lastPeriodStartDate = pickedDate;
                  });
                }
              },
            ),
            const Divider(),
            SwitchListTile(
              contentPadding: EdgeInsets.zero,
              title: const Text('My cycle is irregular'),
              value: _isIrregularCycle,
              onChanged: (value) {
                setState(() {
                  _isIrregularCycle = value;
                });
              },
            ),
            const Divider(),
            SwitchListTile(
              contentPadding: EdgeInsets.zero,
              title: const Text('Enable Pad Tracking'),
              subtitle:
                  const Text('Track supply usage and receive change reminders'),
              value: _isPadTrackingEnabled,
              onChanged: (value) {
                setState(() {
                  _isPadTrackingEnabled = value;
                });
              },
            ),
            const SizedBox(height: 40),
            ElevatedButton(
              onPressed: _saveSettings,
              child: const Text('Save Settings'),
            )
          ],
        ),
      ),
    );
  }
}
