import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../theme/app_theme.dart';
import '../../providers/user_provider.dart';

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

  @override
  ConsumerState<PadSettingsDialog> createState() => _PadSettingsDialogState();
}

class _PadSettingsDialogState extends ConsumerState<PadSettingsDialog> {
  bool _isTrackingEnabled = false;
  int _typicalFlow = 2; // Mediumish
  int _padAbsorbency = 3; // Regular

  // Inventory State
  int _padInventoryCount = 0;
  int _lowInventoryThreshold = 5;
  bool _isAutoInventoryEnabled = true;

  final TextEditingController _brandController = TextEditingController();

  @override
  void initState() {
    super.initState();
    final user = ref.read(userProfileProvider);
    if (user != null) {
      _isTrackingEnabled = user.isPadTrackingEnabled;
      _typicalFlow = user.typicalFlowIntensity ?? 2;
      _padAbsorbency = user.padAbsorbency ?? 3;

      // Init Inventory
      _padInventoryCount = user.padInventoryCount;
      _lowInventoryThreshold = user.lowInventoryThreshold;
      _isAutoInventoryEnabled = user.isAutoInventoryEnabled;

      _brandController.text = user.padBrand ?? '';
    }
  }

  @override
  void dispose() {
    _brandController.dispose();
    super.dispose();
  }

  Future<void> _saveSettings() async {
    final user = ref.read(userProfileProvider);
    if (user != null) {
      final updatedProfile = user.copyWith(
        isPadTrackingEnabled: _isTrackingEnabled,
        typicalFlowIntensity: _typicalFlow,
        padAbsorbency: _padAbsorbency,
        padInventoryCount: _padInventoryCount,
        lowInventoryThreshold: _lowInventoryThreshold,
        isAutoInventoryEnabled: _isAutoInventoryEnabled,
        lastInventoryUpdate: (_padInventoryCount != (user.padInventoryCount))
            ? DateTime.now()
            : user.lastInventoryUpdate,
        padBrand: _brandController.text.trim().isEmpty
            ? null
            : _brandController.text.trim(),
      );

      await ref
          .read(userProfileProvider.notifier)
          .updateProfile(updatedProfile);

      if (mounted) {
        Navigator.pop(context);
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Preferences saved')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
      child: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Period Supplies',
              style: GoogleFonts.outfit(
                fontSize: 20,
                fontWeight: FontWeight.w600,
                color: AppColors.navyBlue,
              ),
            ),
            const SizedBox(height: 24),

            // Toggle
            Row(
              children: [
                Expanded(
                  child: Text(
                    'Enable Pad Tracking',
                    style: GoogleFonts.outfit(
                      fontSize: 16,
                      color: AppColors.charcoal,
                    ),
                  ),
                ),
                Switch(
                  value: _isTrackingEnabled,
                  onChanged: (val) => setState(() => _isTrackingEnabled = val),
                  activeThumbColor: AppColors.menstrualPhase,
                ),
              ],
            ),

            if (_isTrackingEnabled) ...[
              const Divider(height: 32),

              // Typical Flow
              Text(
                'Typical Flow Intensity',
                style: GoogleFonts.outfit(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                  color: AppColors.warmGray,
                ),
              ),
              const SizedBox(height: 8),
              Row(
                children: [
                  Text('Light',
                      style: GoogleFonts.outfit(
                          fontSize: 12, color: AppColors.warmGray)),
                  Expanded(
                    child: Slider(
                      value: _typicalFlow.toDouble(),
                      min: 1,
                      max: 5,
                      divisions: 4,
                      activeColor: AppColors
                          .menstrualPhase, // Slider still uses activeColor in many versions, check specifically.
                      // If it's SwitchListTile, it's activeColor, Slider is activeColor.
                      // Actually, let's keep it as is if it's not deprecated for Slider.

                      onChanged: (val) =>
                          setState(() => _typicalFlow = val.round()),
                    ),
                  ),
                  Text('Heavy',
                      style: GoogleFonts.outfit(
                          fontSize: 12, color: AppColors.warmGray)),
                ],
              ),
              Center(
                child: Text('$_typicalFlow/5',
                    style: GoogleFonts.outfit(
                        fontWeight: FontWeight.bold,
                        color: AppColors.menstrualPhase)),
              ),

              const SizedBox(height: 20),

              // Pad Absorbency
              Text(
                'Pad Absorbency/Capacity',
                style: GoogleFonts.outfit(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                  color: AppColors.warmGray,
                ),
              ),
              const SizedBox(height: 4),
              Text(
                'Regular(3), Super(4), Overnight(5)',
                style: GoogleFonts.outfit(
                    fontSize: 12,
                    color: AppColors.warmGray.withValues(alpha: 0.8)),
              ),
              Row(
                children: [
                  Text('Low',
                      style: GoogleFonts.outfit(
                          fontSize: 12, color: AppColors.warmGray)),
                  Expanded(
                    child: Slider(
                      value: _padAbsorbency.toDouble(),
                      min: 1,
                      max: 5,
                      divisions: 4,
                      activeColor: AppColors.menstrualPhase,
                      onChanged: (val) =>
                          setState(() => _padAbsorbency = val.round()),
                    ),
                  ),
                  Text('High',
                      style: GoogleFonts.outfit(
                          fontSize: 12, color: AppColors.warmGray)),
                ],
              ),
              Center(
                child: Text('$_padAbsorbency/5',
                    style: GoogleFonts.outfit(
                        fontWeight: FontWeight.bold,
                        color: AppColors.menstrualPhase)),
              ),

              const SizedBox(height: 20),

              // Brand
              Text(
                'Preferred Brand',
                style: GoogleFonts.outfit(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                  color: AppColors.warmGray,
                ),
              ),
              const SizedBox(height: 8),
              TextField(
                controller: _brandController,
                decoration: InputDecoration(
                  hintText: 'e.g., Always Infinity, Cora, Period Undies...',
                  filled: true,
                  fillColor: AppColors.warmCream.withValues(alpha: 0.5),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                    borderSide: BorderSide.none,
                  ),
                  contentPadding:
                      const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                ),
              ),

              const SizedBox(height: 20),
              const Divider(),
              const SizedBox(height: 16),

              // Inventory Management Header
              Row(
                children: [
                  const Icon(Icons.inventory_2_outlined,
                      size: 20, color: AppColors.navyBlue),
                  const SizedBox(width: 8),
                  Text(
                    'Inventory Tracking',
                    style: GoogleFonts.outfit(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color: AppColors.navyBlue,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 16),

              // Current Count
              Row(
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          'Current Stock',
                          style: GoogleFonts.outfit(
                              fontWeight: FontWeight.w500,
                              color: AppColors.warmGray),
                        ),
                        Text(
                          'Pad Inventory',
                          style: GoogleFonts.outfit(
                              fontSize: 12,
                              color: AppColors.warmGray.withValues(alpha: 0.8)),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    decoration: BoxDecoration(
                      color: AppColors.warmCream.withValues(alpha: 0.5),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Row(
                      children: [
                        IconButton(
                          icon: const Icon(Icons.remove,
                              size: 20, color: AppColors.navyBlue),
                          onPressed: () {
                            if (_padInventoryCount > 0) {
                              setState(() => _padInventoryCount--);
                            }
                          },
                        ),
                        Text(
                          '$_padInventoryCount',
                          style: GoogleFonts.outfit(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                              color: AppColors.navyBlue),
                        ),
                        IconButton(
                          icon: const Icon(Icons.add,
                              size: 20, color: AppColors.navyBlue),
                          onPressed: () => setState(() => _padInventoryCount++),
                        ),
                      ],
                    ),
                  ),
                ],
              ),

              const SizedBox(height: 16),

              // Low Stock Threshold
              Row(
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          'Low Stock Alert',
                          style: GoogleFonts.outfit(
                              fontWeight: FontWeight.w500,
                              color: AppColors.warmGray),
                        ),
                        Text(
                          'Warn when below $_lowInventoryThreshold',
                          style: GoogleFonts.outfit(
                              fontSize: 12,
                              color: AppColors.warmGray.withValues(alpha: 0.8)),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(
                    width: 120,
                    child: Slider(
                      value: _lowInventoryThreshold.toDouble(),
                      min: 1,
                      max: 20,
                      divisions: 19,
                      activeColor: AppColors.rose,
                      onChanged: (val) =>
                          setState(() => _lowInventoryThreshold = val.round()),
                    ),
                  ),
                ],
              ),

              // Auto Deduct Toggle
              SwitchListTile(
                contentPadding: EdgeInsets.zero,
                title: Text(
                  'Auto-deduct on Log',
                  style: GoogleFonts.outfit(
                      fontWeight: FontWeight.w500, color: AppColors.charcoal),
                ),
                subtitle: Text(
                  'Reduce count when you log a pad',
                  style: GoogleFonts.outfit(
                      fontSize: 12, color: AppColors.warmGray),
                ),
                value: _isAutoInventoryEnabled,
                onChanged: (val) =>
                    setState(() => _isAutoInventoryEnabled = val),
                activeThumbColor: AppColors.menstrualPhase,
              ),
            ],

            const SizedBox(height: 32),

            // Buttons
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  child: Text(
                    'Cancel',
                    style: GoogleFonts.outfit(color: AppColors.warmGray),
                  ),
                ),
                const SizedBox(width: 8),
                ElevatedButton(
                  onPressed: _saveSettings,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: AppColors.navyBlue,
                    foregroundColor: Colors.white,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12)),
                  ),
                  child: const Text('Save'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
