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 IntakeScreen extends StatefulWidget {
  const IntakeScreen({super.key});

  @override
  State<IntakeScreen> createState() => _IntakeScreenState();
}

class _IntakeScreenState extends State<IntakeScreen> {
  List<dynamic> _questions = [];
  final Map<String, dynamic> _answers = {};
  final Map<String, TextEditingController> _controllers = {};
  bool _loadingQ = true;
  bool _submitting = false;
  Map<String, dynamic>? _result;
  String? _error;
  int _step = 0;

  TextEditingController _getController(String key) {
    if (!_controllers.containsKey(key)) {
      _controllers[key] = TextEditingController(text: _answers[key]?.toString() ?? '');
    }
    return _controllers[key]!;
  }

  @override
  void initState() {
    super.initState();
    _loadQuestions();
  }

  @override
  void dispose() {
    for (final c in _controllers.values) {
      c.dispose();
    }
    super.dispose();
  }

  Future<void> _loadQuestions() async {
    try {
      final res = await context.read<AppProvider>().api.getIntakeQuestions();
      _questions = res['questions'] as List? ?? [];
    } catch (_) {
      _questions = _defaultQuestions;
    }
    setState(() => _loadingQ = false);
  }

  static const _defaultQuestions = [
    {'key': 'legal_area', 'question': 'What area of law does this relate to?', 'type': 'choice',
     'options': ['criminal', 'civil', 'family', 'labor', 'immigration', 'housing', 'business', 'other']},
    {'key': 'country', 'question': 'Which country is this in?', 'type': 'text'},
    {'key': 'urgency', 'question': 'How urgent is this?', 'type': 'choice', 'options': ['low', 'moderate', 'high', 'emergency']},
    {'key': 'description', 'question': 'Describe your legal situation in detail.', 'type': 'text'},
    {'key': 'desired_outcome', 'question': 'What outcome are you hoping for?', 'type': 'text'},
  ];

  Future<void> _submit() async {
    setState(() { _submitting = true; _error = null; });
    try {
      _result = await context.read<AppProvider>().api.submitIntake(_answers);
    } on ApiException catch (e) {
      if (e.isLimitError) {
        if (mounted) showUpgradePrompt(context, feature: 'case assessments');
      } else {
        _error = e.message;
      }
    } catch (_) {
      _error = 'Connection error';
    }
    setState(() => _submitting = false);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.navy,
      appBar: AppBar(
        title: Text('Legal Intake', style: AppTypography.headingLg.copyWith(color: Colors.white)),
        backgroundColor: Colors.transparent,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: _loadingQ
          ? const Center(child: CircularProgressIndicator(color: AppColors.royalBlue))
          : _result != null
              ? _buildResult()
              : _buildForm(),
    );
  }

  Widget _buildForm() {
    final questions = _questions.isEmpty ? _defaultQuestions : _questions;
    if (_step >= questions.length) {
      // Summary
      return SingleChildScrollView(
        padding: const EdgeInsets.fromLTRB(16, 0, 16, 40),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Review & Submit', style: AppTypography.headingMd.copyWith(color: Colors.white)),
            const SizedBox(height: 16),
            ..._answers.entries.map((e) => Padding(
              padding: const EdgeInsets.only(bottom: 12),
              child: GlassCard(
                padding: const EdgeInsets.all(14),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(e.key.replaceAll('_', ' ').toUpperCase(),
                        style: AppTypography.label.copyWith(color: AppColors.textMuted)),
                    const SizedBox(height: 4),
                    Text(e.value.toString(), style: AppTypography.bodyMd.copyWith(color: Colors.white)),
                  ],
                ),
              ),
            )),
            if (_error != null)
              Padding(
                padding: const EdgeInsets.only(bottom: 12),
                child: Text(_error!, style: AppTypography.bodyMd.copyWith(color: AppColors.error)),
              ),
            const SizedBox(height: 8),
            Row(
              children: [
                Expanded(
                  child: GestureDetector(
                    onTap: () => setState(() => _step--),
                    child: Container(
                      height: 50,
                      decoration: BoxDecoration(
                        color: AppColors.glassSurface,
                        borderRadius: BorderRadius.circular(14),
                        border: Border.all(color: AppColors.glassBorder),
                      ),
                      child: Center(child: Text('Back', style: AppTypography.button.copyWith(color: Colors.white))),
                    ),
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  flex: 2,
                  child: GestureDetector(
                    onTap: _submitting ? null : _submit,
                    child: Container(
                      height: 50,
                      decoration: BoxDecoration(
                        gradient: AppColors.blueGradient,
                        borderRadius: BorderRadius.circular(14),
                      ),
                      child: Center(
                        child: _submitting
                            ? const SizedBox(width: 22, height: 22, child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2))
                            : Text('Submit', style: AppTypography.button.copyWith(color: Colors.white)),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      );
    }

    final q = questions[_step] as Map;
    final key = (q['id'] ?? q['key'])?.toString() ?? '';
    final question = q['question']?.toString() ?? '';
    final type = q['type']?.toString() ?? 'text';
    final isChoice = type == 'choice' || type == 'select';
    final options = (q['options'] as List?)?.cast<String>() ?? [];

    return Padding(
      padding: const EdgeInsets.fromLTRB(16, 0, 16, 40),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Progress
          LinearProgressIndicator(
            value: (_step + 1) / (questions.length + 1),
            backgroundColor: AppColors.glassSurface,
            valueColor: const AlwaysStoppedAnimation(AppColors.royalBlue),
            borderRadius: BorderRadius.circular(4),
          ),
          const SizedBox(height: 8),
          Text('${_step + 1} of ${questions.length}',
              style: AppTypography.bodySm.copyWith(color: AppColors.textMuted)),
          const SizedBox(height: 24),
          Text(question, style: AppTypography.headingLg.copyWith(color: Colors.white)),
          const SizedBox(height: 20),

          if (isChoice && options.isNotEmpty)
            ...options.map((opt) => Padding(
              padding: const EdgeInsets.only(bottom: 10),
              child: GestureDetector(
                onTap: () {
                  _answers[key] = opt;
                  setState(() => _step++);
                },
                child: GlassCard(
                  highlighted: _answers[key] == opt,
                  padding: const EdgeInsets.all(16),
                  child: Row(
                    children: [
                      Container(
                        width: 24, height: 24,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          color: _answers[key] == opt ? AppColors.royalBlue : Colors.transparent,
                          border: Border.all(
                            color: _answers[key] == opt ? AppColors.royalBlue : AppColors.glassBorder,
                            width: 2,
                          ),
                        ),
                        child: _answers[key] == opt
                            ? const Icon(Icons.check, size: 14, color: Colors.white)
                            : null,
                      ),
                      const SizedBox(width: 14),
                      Text(opt[0].toUpperCase() + opt.substring(1),
                          style: AppTypography.bodyLg.copyWith(color: Colors.white)),
                    ],
                  ),
                ),
              ),
            ))
          else if (!isChoice || options.isEmpty) ...[
            GlassCard(
              padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
              child: TextField(
                key: ValueKey(key),
                controller: _getController(key),
                maxLines: key == 'description' ? 5 : 2,
                style: AppTypography.bodyMd.copyWith(color: Colors.white),
                decoration: InputDecoration(
                  hintText: 'Your answer...',
                  hintStyle: AppTypography.bodyMd.copyWith(color: AppColors.textMuted),
                  border: InputBorder.none,
                ),
                onChanged: (v) => _answers[key] = v,
              ),
            ),
          ],

          const Spacer(),
          Row(
            children: [
              if (_step > 0)
                Expanded(
                  child: GestureDetector(
                    onTap: () => setState(() => _step--),
                    child: Container(
                      height: 50,
                      decoration: BoxDecoration(
                        color: AppColors.glassSurface,
                        borderRadius: BorderRadius.circular(14),
                        border: Border.all(color: AppColors.glassBorder),
                      ),
                      child: Center(child: Text('Back', style: AppTypography.button.copyWith(color: Colors.white))),
                    ),
                  ),
                ),
              if (_step > 0) const SizedBox(width: 12),
              if (!isChoice)
                Expanded(
                  flex: 2,
                  child: GestureDetector(
                    onTap: () {
                      if ((_answers[key]?.toString() ?? '').trim().isEmpty) return;
                      setState(() => _step++);
                    },
                    child: Container(
                      height: 50,
                      decoration: BoxDecoration(
                        gradient: AppColors.blueGradient,
                        borderRadius: BorderRadius.circular(14),
                      ),
                      child: Center(child: Text('Next', style: AppTypography.button.copyWith(color: Colors.white))),
                    ),
                  ),
                ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildResult() {
    final analysis = _result!['analysis'] as Map<String, dynamic>?;
    return SingleChildScrollView(
      padding: const EdgeInsets.fromLTRB(16, 0, 16, 40),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          GlassCard(
            highlighted: true,
            padding: const EdgeInsets.all(20),
            child: Row(
              children: [
                Icon(Icons.check_circle_rounded, color: AppColors.success, size: 24),
                const SizedBox(width: 12),
                Expanded(child: Text('Case Analysis Complete', style: AppTypography.headingMd.copyWith(color: AppColors.success))),
              ],
            ),
          ),
          const SizedBox(height: 16),

          if (analysis != null) ...[
            if (analysis['issues'] != null) _section('Key Issues', analysis['issues'].toString()),
            if (analysis['legal_areas'] != null) _section('Legal Areas', analysis['legal_areas'].toString()),
            if (analysis['next_steps'] != null) _section('Recommended Next Steps', analysis['next_steps'].toString()),
            if (analysis['urgency_assessment'] != null) _section('Urgency', analysis['urgency_assessment'].toString()),
            if (analysis['key_questions'] != null) _section('Key Questions', analysis['key_questions'].toString()),
          ],

          if (_result!['conversation_id'] != null) ...[
            const SizedBox(height: 20),
            GestureDetector(
              onTap: () => Navigator.of(context).pushReplacementNamed(
                '/chat',
                arguments: {'conversationId': _result!['conversation_id'].toString()},
              ),
              child: Container(
                width: double.infinity,
                height: 52,
                decoration: BoxDecoration(
                  gradient: AppColors.blueGradient,
                  borderRadius: BorderRadius.circular(14),
                ),
                child: Center(
                  child: Row(mainAxisSize: MainAxisSize.min, children: [
                    const Icon(Icons.chat_rounded, color: Colors.white, size: 20),
                    const SizedBox(width: 8),
                    Text('Continue in Chat', style: AppTypography.button.copyWith(color: Colors.white)),
                  ]),
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _section(String title, String content) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: GlassCard(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(title, style: AppTypography.headingMd.copyWith(color: AppColors.gold)),
            const SizedBox(height: 8),
            Text(content, style: AppTypography.bodyMd.copyWith(color: Colors.white, height: 1.5)),
          ],
        ),
      ),
    );
  }
}
