import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:shadcn_ui/shadcn_ui.dart';

import 'package:superport_v2/core/constants/app_sections.dart';
import 'package:superport_v2/widgets/app_layout.dart';
import 'package:superport_v2/widgets/components/filter_bar.dart';
import 'package:superport_v2/widgets/components/superport_pagination_controls.dart';
import 'package:superport_v2/widgets/components/superport_table.dart';

import '../../../../../core/config/environment.dart';
import '../../../../../widgets/spec_page.dart';
import '../../domain/entities/menu.dart';
import '../../domain/repositories/menu_repository.dart';
import '../controllers/menu_controller.dart' as menu;
import '../dialogs/menu_detail_dialog.dart';

/// 메뉴 관리 페이지. 기능 플래그에 따라 사양/실제 화면을 전환한다.
class MenuPage extends StatelessWidget {
  const MenuPage({super.key});

  @override
  Widget build(BuildContext context) {
    final enabled = Environment.flag('FEATURE_MENUS_ENABLED');
    if (!enabled) {
      return SpecPage(
        title: '메뉴 관리',
        summary: '메뉴 코드, 트리 구조, 사용여부를 관리합니다.',
        trailing: ShadBadge(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Icon(LucideIcons.info, size: 14),
                const SizedBox(width: 6),
                const Text('비활성화 (백엔드 준비 중)'),
              ],
            ),
          ),
        ),
        sections: const [
          SpecSection(
            title: '입력 폼',
            items: [
              '메뉴코드 [Text]',
              '메뉴명 [Text]',
              '상위메뉴 [Dropdown]',
              '경로 [Text]',
              '표시순서 [Number]',
              '사용여부 [Switch]',
              '비고 [Text]',
            ],
          ),
          SpecSection(
            title: '수정 폼',
            items: ['메뉴코드 [ReadOnly]', '생성일시 [ReadOnly]'],
          ),
          SpecSection(
            title: '테이블 리스트',
            description: '1행 예시',
            table: SpecTable(
              columns: [
                '번호',
                '메뉴코드',
                '메뉴명',
                '상위메뉴',
                '경로',
                '사용여부',
                '비고',
                '변경일시',
              ],
              rows: [
                [
                  '1',
                  'MENU001',
                  '대시보드',
                  '-',
                  '/dashboard',
                  'Y',
                  '-',
                  '2024-03-01 10:00',
                ],
              ],
            ),
          ),
        ],
      );
    }

    return const _MenuEnabledPage();
  }
}

/// 메뉴 기능이 활성화된 경우 사용하는 실제 화면 위젯.
class _MenuEnabledPage extends StatefulWidget {
  const _MenuEnabledPage();

  @override
  State<_MenuEnabledPage> createState() => _MenuEnabledPageState();
}

/// 메뉴 목록과 필터를 관리하는 상태 클래스.
class _MenuEnabledPageState extends State<_MenuEnabledPage> {
  late final menu.MenuController _controller;
  final TextEditingController _searchController = TextEditingController();
  final FocusNode _searchFocus = FocusNode();
  final DateFormat _dateFormat = DateFormat('yyyy-MM-dd HH:mm');
  String? _lastError;

  @override
  void initState() {
    super.initState();
    _controller = menu.MenuController(repository: GetIt.I<MenuRepository>())
      ..addListener(_handleControllerUpdate);
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await _controller.loadParents();
      await _controller.fetch();
    });
  }

  void _handleControllerUpdate() {
    final error = _controller.errorMessage;
    if (error != null && error != _lastError && mounted) {
      _lastError = error;
      final messenger = ScaffoldMessenger.maybeOf(context);
      if (messenger != null) {
        messenger.showSnackBar(SnackBar(content: Text(error)));
      }
      _controller.clearError();
    }
  }

  @override
  void dispose() {
    _controller.removeListener(_handleControllerUpdate);
    _controller.dispose();
    _searchController.dispose();
    _searchFocus.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);

    return AnimatedBuilder(
      animation: _controller,
      builder: (context, _) {
        final result = _controller.result;
        final menus = result?.items ?? const <MenuItem>[];
        final totalCount = result?.total ?? 0;
        final currentPage = result?.page ?? 1;
        final totalPages = result == null || result.pageSize == 0
            ? 1
            : (result.total / result.pageSize).ceil().clamp(1, 9999);

        final showReset =
            _searchController.text.isNotEmpty ||
            _controller.parentFilter != null ||
            _controller.statusFilter != menu.MenuStatusFilter.all ||
            _controller.includeDeleted;

        return AppLayout(
          title: '메뉴 관리',
          subtitle: '메뉴 트리와 경로, 사용 상태를 관리합니다.',
          breadcrumbs: const [
            AppBreadcrumbItem(label: '대시보드', path: dashboardRoutePath),
            AppBreadcrumbItem(label: '마스터', path: '/masters/menus'),
            AppBreadcrumbItem(label: '메뉴'),
          ],
          actions: [
            ShadButton(
              leading: const Icon(LucideIcons.plus, size: 16),
              onPressed: _controller.isSubmitting
                  ? null
                  : _openMenuCreateDialog,
              child: const Text('신규 등록'),
            ),
          ],
          toolbar: FilterBar(
            actions: [
              ShadButton.outline(
                onPressed: _controller.isLoading ? null : _applyFilters,
                child: const Text('검색 적용'),
              ),
              if (showReset)
                ShadButton.ghost(
                  onPressed: _controller.isLoading
                      ? null
                      : () {
                          _searchController.clear();
                          _searchFocus.requestFocus();
                          _controller.updateQuery('');
                          _controller.updateParentFilter(null);
                          _controller.updateStatusFilter(
                            menu.MenuStatusFilter.all,
                          );
                          _controller.updateIncludeDeleted(false);
                          _controller.fetch(page: 1);
                        },
                  child: const Text('초기화'),
                ),
            ],
            children: [
              SizedBox(
                width: 260,
                child: ShadInput(
                  controller: _searchController,
                  focusNode: _searchFocus,
                  placeholder: const Text('메뉴코드, 메뉴명 검색'),
                  leading: const Icon(LucideIcons.search, size: 16),
                  onSubmitted: (_) => _applyFilters(),
                ),
              ),
              SizedBox(
                width: 220,
                child: ShadSelect<int?>(
                  key: ValueKey(_controller.parentFilter),
                  initialValue: _controller.parentFilter,
                  placeholder: Text(
                    _controller.isLoadingParents ? '상위 로딩중...' : '상위 전체',
                  ),
                  selectedOptionBuilder: (context, value) {
                    if (value == null) {
                      return Text(
                        _controller.isLoadingParents ? '상위 로딩중...' : '상위 전체',
                      );
                    }
                    final target = _controller.parents.firstWhere(
                      (menuItem) => menuItem.id == value,
                      orElse: () =>
                          MenuItem(id: value, menuCode: '', menuName: ''),
                    );
                    final label = target.menuName.isEmpty
                        ? '상위 전체'
                        : target.menuName;
                    return Text(label);
                  },
                  onChanged: _controller.isLoadingParents
                      ? null
                      : (value) {
                          _controller.updateParentFilter(value);
                          _controller.fetch(page: 1);
                        },
                  options: [
                    const ShadOption<int?>(value: null, child: Text('상위 전체')),
                    ..._controller.parents.map(
                      (menuItem) => ShadOption<int?>(
                        value: menuItem.id,
                        child: Text(menuItem.menuName),
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(
                width: 200,
                child: ShadSelect<menu.MenuStatusFilter>(
                  key: ValueKey(_controller.statusFilter),
                  initialValue: _controller.statusFilter,
                  selectedOptionBuilder: (context, filter) =>
                      Text(_statusLabel(filter)),
                  onChanged: (value) {
                    if (value == null) return;
                    _controller.updateStatusFilter(value);
                    _controller.fetch(page: 1);
                  },
                  options: menu.MenuStatusFilter.values
                      .map(
                        (filter) => ShadOption(
                          value: filter,
                          child: Text(_statusLabel(filter)),
                        ),
                      )
                      .toList(),
                ),
              ),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  ShadSwitch(
                    value: _controller.includeDeleted,
                    onChanged: (value) {
                      _controller.updateIncludeDeleted(value);
                      _controller.fetch(page: 1);
                    },
                  ),
                  const SizedBox(width: 8),
                  const Text('삭제 포함'),
                ],
              ),
            ],
          ),
          child: ShadCard(
            title: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text('메뉴 목록', style: theme.textTheme.h3),
                Text('$totalCount건', style: theme.textTheme.muted),
              ],
            ),
            footer: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '페이지 $currentPage / $totalPages',
                  style: theme.textTheme.small,
                ),
                SuperportPaginationControls(
                  currentPage: currentPage,
                  totalPages: totalPages,
                  isBusy: _controller.isLoading,
                  onPageSelected: (page) => _controller.fetch(page: page),
                ),
              ],
            ),
            child: _controller.isLoading
                ? const Padding(
                    padding: EdgeInsets.all(48),
                    child: Center(child: CircularProgressIndicator()),
                  )
                : menus.isEmpty
                ? Padding(
                    padding: const EdgeInsets.all(32),
                    child: Text(
                      '조건에 맞는 메뉴가 없습니다.',
                      style: theme.textTheme.muted,
                    ),
                  )
                : _MenuTable(
                    menus: menus,
                    dateFormat: _dateFormat,
                    onRowTap: _controller.isSubmitting
                        ? null
                        : _openMenuDetailDialog,
                  ),
          ),
        );
      },
    );
  }

  void _applyFilters() {
    _controller.updateQuery(_searchController.text.trim());
    _controller.fetch(page: 1);
  }

  String _statusLabel(menu.MenuStatusFilter filter) {
    switch (filter) {
      case menu.MenuStatusFilter.all:
        return '전체(사용/미사용)';
      case menu.MenuStatusFilter.activeOnly:
        return '사용중';
      case menu.MenuStatusFilter.inactiveOnly:
        return '미사용';
    }
  }

  Future<void> _openMenuCreateDialog() async {
    final result = await showMenuDetailDialog(
      context: context,
      dateFormat: _dateFormat,
      parents: _controller.parents,
      isLoadingParents: _controller.isLoadingParents,
      onCreate: _controller.create,
      onUpdate: _controller.update,
      onDelete: _controller.delete,
      onRestore: _controller.restore,
    );
    if (result != null && mounted) {
      _showSnack(result.message);
    }
  }

  Future<void> _openMenuDetailDialog(MenuItem menu) async {
    final menuId = menu.id;
    if (menuId == null) {
      _showSnack('ID 정보가 없어 상세를 열 수 없습니다.');
      return;
    }
    final result = await showMenuDetailDialog(
      context: context,
      dateFormat: _dateFormat,
      menu: menu,
      parents: _controller.parents,
      isLoadingParents: _controller.isLoadingParents,
      onCreate: _controller.create,
      onUpdate: _controller.update,
      onDelete: _controller.delete,
      onRestore: _controller.restore,
    );
    if (result != null && mounted) {
      _showSnack(result.message);
    }
  }

  void _showSnack(String message) {
    if (!mounted) {
      return;
    }
    final messenger = ScaffoldMessenger.maybeOf(context);
    if (messenger == null) {
      return;
    }
    messenger.showSnackBar(SnackBar(content: Text(message)));
  }
}

class _MenuTable extends StatelessWidget {
  const _MenuTable({
    required this.menus,
    required this.dateFormat,
    required this.onRowTap,
  });

  final List<MenuItem> menus;
  final DateFormat dateFormat;
  final void Function(MenuItem menu)? onRowTap;

  @override
  Widget build(BuildContext context) {
    final columns = const [
      Text('ID'),
      Text('메뉴코드'),
      Text('메뉴명'),
      Text('상위메뉴'),
      Text('경로'),
      Text('사용'),
      Text('삭제'),
      Text('비고'),
      Text('변경일시'),
    ];

    final rows = menus
        .map(
          (item) => <Widget>[
            Text(item.id?.toString() ?? '-'),
            Text(item.menuCode),
            Text(item.menuName),
            Text(item.parent?.menuName ?? '-'),
            Text(item.path?.isEmpty ?? true ? '-' : item.path!),
            Text(item.isActive ? 'Y' : 'N'),
            Text(item.isDeleted ? 'Y' : '-'),
            Text(item.note?.isEmpty ?? true ? '-' : item.note!),
            Text(
              item.updatedAt == null
                  ? '-'
                  : dateFormat.format(item.updatedAt!.toLocal()),
            ),
          ],
        )
        .toList();

    return SuperportTable(
      columns: columns,
      rows: rows,
      rowHeight: 56,
      maxHeight: 56.0 * (menus.length + 1),
      onRowTap: onRowTap == null
          ? null
          : (index) {
              if (index < 0 || index >= menus.length) {
                return;
              }
              onRowTap!(menus[index]);
            },
      columnSpanExtent: (index) => switch (index) {
        3 => const FixedTableSpanExtent(180),
        4 => const FixedTableSpanExtent(200),
        7 => const FixedTableSpanExtent(200),
        8 => const FixedTableSpanExtent(160),
        _ => const FixedTableSpanExtent(120),
      },
    );
  }
}
