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

import 'package:doormile/core/theme/app_colors.dart';
import 'package:doormile/core/theme/app_theme.dart';

/// White rounded card with the design-system ambient shadow.
class AppCard extends StatelessWidget {
  final Widget child;
  final EdgeInsetsGeometry padding;
  final VoidCallback? onTap;
  final Color color;
  final BorderRadius? radius;
  final Border? border;

  const AppCard({
    super.key,
    required this.child,
    this.padding = const EdgeInsets.all(16),
    this.onTap,
    this.color = AppColors.surfaceContainerLowest,
    this.radius,
    this.border,
  });

  @override
  Widget build(BuildContext context) {
    final br = radius ?? BorderRadius.circular(18);
    return Material(
      color: color,
      borderRadius: br,
      child: InkWell(
        onTap: onTap,
        borderRadius: br,
        child: Ink(
          decoration: BoxDecoration(
            color: color,
            borderRadius: br,
            border: border ?? Border.all(color: AppColors.surfaceContainer.withValues(alpha: 0.7)),
            boxShadow: AppTheme.cardShadow,
          ),
          child: Padding(padding: padding, child: child),
        ),
      ),
    );
  }
}

/// Primary filled action button (min height 52, 12px radius).
class PrimaryButton extends StatelessWidget {
  final String label;
  final VoidCallback? onPressed;
  final IconData? trailingIcon;
  final bool loading;
  final Color color;
  final double height;

  const PrimaryButton({
    super.key,
    required this.label,
    required this.onPressed,
    this.trailingIcon,
    this.loading = false,
    this.color = AppColors.primary,
    this.height = 52,
  });

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: double.infinity,
      height: height,
      child: ElevatedButton(
        onPressed: loading ? null : onPressed,
        style: ElevatedButton.styleFrom(
          backgroundColor: color,
          foregroundColor: Colors.white,
          disabledBackgroundColor: color.withValues(alpha: 0.6),
          disabledForegroundColor: Colors.white,
          elevation: 0,
          shadowColor: AppColors.primary.withValues(alpha: 0.2),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        ),
        child: loading
            ? const SizedBox(
                width: 22,
                height: 22,
                child: CircularProgressIndicator(strokeWidth: 2.4, color: Colors.white),
              )
            : Row(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Flexible(
                    child: Text(label,
                        style: AppTheme.button,
                        overflow: TextOverflow.ellipsis,
                        maxLines: 1),
                  ),
                  if (trailingIcon != null) ...[
                    const SizedBox(width: 8),
                    Icon(trailingIcon, size: 20),
                  ],
                ],
              ),
      ),
    );
  }
}

/// Secondary tinted button (pink bg, red text).
class SecondaryButton extends StatelessWidget {
  final String label;
  final VoidCallback? onPressed;
  const SecondaryButton({super.key, required this.label, this.onPressed});

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 44,
      child: OutlinedButton(
        onPressed: onPressed,
        style: OutlinedButton.styleFrom(
          backgroundColor: AppColors.surfaceContainerLowest,
          foregroundColor: AppColors.primary,
          side: const BorderSide(color: AppColors.outlineVariant),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
          padding: const EdgeInsets.symmetric(horizontal: 18),
        ),
        child: Text(label, style: AppTheme.labelMd.copyWith(color: AppColors.primary)),
      ),
    );
  }
}

/// Pill-shaped status / category chip.
class StatusChip extends StatelessWidget {
  final String label;
  final Color color;
  final Color bg;
  final IconData? icon;
  const StatusChip({
    super.key,
    required this.label,
    required this.color,
    required this.bg,
    this.icon,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 5),
      decoration: BoxDecoration(
        color: bg,
        borderRadius: BorderRadius.circular(999),
        border: Border.all(color: color.withValues(alpha: 0.12)),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (icon != null) ...[Icon(icon, size: 14, color: color), const SizedBox(width: 4)],
          Text(label,
              style: AppTheme.caption.copyWith(color: color, fontWeight: FontWeight.w600)),
        ],
      ),
    );
  }
}

/// A horizontal stepper progress bar with a fraction filled.
class JourneyProgressBar extends StatelessWidget {
  final double value; // 0..1
  final bool gradient;
  const JourneyProgressBar({super.key, required this.value, this.gradient = false});

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(999),
      child: Stack(
        children: [
          Container(height: 6, color: AppColors.surfaceContainer),
          FractionallySizedBox(
            widthFactor: value.clamp(0, 1),
            child: Container(
              height: 6,
              decoration: BoxDecoration(
                color: gradient ? null : AppColors.primary,
                gradient: gradient
                    ? const LinearGradient(colors: [
                        AppColors.firstMile,
                        AppColors.midMile,
                        AppColors.lastMile,
                      ])
                    : null,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

/// Eco / EV reassurance banner used across screens.
class EcoBanner extends StatelessWidget {
  final String text;
  const EcoBanner({super.key, required this.text});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: AppColors.tertiaryFixed.withValues(alpha: 0.4),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: AppColors.tertiary.withValues(alpha: 0.1)),
      ),
      child: Row(
        children: [
          const Icon(Icons.eco, color: AppColors.tertiary, size: 22),
          const SizedBox(width: 12),
          Expanded(
            child: Text(text,
                style: AppTheme.bodyMd.copyWith(color: AppColors.tertiary, height: 1.35)),
          ),
        ],
      ),
    );
  }
}

/// Warm page backdrop with restrained route/map texture.
class AppBackground extends StatelessWidget {
  final Widget child;
  final EdgeInsetsGeometry padding;
  const AppBackground({
    super.key,
    required this.child,
    this.padding = EdgeInsets.zero,
  });

  @override
  Widget build(BuildContext context) {
    return DecoratedBox(
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [Color(0xFFFFFBF8), AppColors.surface],
        ),
      ),
      child: Stack(
        children: [
          const Positioned(
            top: 240,
            left: -70,
            child: _SoftCircle(size: 180, color: Color(0x1A126E82)),
          ),
          Padding(padding: padding, child: child),
        ],
      ),
    );
  }
}

class _SoftCircle extends StatelessWidget {
  final double size;
  final Color color;
  const _SoftCircle({required this.size, required this.color});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: size,
      height: size,
      decoration: BoxDecoration(shape: BoxShape.circle, color: color),
    );
  }
}

/// Reusable immersive red header used by primary tabs.
class ImmersiveHeader extends StatelessWidget {
  final String title;
  final String subtitle;
  final IconData icon;
  final Widget? trailing;
  final bool showBack;

  const ImmersiveHeader({
    super.key,
    required this.title,
    required this.subtitle,
    required this.icon,
    this.trailing,
    this.showBack = false,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          colors: [AppColors.primaryContainer, AppColors.primary],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.vertical(bottom: Radius.circular(24)),
      ),
      child: ClipRRect(
        borderRadius: const BorderRadius.vertical(bottom: Radius.circular(24)),
        child: AnnotatedRegion<SystemUiOverlayStyle>(
          value: SystemUiOverlayStyle.light,
          child: Stack(
            children: [
              Positioned(
                right: -20,
                bottom: -30,
                child: Icon(icon, size: 140, color: Colors.white.withValues(alpha: 0.04)),
              ),
              Positioned(
                right: 100,
                top: -10,
                child: Transform.rotate(
                  angle: 0.2,
                  child: Icon(Icons.auto_awesome_rounded, size: 60, color: Colors.white.withValues(alpha: 0.03)),
                ),
              ),
              SafeArea(
                bottom: false,
                child: Padding(
                  padding: const EdgeInsets.fromLTRB(20, 16, 20, 16),
            child: Row(
              children: [
                if (showBack) ...[
                  IconButton(
                    onPressed: () => Navigator.pop(context),
                    icon: const Icon(Icons.arrow_back, color: Colors.white),
                    padding: EdgeInsets.zero,
                    alignment: Alignment.centerLeft,
                  ),
                  const SizedBox(width: 4),
                ],
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(title,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: AppTheme.headlineLg.copyWith(color: Colors.white)),
                      const SizedBox(height: 4),
                      Text(subtitle,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: AppTheme.bodyMd.copyWith(color: Colors.white.withValues(alpha: 0.8))),
                    ],
                  ),
                ),
                if (trailing != null) trailing!,
              ],
            ),
          ),
        ),
            ],
          ),
        ),
      ),
    );
  }
}

/// A small circular icon avatar with a tinted background.
class IconBadge extends StatelessWidget {
  final IconData icon;
  final Color bg;
  final Color color;
  final double size;
  final double iconSize;
  final bool circle;
  const IconBadge({
    super.key,
    required this.icon,
    required this.bg,
    required this.color,
    this.size = 48,
    this.iconSize = 22,
    this.circle = false,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: size,
      height: size,
      decoration: BoxDecoration(
        color: bg,
        borderRadius: BorderRadius.circular(circle ? size : 12),
      ),
      child: Icon(icon, color: color, size: iconSize),
    );
  }
}

/// Title row with an optional trailing action ("View All").
class SectionHeader extends StatelessWidget {
  final String title;
  final String? action;
  final VoidCallback? onAction;
  const SectionHeader({super.key, required this.title, this.action, this.onAction});

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Flexible(
          child: Text(title,
              style: AppTheme.headlineSm, overflow: TextOverflow.ellipsis, maxLines: 1),
        ),
        if (action != null)
          GestureDetector(
            onTap: onAction,
            child: Padding(
              padding: const EdgeInsets.only(left: 8),
              child: Text(action!,
                  style: AppTheme.labelMd.copyWith(color: AppColors.primary)),
            ),
          ),
      ],
    );
  }
}
