import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:lucide_icons/lucide_icons.dart';
import '../../../app/theme/app_colors.dart';
import '../../../core/widgets/arabic_text.dart';
import '../../../core/widgets/bottom_sheet_content_padding.dart';
import '../../../data/local/hive_boxes.dart';
import '../../../data/local/models/app_settings.dart';
import '../../../data/services/muslim_api_service.dart';

class DoaScreen extends StatefulWidget {
  final bool isSimpleModeTab;
  const DoaScreen({super.key, this.isSimpleModeTab = false});

  @override
  State<DoaScreen> createState() => _DoaScreenState();
}

class _DoaScreenState extends State<DoaScreen> {
  final TextEditingController _searchController = TextEditingController();
  List<Map<String, dynamic>> _allDoa = [];
  List<Map<String, dynamic>> _filteredDoa = [];
  bool _loading = true;
  String? _error;

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

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

  Future<void> _loadDoa() async {
    setState(() {
      _loading = true;
      _error = null;
    });

    try {
      final data = await MuslimApiService.instance.getDoaList(strict: true);
      if (!mounted) return;
      setState(() {
        _allDoa = data;
        _filteredDoa = data;
        _loading = false;
      });
    } catch (_) {
      if (!mounted) return;
      setState(() {
        _allDoa = [];
        _filteredDoa = [];
        _loading = false;
        _error = 'Gagal memuat doa dari server';
      });
    }
  }

  void _onSearchChanged(String value) {
    final q = value.trim().toLowerCase();
    if (q.isEmpty) {
      setState(() => _filteredDoa = _allDoa);
      return;
    }
    setState(() {
      _filteredDoa = _allDoa.where((item) {
        final title = item['judul']?.toString().toLowerCase() ?? '';
        final indo = item['indo']?.toString().toLowerCase() ?? '';
        return title.contains(q) || indo.contains(q);
      }).toList();
    });
  }

  void _showArabicFontSettings() {
    final settingsBox = Hive.box<AppSettings>(HiveBoxes.settings);
    final settings = settingsBox.get('default') ?? AppSettings();
    if (!settings.isInBox) {
      settingsBox.put('default', settings);
    }
    double arabicFontSize = settings.arabicFontSize;

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      useSafeArea: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (ctx) => StatefulBuilder(
        builder: (context, setModalState) {
          return Padding(
            padding: bottomSheetContentPadding(context),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  'Pengaturan Tampilan',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 16),
                const Text('Ukuran Font Arab'),
                Slider(
                  value: arabicFontSize,
                  min: 16,
                  max: 40,
                  divisions: 12,
                  label: '${arabicFontSize.round()}pt',
                  activeColor: AppColors.primary,
                  onChanged: (value) {
                    setModalState(() => arabicFontSize = value);
                    settings.arabicFontSize = value;
                    if (settings.isInBox) {
                      settings.save();
                    } else {
                      settingsBox.put('default', settings);
                    }
                  },
                ),
                const SizedBox(height: 8),
              ],
            ),
          );
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final isDark = Theme.of(context).brightness == Brightness.dark;

    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: !widget.isSimpleModeTab,
        title: const Text('Kumpulan Doa'),
        actionsPadding: const EdgeInsets.only(right: 8),
        actions: [
          IconButton(
            onPressed: _loadDoa,
            icon: const Icon(LucideIcons.refreshCw),
            tooltip: 'Muat ulang',
          ),
          IconButton(
            onPressed: _showArabicFontSettings,
            icon: const Icon(LucideIcons.settings2),
            tooltip: 'Pengaturan tampilan',
          ),
        ],
      ),
      body: SafeArea(
        top: false,
        bottom: !widget.isSimpleModeTab,
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.fromLTRB(16, 8, 16, 12),
              child: TextField(
                controller: _searchController,
                onChanged: _onSearchChanged,
                decoration: InputDecoration(
                  hintText: 'Cari judul atau isi doa...',
                  prefixIcon: const Icon(LucideIcons.search),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
              ),
            ),
            Expanded(
              child: _loading
                  ? const Center(child: CircularProgressIndicator())
                  : _error != null
                      ? Center(
                          child: Text(
                            _error!,
                            style: TextStyle(
                              color: isDark
                                  ? AppColors.textSecondaryDark
                                  : AppColors.textSecondaryLight,
                            ),
                          ),
                        )
                      : _filteredDoa.isEmpty
                          ? Center(
                              child: Text(
                                'Doa tidak ditemukan',
                                style: TextStyle(
                                  color: isDark
                                      ? AppColors.textSecondaryDark
                                      : AppColors.textSecondaryLight,
                                ),
                              ),
                            )
                          : ListView.builder(
                              padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
                              itemCount: _filteredDoa.length,
                              itemBuilder: (context, index) {
                                final item = _filteredDoa[index];
                                return Container(
                                  margin: const EdgeInsets.only(bottom: 12),
                                  padding: const EdgeInsets.all(14),
                                  decoration: BoxDecoration(
                                    color: isDark
                                        ? AppColors.surfaceDark
                                        : AppColors.surfaceLight,
                                    borderRadius: BorderRadius.circular(14),
                                    border: Border.all(
                                      color: isDark
                                          ? AppColors.primary
                                              .withValues(alpha: 0.1)
                                          : AppColors.cream,
                                    ),
                                  ),
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        item['judul']?.toString() ?? '-',
                                        style: const TextStyle(
                                          fontSize: 15,
                                          fontWeight: FontWeight.w700,
                                          color: AppColors.primary,
                                        ),
                                      ),
                                      const SizedBox(height: 10),
                                      Align(
                                        alignment: Alignment.centerRight,
                                        child: ArabicText(
                                          item['arab']?.toString() ?? '',
                                          textAlign: TextAlign.right,
                                          baseFontSize: 24,
                                          fontWeight: FontWeight.w400,
                                          height: 1.8,
                                        ),
                                      ),
                                      const SizedBox(height: 8),
                                      Text(
                                        item['indo']?.toString() ?? '',
                                        style: TextStyle(
                                          height: 1.5,
                                          color: isDark
                                              ? AppColors.textSecondaryDark
                                              : AppColors.textSecondaryLight,
                                        ),
                                      ),
                                      if ((item['source']
                                              ?.toString()
                                              .isNotEmpty ??
                                          false)) ...[
                                        const SizedBox(height: 10),
                                        Text(
                                          'Sumber: ${item['source']}',
                                          style: const TextStyle(
                                            fontSize: 12,
                                            color: AppColors.primary,
                                            fontWeight: FontWeight.w600,
                                          ),
                                        ),
                                      ],
                                    ],
                                  ),
                                );
                              },
                            ),
            ),
          ],
        ),
      ),
    );
  }
}
