import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_typography.dart';
import '../../services/app_provider.dart';
import '../../services/api_service.dart';
import '../../widgets/glass_card.dart';
import '../../widgets/upgrade_prompt.dart';

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

  @override
  State<LawSearchScreen> createState() => _LawSearchScreenState();
}

class _LawSearchScreenState extends State<LawSearchScreen> {
  final _descCtrl = TextEditingController();
  String? _selectedCountry;
  bool _loading = false;
  Map<String, dynamic>? _result;
  String? _error;

  Future<void> _search() async {
    if (_descCtrl.text.trim().isEmpty) return;
    setState(() { _loading = true; _result = null; _error = null; });
    try {
      _result = await context.read<AppProvider>().api.lawSearch(
        description: _descCtrl.text.trim(),
        country: _selectedCountry,
      );
    } on ApiException catch (e) {
      if (e.isLimitError) {
        if (mounted) showUpgradePrompt(context, feature: 'law searches');
      } else {
        _error = e.message;
      }
    } catch (_) {
      _error = 'Connection error';
    }
    setState(() => _loading = false);
  }

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

  @override
  Widget build(BuildContext context) {
    final provider = context.watch<AppProvider>();

    return Scaffold(
      backgroundColor: AppColors.navy,
      appBar: AppBar(
        title: Text('Law Search', style: AppTypography.headingLg.copyWith(color: Colors.white)),
        backgroundColor: Colors.transparent,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.fromLTRB(16, 0, 16, 100),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Search for applicable laws and regulations.',
                style: AppTypography.bodyMd.copyWith(color: AppColors.textSecondary)),
            const SizedBox(height: 24),

            GlassCard(
              padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 4),
              child: DropdownButtonFormField<String>(
                value: _selectedCountry,
                hint: Text('Select Country', style: AppTypography.bodyMd.copyWith(color: AppColors.textMuted)),
                dropdownColor: AppColors.navy,
                style: AppTypography.bodyMd.copyWith(color: Colors.white),
                decoration: const InputDecoration(border: InputBorder.none),
                items: provider.countries.map<DropdownMenuItem<String>>((c) {
                  return DropdownMenuItem(
                    value: c['code']?.toString() ?? '',
                    child: Text(c['name']?.toString() ?? ''),
                  );
                }).toList(),
                onChanged: (v) => setState(() => _selectedCountry = v),
              ),
            ),
            const SizedBox(height: 12),

            GlassCard(
              padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
              child: TextField(
                controller: _descCtrl,
                maxLines: 4,
                style: AppTypography.bodyMd.copyWith(color: Colors.white),
                decoration: InputDecoration(
                  hintText: 'Describe your legal situation or the law you are looking for...',
                  hintStyle: AppTypography.bodyMd.copyWith(color: AppColors.textMuted),
                  border: InputBorder.none,
                ),
              ),
            ),
            const SizedBox(height: 20),

            GestureDetector(
              onTap: _loading ? null : _search,
              child: Container(
                width: double.infinity,
                height: 52,
                decoration: BoxDecoration(
                  gradient: AppColors.blueGradient,
                  borderRadius: BorderRadius.circular(14),
                ),
                child: Center(
                  child: _loading
                      ? const SizedBox(width: 22, height: 22, child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2))
                      : Row(mainAxisSize: MainAxisSize.min, children: [
                          const Icon(Icons.search_rounded, color: Colors.white, size: 20),
                          const SizedBox(width: 8),
                          Text('Search Laws', style: AppTypography.button.copyWith(color: Colors.white)),
                        ]),
                ),
              ),
            ),

            if (_error != null) ...[
              const SizedBox(height: 16),
              GlassCard(
                padding: const EdgeInsets.all(16),
                child: Text(_error!, style: AppTypography.bodyMd.copyWith(color: AppColors.error)),
              ),
            ],

            if (_result != null) ...[
              const SizedBox(height: 24),
              GlassCard(
                padding: const EdgeInsets.all(20),
                highlighted: true,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(Icons.balance_rounded, color: AppColors.gold, size: 20),
                        const SizedBox(width: 8),
                        Text('Applicable Laws', style: AppTypography.headingMd.copyWith(color: AppColors.gold)),
                      ],
                    ),
                    const SizedBox(height: 16),
                    SelectableText(
                      _result!['applicable_laws']?.toString() ?? _result.toString(),
                      style: AppTypography.bodyMd.copyWith(color: Colors.white, height: 1.6),
                    ),
                    if (_result!['disclaimer'] != null) ...[
                      const SizedBox(height: 12),
                      Text(_result!['disclaimer'].toString(),
                          style: AppTypography.bodySm.copyWith(color: AppColors.textMuted, fontStyle: FontStyle.italic)),
                    ],
                  ],
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }
}
