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/tilt_card.dart';
import '../../widgets/formatted_text.dart';
import '../../widgets/upgrade_prompt.dart';

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

  @override
  State<CostEstimatorScreen> createState() => _CostEstimatorScreenState();
}

class _CostEstimatorScreenState extends State<CostEstimatorScreen> {
  final _descriptionController = TextEditingController();
  String? _selectedCountry;
  String? _selectedCategory;
  bool _loading = false;
  Map<String, dynamic>? _estimate;

  static const _legalCategories = [
    'Criminal Defense', 'Civil Litigation', 'Family Law', 'Immigration',
    'Real Estate', 'Employment', 'Personal Injury', 'Business Law',
    'Intellectual Property', 'Tax Law', 'Other',
  ];

  Future<void> _getEstimate() async {
    if (_descriptionController.text.isEmpty) return;
    setState(() { _loading = true; _estimate = null; });
    try {
      final provider = context.read<AppProvider>();
      final result = await provider.api.estimateCost({
        'country': _selectedCountry ?? '',
        'case_type': _selectedCategory ?? 'Other',
        'description': _descriptionController.text,
      });
      setState(() { _estimate = result; });
    } on ApiException catch (e) {
      if (e.isLimitError) {
        if (mounted) showUpgradePrompt(context, feature: 'cost estimates');
      } else if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Error: ${e.message}'),
            backgroundColor: AppColors.error,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          ),
        );
      }
    } catch (_) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: const Text('Failed to get estimate'),
            backgroundColor: AppColors.error,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          ),
        );
      }
    }
    setState(() { _loading = false; });
  }

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

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

    return Scaffold(
      backgroundColor: Colors.transparent,
      appBar: AppBar(
        title: Text('Cost Estimator', 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('Get an AI-powered cost estimate for legal services.',
                style: AppTypography.bodyMd.copyWith(color: AppColors.textSecondary)),
            const SizedBox(height: 24),

            // Country selector
            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() ?? c['name']?.toString() ?? '',
                    child: Text(c['name']?.toString() ?? ''),
                  );
                }).toList(),
                onChanged: (v) => setState(() => _selectedCountry = v),
              ),
            ),
            const SizedBox(height: 12),

            // Category selector
            GlassCard(
              padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 4),
              child: DropdownButtonFormField<String>(
                value: _selectedCategory,
                hint: Text('Legal Category', style: AppTypography.bodyMd.copyWith(color: AppColors.textMuted)),
                dropdownColor: AppColors.navy,
                style: AppTypography.bodyMd.copyWith(color: Colors.white),
                decoration: const InputDecoration(border: InputBorder.none),
                items: _legalCategories.map((c) {
                  return DropdownMenuItem(value: c, child: Text(c));
                }).toList(),
                onChanged: (v) => setState(() => _selectedCategory = v),
              ),
            ),
            const SizedBox(height: 12),

            // Description
            GlassCard(
              padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
              child: TextField(
                controller: _descriptionController,
                maxLines: 4,
                style: AppTypography.bodyMd.copyWith(color: Colors.white),
                decoration: InputDecoration(
                  hintText: 'Describe your legal situation...',
                  hintStyle: AppTypography.bodyMd.copyWith(color: AppColors.textMuted),
                  border: InputBorder.none,
                ),
              ),
            ),
            const SizedBox(height: 20),

            // Estimate button
            GestureDetector(
              onTap: _loading ? null : _getEstimate,
              child: Container(
                width: double.infinity,
                height: 52,
                decoration: BoxDecoration(
                  gradient: AppColors.blueGradient,
                  borderRadius: BorderRadius.circular(14),
                  boxShadow: [
                    BoxShadow(color: AppColors.royalBlue.withValues(alpha: 0.35), blurRadius: 16, offset: const Offset(0, 4)),
                  ],
                ),
                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.calculate_rounded, color: Colors.white, size: 20),
                            const SizedBox(width: 8),
                            Text('Get Estimate', style: AppTypography.button.copyWith(color: Colors.white)),
                          ],
                        ),
                ),
              ),
            ),

            // Result
            if (_estimate != null) ...[
              const SizedBox(height: 28),
              TiltCard(
                child: Container(
                  width: double.infinity,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(16),
                    gradient: LinearGradient(
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                      colors: [
                        AppColors.gold.withValues(alpha: 0.08),
                        AppColors.glassSurface,
                      ],
                    ),
                    border: Border.all(color: AppColors.gold.withValues(alpha: 0.25)),
                  ),
                  padding: const EdgeInsets.all(20),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Icon(Icons.receipt_long_rounded, color: AppColors.gold, size: 22),
                          const SizedBox(width: 8),
                          Text('Estimate', style: AppTypography.headingLg.copyWith(color: AppColors.gold)),
                        ],
                      ),
                      const SizedBox(height: 16),
                      if (_estimate!['estimate'] != null) ...[
                        FormattedText(
                          text: _estimate!['estimate'].toString(),
                          baseStyle: AppTypography.bodyMd.copyWith(color: Colors.white, height: 1.5),
                        ),
                      ],
                      if (_estimate!['disclaimer'] != null) ...[
                        const SizedBox(height: 12),
                        Text(
                          _estimate!['disclaimer'].toString(),
                          style: AppTypography.bodySm.copyWith(color: AppColors.textMuted, fontStyle: FontStyle.italic),
                        ),
                      ],
                    ],
                  ),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }
}
