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/upgrade_prompt.dart';

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

  @override
  State<StatuteCheckScreen> createState() => _StatuteCheckScreenState();
}

class _StatuteCheckScreenState extends State<StatuteCheckScreen> {
  final _caseTypeCtrl = TextEditingController();
  String? _selectedCountry;
  DateTime _incidentDate = DateTime.now().subtract(const Duration(days: 365));
  bool _loading = false;
  Map<String, dynamic>? _result;
  String? _error;

  Future<void> _check() async {
    if (_caseTypeCtrl.text.trim().isEmpty) return;
    setState(() { _loading = true; _result = null; _error = null; });
    try {
      final provider = context.read<AppProvider>();
      _result = await provider.api.statuteCheck(
        caseType: _caseTypeCtrl.text.trim(),
        incidentDate: '${_incidentDate.year}-${_incidentDate.month.toString().padLeft(2, '0')}-${_incidentDate.day.toString().padLeft(2, '0')}',
        country: _selectedCountry,
      );
    } on ApiException catch (e) {
      if (e.isLimitError) {
        if (mounted) showUpgradePrompt(context, feature: 'statute checks');
      } else {
        _error = e.message;
      }
    } catch (_) {
      _error = 'Connection error';
    }
    setState(() => _loading = false);
  }

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

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

    return Scaffold(
      backgroundColor: AppColors.navy,
      appBar: AppBar(
        title: Text('Statute of Limitations', 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('Check if your case is still within the statute of limitations.',
                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: _caseTypeCtrl,
                style: AppTypography.bodyMd.copyWith(color: Colors.white),
                decoration: InputDecoration(
                  hintText: 'Case type (e.g., breach of contract, personal injury)',
                  hintStyle: AppTypography.bodyMd.copyWith(color: AppColors.textMuted),
                  border: InputBorder.none,
                ),
              ),
            ),
            const SizedBox(height: 12),

            GestureDetector(
              onTap: () async {
                final picked = await showDatePicker(
                  context: context,
                  initialDate: _incidentDate,
                  firstDate: DateTime(2000),
                  lastDate: DateTime.now(),
                  builder: (c, child) => Theme(
                    data: ThemeData.dark().copyWith(
                      colorScheme: const ColorScheme.dark(primary: AppColors.royalBlue, surface: AppColors.navy),
                    ),
                    child: child!,
                  ),
                );
                if (picked != null) setState(() => _incidentDate = picked);
              },
              child: GlassCard(
                padding: const EdgeInsets.all(16),
                child: Row(
                  children: [
                    const Icon(Icons.calendar_today_rounded, color: AppColors.royalBlue, size: 20),
                    const SizedBox(width: 12),
                    Text('Incident Date: ${_incidentDate.day}/${_incidentDate.month}/${_incidentDate.year}',
                        style: AppTypography.bodyMd.copyWith(color: Colors.white)),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 20),

            GestureDetector(
              onTap: _loading ? null : _check,
              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))
                      : Text('Check Statute', style: AppTypography.button.copyWith(color: Colors.white)),
                ),
              ),
            ),

            if (_error != null) ...[
              const SizedBox(height: 16),
              GlassCard(
                padding: const EdgeInsets.all(16),
                child: Row(
                  children: [
                    const Icon(Icons.error_outline_rounded, color: AppColors.error, size: 20),
                    const SizedBox(width: 10),
                    Expanded(child: Text(_error!, style: AppTypography.bodyMd.copyWith(color: AppColors.error))),
                  ],
                ),
              ),
            ],

            if (_result != null) ...[
              const SizedBox(height: 24),
              TiltCard(
                child: Container(
                  width: double.infinity,
                  padding: const EdgeInsets.all(20),
                  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)),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Icon(Icons.gavel_rounded, color: AppColors.gold, size: 22),
                          const SizedBox(width: 8),
                          Text('Analysis', style: AppTypography.headingLg.copyWith(color: AppColors.gold)),
                        ],
                      ),
                      const SizedBox(height: 16),
                      Text(
                        _result!['analysis']?.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)),
                      ],
                    ],
                  ),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }
}
