import 'package:flutter/material.dart';
import 'package:kasy_kit/components/kasy_app_bar.dart';
import 'package:kasy_kit/core/bottom_menu/bart_inner_paths.dart';
import 'package:kasy_kit/core/haptics/kasy_haptics.dart';
import 'package:kasy_kit/core/theme/theme.dart';
import 'package:kasy_kit/core/widgets/kasy_hover.dart';
import 'package:kasy_kit/core/widgets/kasy_scroll_behavior.dart';
import 'package:kasy_kit/features/home/home_components_preview_page.dart';
import 'package:kasy_kit/features/home/home_components_preview_registry.dart';

/// UI-kit catalog, reachable from the home dashboard.
///
/// Unlike [KasyOverlayScaffold] screens, the frosted bar does not overlay the list:
/// scroll lives **inside** the inset card so the catalog reads as a contained sheet.
class HomeComponentsPage extends StatelessWidget {
  const HomeComponentsPage({super.key});

  static int get sectionCount => _kCatalog.length;

  @override
  Widget build(BuildContext context) {
    final Color headerBg = context.colors.background;
    return Scaffold(
      backgroundColor: headerBg,
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          KasyAppBar(
            title: 'Components',
            onBack: () => Navigator.maybePop(context),
          ),
          Expanded(
            child: Padding(
              padding: EdgeInsets.fromLTRB(
                KasySpacing.pageHorizontalGutter,
                KasySpacing.belowChromeContentGap,
                KasySpacing.pageHorizontalGutter,
                MediaQuery.paddingOf(context).bottom +
                    KasySpacing.belowChromeContentGap,
              ),
              child: _componentsCatalogInset(
                context,
                child: Padding(
                  padding: const EdgeInsets.symmetric(
                    horizontal: KasySpacing.xs,
                  ),
                  child: ScrollConfiguration(
                    behavior: const KasyKitScrollBehavior(),
                    child: ListView.separated(
                      padding: EdgeInsets.zero,
                      itemCount: _kCatalog.length + 1,
                      separatorBuilder: (context, index) => Divider(
                        height: 1,
                        thickness: 1,
                        indent: KasySpacing.md,
                        endIndent: KasySpacing.md,
                        color: context.colors.outline.withValues(alpha: 0.33),
                      ),
                      itemBuilder: (context, index) {
                        if (index >= _kCatalog.length) {
                          return const SizedBox(height: KasySpacing.sm);
                        }
                        final _CatalogRow row = _kCatalog[index];
                        return KasyHover(
                          hapticEnabled: false,
                          onTap: () {
                            KasyHaptics.selection(context);
                            if (row.name == 'Design System') {
                              Navigator.of(context).pushNamed(
                                bartInnerPath('home', 'design-system'),
                              );
                              return;
                            }
                            final ComponentPreviewDefinition? definition =
                                getComponentPreviewDefinition(row.name);
                            if (definition == null) {
                              return;
                            }
                            Navigator.of(context).pushNamed(
                              bartInnerPath('home', 'components-preview'),
                              arguments: HomeComponentPreviewRouteExtra(
                                title: definition.title,
                                variants: definition.variants,
                              ),
                            );
                          },
                          child: Padding(
                            padding: const EdgeInsets.symmetric(
                              horizontal: KasySpacing.smd,
                              vertical: 16,
                            ),
                            child: Row(
                                children: [
                                  Expanded(
                                    child: Row(
                                      children: [
                                        Flexible(
                                          child: Text(
                                            row.name,
                                            style: context.textTheme.titleMedium,
                                          ),
                                        ),
                                        if (_kReadyComponents.contains(
                                          row.name,
                                        )) ...[
                                          const SizedBox(width: KasySpacing.sm),
                                          Text(
                                            'Pronto',
                                            style: context.textTheme.bodySmall
                                                ?.copyWith(
                                                  color: context.colors.success,
                                                  fontWeight: FontWeight.w600,
                                                ),
                                          ),
                                        ],
                                        if (_kWebReadyComponents.contains(
                                          row.name,
                                        )) ...[
                                          const SizedBox(width: KasySpacing.xs),
                                          Text(
                                            'Web',
                                            style: context.textTheme.bodySmall
                                                ?.copyWith(
                                                  color: context.colors.primary,
                                                  fontWeight: FontWeight.w600,
                                                ),
                                          ),
                                        ],
                                        if (_kUrgentComponents.contains(
                                          row.name,
                                        )) ...[
                                          const SizedBox(width: KasySpacing.sm),
                                          Text(
                                            'Prioridade: Urgente',
                                            style: context.textTheme.bodySmall
                                                ?.copyWith(
                                                  color: context.colors.warning,
                                                  fontWeight: FontWeight.w700,
                                                ),
                                          ),
                                        ],
                                      ],
                                    ),
                                  ),
                                  Icon(
                                    KasyIcons.chevronRight,
                                    color: context.colors.muted,
                                    size: 22,
                                  ),
                                ],
                            ),
                          ),
                        );

                      },
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _CatalogRow {
  final String name;

  const _CatalogRow(this.name);
}

const Set<String> _kReadyComponents = <String>{
  'Accordion',
  'Alert',
  'AppBar',
  'Avatar',
  'Badge',
  'BottomSheet',
  'Button',
  'Card',
  'Checkbox',
  'Design System',
  'Dialog',
  'Hover',
  'Tabs',
  'TextArea',
  'TextField',
  'Sidebar',
  'Skeleton',
  'SwipeAction',
  'TextFieldOTP',
  'Toast',
};

/// Components that have been adapted for web (cursor, hover, shadow, border).
const Set<String> _kWebReadyComponents = <String>{
  'Accordion',
  'Alert',
  'AppBar',
  'Avatar',
  'Badge',
  'BottomSheet',
  'Button',
  'Card',
  'Checkbox',
  'Design System',
  'Dialog',
  'Hover',
  'Sidebar',
  'Skeleton',
  'SwipeAction',
  'TextArea',
  'TextField',
  'TextFieldOTP',
  'Toast',
};

const Set<String> _kUrgentComponents = <String>{
  'Switch',
  'Radio Group',
  'DatePicker',
};

const List<_CatalogRow> _kCatalog = [
  // Design System — tokens showcase
  _CatalogRow('Design System'),
  // Pronto (_kReadyComponents), A–Z
  _CatalogRow('Accordion'),
  _CatalogRow('Alert'),
  _CatalogRow('AppBar'),
  _CatalogRow('Avatar'),
  _CatalogRow('Badge'),
  _CatalogRow('BottomSheet'),
  _CatalogRow('Button'),
  _CatalogRow('Card'),
  _CatalogRow('Checkbox'),
  _CatalogRow('Dialog'),
  _CatalogRow('Hover'),
  _CatalogRow('Sidebar'),
  _CatalogRow('Skeleton'),
  _CatalogRow('SwipeAction'),
  _CatalogRow('TextArea'),
  _CatalogRow('TextField'),
  _CatalogRow('TextFieldOTP'),
  _CatalogRow('Toast'),
  // Prioridade: Urgente (_kUrgentComponents), A–Z
  _CatalogRow('DatePicker'),
  _CatalogRow('Radio Group'),
  _CatalogRow('Switch'),
  _CatalogRow('Tabs'),
  // Demais, A–Z
  _CatalogRow('BarChart'),
  _CatalogRow('Calendar'),
  _CatalogRow('Chip'),
  _CatalogRow('CloseButton'),
  _CatalogRow('ControlField'),
  _CatalogRow('DateField'),
  _CatalogRow('DateRangePicker'),
  _CatalogRow('Description'),
  _CatalogRow('FieldError'),
  _CatalogRow('TextFieldGroup'),
  _CatalogRow('TextFieldOTPGroup'),
  _CatalogRow('Label'),
  _CatalogRow('LineChart'),
  _CatalogRow('LinkButton'),
  _CatalogRow('ListGroup'),
  _CatalogRow('Menu'),
  _CatalogRow('NumberField'),
  _CatalogRow('NumberStepper'),
  _CatalogRow('NumberValue'),
  _CatalogRow('Popover'),
  _CatalogRow('PressableFeedback'),
  _CatalogRow('ProgressBar'),
  _CatalogRow('ProgressButton'),
  _CatalogRow('ProgressCircle'),
  _CatalogRow('Radio ButtonGroup'),
  _CatalogRow('RangeCalendar'),
  _CatalogRow('Rating'),
  _CatalogRow('ScrollShadow'),
  _CatalogRow('SearchFieldSelect'),
  _CatalogRow('Separator'),
  _CatalogRow('SlideButton'),
  _CatalogRow('Slider'),
  _CatalogRow('SocialAuthButton'),
  _CatalogRow('Spinner'),
  _CatalogRow('SplitView'),
  _CatalogRow('Stepper'),
  _CatalogRow('Surface'),
  _CatalogRow('TagGroup'),
  _CatalogRow('ToggleButton'),
  _CatalogRow('ToggleButtonGroup'),
  _CatalogRow('TrendChip'),
  _CatalogRow('Widget'),
];

/// UI-kit catalog only — inset list surface (not a shared app shell).
Widget _componentsCatalogInset(BuildContext context, {required Widget child}) {
  const double radius = 24;
  final bool isDark = Theme.of(context).brightness == Brightness.dark;
  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.07),
          blurRadius: 18,
          offset: const Offset(0, 6),
        ),
      ],
    ),
    child: ClipRRect(borderRadius: BorderRadius.circular(radius), child: child),
  );
}
