import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';

import '../../data/local/hive_boxes.dart';
import '../../data/local/models/app_settings.dart';

/// Arabic text widget that reacts to [AppSettings.arabicFontSize].
///
/// `baseFontSize` keeps per-screen visual hierarchy while still following
/// global user preference from Settings.
class ArabicText extends StatelessWidget {
  const ArabicText(
    this.data, {
    super.key,
    this.baseFontSize = 24,
    this.fontWeight = FontWeight.w400,
    this.height,
    this.color,
    this.textAlign,
    this.maxLines,
    this.overflow,
    this.textDirection,
    this.fontStyle,
    this.letterSpacing,
  });

  final String data;
  final double baseFontSize;
  final FontWeight fontWeight;
  final double? height;
  final Color? color;
  final TextAlign? textAlign;
  final int? maxLines;
  final TextOverflow? overflow;
  final TextDirection? textDirection;
  final FontStyle? fontStyle;
  final double? letterSpacing;
  static const double _explicitLineHeightCompression = 0.9;
  static const double _defaultArabicLineHeight = 1.8;
  static const String _primaryArabicFontFamily = 'ScheherazadeNew';
  static const List<String> _arabicFallbackFamilies = <String>[
    'UthmanTahaNaskh',
    'KFGQPCUthmanicHafs',
    'Amiri',
    'Noto Naskh Arabic',
    'Noto Sans Arabic',
    'Droid Arabic Naskh',
    'sans-serif',
  ];

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<Box<AppSettings>>(
      valueListenable: Hive.box<AppSettings>(HiveBoxes.settings)
          .listenable(keys: ['default']),
      builder: (_, box, __) {
        final preferredSize = box.get('default')?.arabicFontSize ?? 24.0;
        final adjustedSize = (baseFontSize + (preferredSize - 24.0))
            .clamp(12.0, 56.0)
            .toDouble();
        final effectiveHeight = height == null
            ? _defaultArabicLineHeight
            : (height! * _explicitLineHeightCompression)
                .clamp(1.6, 2.35)
                .toDouble();

        return Text(
          data,
          textAlign: textAlign,
          maxLines: maxLines,
          overflow: overflow,
          textDirection: textDirection,
          strutStyle: StrutStyle(
            fontFamily: _primaryArabicFontFamily,
            fontSize: adjustedSize,
            height: effectiveHeight,
            leading: 0.08,
            forceStrutHeight: true,
          ),
          style: TextStyle(
            fontFamily: _primaryArabicFontFamily,
            fontFamilyFallback: _arabicFallbackFamilies,
            fontSize: adjustedSize,
            fontWeight: fontWeight,
            height: effectiveHeight,
            color: color,
            fontStyle: fontStyle,
            letterSpacing: letterSpacing,
          ),
        );
      },
    );
  }
}
