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

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

  @override
  ConsumerState<SharingSettingsScreen> createState() =>
      _SharingSettingsScreenState();
}

class _SharingSettingsScreenState extends ConsumerState<SharingSettingsScreen> {
  final _partnerIdController = TextEditingController();
  bool _isLoading = false;
  String? _errorText;

  @override
  void initState() {
    super.initState();
    final user = ref.read(userProfileProvider);
    if (user != null && user.partnerId != null) {
      _partnerIdController.text = user.partnerId!;
    }
  }

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

  Future<void> _savePartnerId() async {
    final input = _partnerIdController.text.trim();
    if (input.isEmpty) return;

    final user = ref.read(userProfileProvider);
    if (user != null) {
      setState(() {
        _isLoading = true;
        _errorText = null;
      });

      try {
        // 1. Preview first
        final result = await SyncService().previewPartnerId(input);
        final partnerName = result['partnerName'];

        if (!mounted) return;

        // 2. Show Confirmation Dialog
        final confirm = await showDialog<bool>(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('Confirm Partner'),
            content: Text(
                'Found partner: $partnerName.\n\nDo you want to link with them?'),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context, false),
                child: const Text('Cancel'),
              ),
              ElevatedButton(
                onPressed: () => Navigator.pop(context, true),
                child: const Text('Confirm Link'),
              ),
            ],
          ),
        );

        if (confirm != true) {
          if (mounted) setState(() => _isLoading = false);
          return;
        }

        // 3. Perform Link
        final verifyResult =
            await SyncService().verifyPartnerId(user.id, input);

        if (!mounted) return;

        await ref.read(userProfileProvider.notifier).updateProfile(
              user.copyWith(
                partnerId: input,
                partnerName: verifyResult['partnerName'],
              ),
            );

        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
                content: Text('Connected to ${verifyResult['partnerName']}!')),
          );

          setState(() {
            _isLoading = false;
          });
        }
      } catch (e) {
        if (mounted) {
          setState(() {
            _isLoading = false;
            _errorText = e.toString().replaceAll('Exception:', '').trim();
          });
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final user = ref.watch(userProfileProvider);
    if (user == null) return const Scaffold();

    return Scaffold(
      appBar: AppBar(title: const Text('Sharing & Partner')),
      body: ListView(
        children: [
          _buildPartnerSection(user),
          const Divider(),
          _buildSharingToggles(user),
        ],
      ),
    );
  }

  Widget _buildPartnerSection(user) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('Partner Connection',
              style: Theme.of(context).textTheme.titleMedium),
          const SizedBox(height: 16),
          // My ID
          Text('My ID (Share this with your partner):',
              style: Theme.of(context).textTheme.bodySmall),
          Row(
            children: [
              Expanded(
                child: SelectableText(
                  user.id,
                  style: const TextStyle(fontWeight: FontWeight.bold),
                ),
              ),
              IconButton(
                icon: const Icon(Icons.copy),
                onPressed: () {
                  Clipboard.setData(ClipboardData(text: user.id));
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('ID copied to clipboard')),
                  );
                },
              ),
            ],
          ),
          const SizedBox(height: 24),
          // Partner ID Input
          TextField(
            controller: _partnerIdController,
            decoration: InputDecoration(
              labelText: 'Enter Partner ID',
              border: const OutlineInputBorder(),
              hintText: 'Paste partner ID here',
              errorText: _errorText,
            ),
            enabled: !_isLoading,
          ),
          const SizedBox(height: 8),
          if (_isLoading)
            const Padding(
              padding: EdgeInsets.all(8.0),
              child: Center(child: CircularProgressIndicator()),
            )
          else
            ElevatedButton(
              onPressed: _savePartnerId,
              child: const Text('Link Partner'),
            ),
        ],
      ),
    );
  }

  Widget _buildSharingToggles(user) {
    final notifier = ref.read(userProfileProvider.notifier);
    final isPadTrackingEnabled = user.isPadTrackingEnabled ?? false;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          child: Text('What to Share',
              style: Theme.of(context).textTheme.titleMedium),
        ),
        SwitchListTile(
          title: const Text('Share Moods'),
          value: user.shareMoods,
          onChanged: (val) =>
              notifier.updateProfile(user.copyWith(shareMoods: val)),
        ),
        SwitchListTile(
          title: const Text('Share Symptoms'),
          value: user.shareSymptoms,
          onChanged: (val) =>
              notifier.updateProfile(user.copyWith(shareSymptoms: val)),
        ),
        SwitchListTile(
          title: const Text('Share Energy Levels'),
          value: user.shareEnergyLevels,
          onChanged: (val) =>
              notifier.updateProfile(user.copyWith(shareEnergyLevels: val)),
        ),
        SwitchListTile(
          title: const Text('Share Pad Supplies'),
          subtitle: !isPadTrackingEnabled
              ? const Text('Enable Pad Tracking to share supplies')
              : null,
          value: isPadTrackingEnabled && (user.sharePadSupplies ?? true),
          onChanged: isPadTrackingEnabled
              ? (val) =>
                  notifier.updateProfile(user.copyWith(sharePadSupplies: val))
              : null,
        ),
        SwitchListTile(
          title: const Text('Share Intimacy'),
          subtitle: const Text('Always shared with your husband'),
          value: true, // Always true
          onChanged: null, // Disabled - always on
        ),
      ],
    );
  }
}
