import 'package:flutter/material.dart';
import 'package:kasy_kit/components/kasy_app_bar.dart';
import 'package:kasy_kit/core/theme/theme.dart';

class DesignSystemPage extends StatelessWidget {
  const DesignSystemPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: context.colors.background,
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          KasyAppBar(
            title: 'Design System',
            onBack: () => Navigator.maybePop(context),
          ),
          Expanded(
            child: ListView(
              padding: EdgeInsets.fromLTRB(
                KasySpacing.pageHorizontalGutter,
                KasySpacing.belowChromeContentGap,
                KasySpacing.pageHorizontalGutter,
                MediaQuery.paddingOf(context).bottom + KasySpacing.xl,
              ),
              children: const [
                _SectionHeader('Colors'),
                SizedBox(height: KasySpacing.md),
                _ColorsSection(),
                SizedBox(height: KasySpacing.xl),
                _SectionHeader('Typography'),
                SizedBox(height: KasySpacing.md),
                _TypographySection(),
                SizedBox(height: KasySpacing.xl),
                _SectionHeader('Spacing'),
                SizedBox(height: KasySpacing.md),
                _SpacingSection(),
                SizedBox(height: KasySpacing.xl),
                _SectionHeader('Radius'),
                SizedBox(height: KasySpacing.md),
                _RadiusSection(),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

// ---------------------------------------------------------------------------
// Section header
// ---------------------------------------------------------------------------

class _SectionHeader extends StatelessWidget {
  final String title;
  const _SectionHeader(this.title);

  @override
  Widget build(BuildContext context) {
    return Text(
      title,
      style: context.textTheme.labelLarge?.copyWith(
        color: context.colors.muted,
        letterSpacing: 0.8,
      ),
    );
  }
}

// ---------------------------------------------------------------------------
// Divider between token rows
// ---------------------------------------------------------------------------

class _TokenDivider extends StatelessWidget {
  const _TokenDivider();

  @override
  Widget build(BuildContext context) {
    return Divider(
      height: 1,
      thickness: 1,
      color: context.colors.outline.withValues(alpha: 0.28),
    );
  }
}

// ---------------------------------------------------------------------------
// Colors
// ---------------------------------------------------------------------------

class _ColorsSection extends StatelessWidget {
  const _ColorsSection();

  @override
  Widget build(BuildContext context) {
    final c = context.colors;

    final List<_ColorToken> brandTokens = [
      _ColorToken('primary', c.primary),
      _ColorToken('onPrimary', c.onPrimary, border: true),
    ];
    final List<_ColorToken> semanticTokens = [
      _ColorToken('success', c.success),
      _ColorToken('onSuccess', c.onSuccess, border: true),
      _ColorToken('warning', c.warning),
      _ColorToken('onWarning', c.onWarning, border: true),
      _ColorToken('error', c.error),
      _ColorToken('onError', c.onError, border: true),
    ];
    final List<_ColorToken> backgroundTokens = [
      _ColorToken('background', c.background, border: true),
      _ColorToken('surface', c.surface, border: true),
      _ColorToken('surfacePrimarySoft', c.surfacePrimarySoft),
      _ColorToken('surfaceNeutralSoft', c.surfaceNeutralSoft),
      _ColorToken('surfaceErrorSoft', c.surfaceErrorSoft),
    ];
    final List<_ColorToken> contentTokens = [
      _ColorToken('onBackground', c.onBackground),
      _ColorToken('onSurface', c.onSurface),
      _ColorToken('muted', c.muted),
      _ColorToken('outline', c.outline, border: true),
      _ColorToken('outlineButton', c.outlineButton, border: true),
    ];
    final List<_ColorToken> greyTokens = [
      _ColorToken('grey1', c.grey1),
      _ColorToken('grey2', c.grey2),
      _ColorToken('grey3', c.grey3),
    ];
    final List<_ColorToken> fieldTokens = [
      _ColorToken('onSurface (label)', c.onSurface),
      _ColorToken('onSurface 54% (helper)', c.onSurface.withValues(alpha: 0.54)),
      _ColorToken('onSurface 45% (hint)', c.onSurface.withValues(alpha: 0.45)),
      _ColorToken('onSurface 62% (icon)', c.onSurface.withValues(alpha: 0.62)),
    ];
    final List<_ColorToken> avatarTokens = [
      _ColorToken('avatarFallbackFill', c.avatarFallbackFill),
    ];
    final List<_ColorToken> premiumTokens = [
      _ColorToken('premiumOverlayMid', c.premiumOverlayMid),
      _ColorToken('premiumOverlayDark', c.premiumOverlayDark),
      _ColorToken('premiumBannerText', c.premiumBannerText),
    ];

    return _TokenCard(
      children: [
        const _ColorGroupLabel('Brand'),
        ..._buildColorRows(context, brandTokens),
        const _TokenDivider(),
        const _ColorGroupLabel('Semantic'),
        ..._buildColorRows(context, semanticTokens),
        const _TokenDivider(),
        const _ColorGroupLabel('Background & Surface'),
        ..._buildColorRows(context, backgroundTokens),
        const _TokenDivider(),
        const _ColorGroupLabel('Content'),
        ..._buildColorRows(context, contentTokens),
        const _TokenDivider(),
        const _ColorGroupLabel('Grey Scale'),
        ..._buildColorRows(context, greyTokens),
        const _TokenDivider(),
        const _ColorGroupLabel('Field'),
        ..._buildColorRows(context, fieldTokens),
        const _TokenDivider(),
        const _ColorGroupLabel('Avatar'),
        ..._buildColorRows(context, avatarTokens),
        const _TokenDivider(),
        const _ColorGroupLabel('Premium'),
        ..._buildColorRows(context, premiumTokens),
      ],
    );
  }

  List<Widget> _buildColorRows(BuildContext context, List<_ColorToken> tokens) {
    return tokens.map((t) => _ColorRow(token: t)).toList();
  }
}

class _ColorToken {
  final String name;
  final Color color;
  final bool border;
  const _ColorToken(this.name, this.color, {this.border = false});
}

class _ColorGroupLabel extends StatelessWidget {
  final String label;
  const _ColorGroupLabel(this.label);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(KasySpacing.md, KasySpacing.smd, KasySpacing.md, KasySpacing.xs),
      child: Text(
        label,
        style: context.textTheme.labelSmall?.copyWith(
          color: context.colors.muted,
          letterSpacing: 0.6,
        ),
      ),
    );
  }
}

class _ColorRow extends StatelessWidget {
  final _ColorToken token;
  const _ColorRow({required this.token});

  @override
  Widget build(BuildContext context) {
    final String hex =
        '#${token.color.toARGB32().toRadixString(16).substring(2).toUpperCase()}';
    return Padding(
      padding: const EdgeInsets.symmetric(
        horizontal: KasySpacing.md,
        vertical: 10,
      ),
      child: Row(
        children: [
          Container(
            width: 28,
            height: 28,
            decoration: BoxDecoration(
              color: token.color,
              borderRadius: BorderRadius.circular(KasyRadius.xs),
              border: token.border
                  ? Border.all(
                      color: context.colors.outline.withValues(alpha: 0.5),
                    )
                  : null,
            ),
          ),
          const SizedBox(width: KasySpacing.smd),
          Expanded(
            child: Text(
              token.name,
              style: context.textTheme.bodyMedium?.copyWith(
                color: context.colors.onSurface,
              ),
            ),
          ),
          Text(
            hex,
            style: context.textTheme.bodySmall?.copyWith(
              color: context.colors.muted,
              fontFeatures: const [FontFeature.tabularFigures()],
            ),
          ),
        ],
      ),
    );
  }
}

// ---------------------------------------------------------------------------
// Typography
// ---------------------------------------------------------------------------

class _TypographySection extends StatelessWidget {
  const _TypographySection();

  @override
  Widget build(BuildContext context) {
    final tt = context.textTheme;
    final ktt = KasyTextTheme.build();

    final List<_TypeToken> tokens = [
      _TypeToken('displayLarge', tt.displayLarge, ktt.displayLarge),
      _TypeToken('displayMedium', tt.displayMedium, ktt.displayMedium),
      _TypeToken('displaySmall', tt.displaySmall, ktt.displaySmall),
      _TypeToken('headlineLarge', tt.headlineLarge, ktt.headlineLarge),
      _TypeToken('headlineMedium', tt.headlineMedium, ktt.headlineMedium),
      _TypeToken('headlineSmall', tt.headlineSmall, ktt.headlineSmall),
      _TypeToken('titleLarge', tt.titleLarge, ktt.titleLarge),
      _TypeToken('titleMedium', tt.titleMedium, ktt.titleMedium),
      _TypeToken('titleSmall', tt.titleSmall, ktt.titleSmall),
      _TypeToken('bodyLarge', tt.bodyLarge, ktt.bodyLarge),
      _TypeToken('bodyMedium', tt.bodyMedium, ktt.bodyMedium),
      _TypeToken('bodySmall', tt.bodySmall, ktt.bodySmall),
      _TypeToken('labelLarge', tt.labelLarge, ktt.labelLarge),
      _TypeToken('labelMedium', tt.labelMedium, ktt.labelMedium),
      _TypeToken('labelSmall', tt.labelSmall, ktt.labelSmall),
    ];

    return _TokenCard(
      children: tokens
          .map(
            (t) => Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                _TypeRow(token: t),
                if (t != tokens.last) const _TokenDivider(),
              ],
            ),
          )
          .toList(),
    );
  }
}

class _TypeToken {
  final String name;
  final TextStyle? style;
  final TextStyle raw;
  const _TypeToken(this.name, this.style, this.raw);
}

class _TypeRow extends StatelessWidget {
  final _TypeToken token;
  const _TypeRow({required this.token});

  @override
  Widget build(BuildContext context) {
    final double size = token.raw.fontSize ?? 14;
    final int weight = token.raw.fontWeight?.value ?? 400;
    return Padding(
      padding: const EdgeInsets.symmetric(
        horizontal: KasySpacing.md,
        vertical: KasySpacing.smd,
      ),
      child: Row(
        children: [
          Expanded(
            child: Text(
              token.name,
              style: token.style,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          const SizedBox(width: KasySpacing.md),
          Text(
            '${size.toInt()}/$weight',
            style: context.textTheme.bodySmall?.copyWith(
              color: context.colors.muted,
              fontFeatures: const [FontFeature.tabularFigures()],
            ),
          ),
        ],
      ),
    );
  }
}

// ---------------------------------------------------------------------------
// Spacing
// ---------------------------------------------------------------------------

class _SpacingSection extends StatelessWidget {
  const _SpacingSection();

  static const List<({String name, double value})> _tokens = [
    (name: 'xs', value: KasySpacing.xs),
    (name: 'sm', value: KasySpacing.sm),
    (name: 'smd', value: KasySpacing.smd),
    (name: 'md', value: KasySpacing.md),
    (name: 'lg', value: KasySpacing.lg),
    (name: 'xl', value: KasySpacing.xl),
    (name: 'xxl', value: KasySpacing.xxl),
    (name: 'xxxl', value: KasySpacing.xxxl),
  ];

  @override
  Widget build(BuildContext context) {
    return _TokenCard(
      children: List.generate(_tokens.length, (i) {
        final t = _tokens[i];
        return Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _SpacingRow(name: t.name, value: t.value),
            if (i < _tokens.length - 1) const _TokenDivider(),
          ],
        );
      }),
    );
  }
}

class _SpacingRow extends StatelessWidget {
  final String name;
  final double value;
  const _SpacingRow({required this.name, required this.value});

  @override
  Widget build(BuildContext context) {
    const double maxBarWidth = 160;
    const double maxValue = KasySpacing.xxxl;
    final double barWidth = (value / maxValue) * maxBarWidth;

    return Padding(
      padding: const EdgeInsets.symmetric(
        horizontal: KasySpacing.md,
        vertical: 10,
      ),
      child: Row(
        children: [
          SizedBox(
            width: 40,
            child: Text(
              name,
              style: context.textTheme.bodyMedium?.copyWith(
                color: context.colors.onSurface,
              ),
            ),
          ),
          const SizedBox(width: KasySpacing.md),
          Container(
            width: barWidth,
            height: 10,
            decoration: BoxDecoration(
              color: context.colors.primary.withValues(alpha: 0.72),
              borderRadius: BorderRadius.circular(KasyRadius.xs),
            ),
          ),
          const SizedBox(width: KasySpacing.smd),
          Text(
            '${value.toInt()}px',
            style: context.textTheme.bodySmall?.copyWith(
              color: context.colors.muted,
              fontFeatures: const [FontFeature.tabularFigures()],
            ),
          ),
        ],
      ),
    );
  }
}

// ---------------------------------------------------------------------------
// Radius
// ---------------------------------------------------------------------------

class _RadiusSection extends StatelessWidget {
  const _RadiusSection();

  static const List<({String name, double value})> _tokens = [
    (name: 'xs', value: KasyRadius.xs),
    (name: 'sm', value: KasyRadius.sm),
    (name: 'md', value: KasyRadius.md),
    (name: 'lg', value: KasyRadius.lg),
    (name: 'xl', value: KasyRadius.xl),
    (name: 'full', value: 999),
  ];

  @override
  Widget build(BuildContext context) {
    return _TokenCard(
      children: List.generate(_tokens.length, (i) {
        final t = _tokens[i];
        return Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _RadiusRow(name: t.name, value: t.value),
            if (i < _tokens.length - 1) const _TokenDivider(),
          ],
        );
      }),
    );
  }
}

class _RadiusRow extends StatelessWidget {
  final String name;
  final double value;
  const _RadiusRow({required this.name, required this.value});

  @override
  Widget build(BuildContext context) {
    final double clampedRadius = value.clamp(0, 20);
    return Padding(
      padding: const EdgeInsets.symmetric(
        horizontal: KasySpacing.md,
        vertical: 10,
      ),
      child: Row(
        children: [
          SizedBox(
            width: 40,
            child: Text(
              name,
              style: context.textTheme.bodyMedium?.copyWith(
                color: context.colors.onSurface,
              ),
            ),
          ),
          const SizedBox(width: KasySpacing.md),
          Container(
            width: 36,
            height: 36,
            decoration: BoxDecoration(
              color: context.colors.primary.withValues(alpha: 0.12),
              border: Border.all(
                color: context.colors.primary.withValues(alpha: 0.5),
                width: 1.5,
              ),
              borderRadius: BorderRadius.circular(clampedRadius),
            ),
          ),
          const SizedBox(width: KasySpacing.smd),
          Text(
            value >= 999 ? 'full' : '${value.toInt()}px',
            style: context.textTheme.bodySmall?.copyWith(
              color: context.colors.muted,
              fontFeatures: const [FontFeature.tabularFigures()],
            ),
          ),
        ],
      ),
    );
  }
}

// ---------------------------------------------------------------------------
// Shared card shell
// ---------------------------------------------------------------------------

class _TokenCard extends StatelessWidget {
  final List<Widget> children;
  const _TokenCard({required this.children});

  @override
  Widget build(BuildContext context) {
    const double radius = 16;
    final bool isDark = context.isDark;
    return DecoratedBox(
      decoration: BoxDecoration(
        color: context.colors.surface,
        borderRadius: BorderRadius.circular(radius),
        border: Border.all(
          color: context.colors.outline.withValues(alpha: 0.4),
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: isDark ? 0.22 : 0.06),
            blurRadius: 14,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(radius),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: children,
        ),
      ),
    );
  }
}
