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/group.dart';
import '../../domain/repositories/group_repository.dart';
import '../dialogs/group_detail_dialog.dart';
import '../controllers/group_controller.dart';

/// 권한 그룹 관리 페이지. 기능 플래그에 따라 사양 화면 또는 실제 목록을 보여준다.
class GroupPage extends StatelessWidget {
  const GroupPage({super.key});

  @override
  Widget build(BuildContext context) {
    final enabled = Environment.flag('FEATURE_GROUPS_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),
                Text('비활성화 (백엔드 준비 중)'),
              ],
            ),
          ),
        ),
        sections: const [
          SpecSection(
            title: '입력 폼',
            items: [
              '그룹명 [Text]',
              '설명 [Textarea]',
              '기본여부 [Switch]',
              '사용여부 [Switch]',
              '비고 [Textarea]',
            ],
          ),
          SpecSection(
            title: '수정 폼',
            items: ['그룹명 [ReadOnly]', '생성일시 [ReadOnly]'],
          ),
          SpecSection(
            title: '테이블 리스트',
            description: '1행 예시',
            table: SpecTable(
              columns: ['번호', '그룹명', '설명', '기본여부', '사용여부', '비고', '변경일시'],
              rows: [
                ['1', '관리자', '시스템 전체 권한', 'Y', 'Y', '-', '2024-03-01 10:00'],
              ],
            ),
          ),
        ],
      );
    }

    return const _GroupEnabledPage();
  }
}

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

  @override
  State<_GroupEnabledPage> createState() => _GroupEnabledPageState();
}

/// 그룹 목록과 필터/폼 상태를 관리하는 상태 클래스.
class _GroupEnabledPageState extends State<_GroupEnabledPage> {
  late final GroupController _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 = GroupController(repository: GetIt.I<GroupRepository>())
      ..addListener(_handleControllerUpdate);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _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 groups = result?.items ?? const <Group>[];
        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.defaultFilter != GroupDefaultFilter.all ||
            _controller.statusFilter != GroupStatusFilter.all;

        return AppLayout(
          title: '그룹 관리',
          subtitle: '권한 그룹 정의와 기본 여부, 사용 상태를 관리합니다.',
          breadcrumbs: const [
            AppBreadcrumbItem(label: '대시보드', path: dashboardRoutePath),
            AppBreadcrumbItem(label: '마스터', path: '/masters/groups'),
            AppBreadcrumbItem(label: '그룹'),
          ],
          actions: [
            ShadButton(
              leading: const Icon(LucideIcons.plus, size: 16),
              onPressed: _controller.isSubmitting
                  ? null
                  : _openGroupCreateDialog,
              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.updateDefaultFilter(
                            GroupDefaultFilter.all,
                          );
                          _controller.updateStatusFilter(GroupStatusFilter.all);
                          _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: 200,
                child: ShadSelect<GroupDefaultFilter>(
                  key: ValueKey(_controller.defaultFilter),
                  initialValue: _controller.defaultFilter,
                  selectedOptionBuilder: (context, filter) =>
                      Text(_defaultLabel(filter)),
                  onChanged: (value) {
                    if (value == null) return;
                    _controller.updateDefaultFilter(value);
                    _controller.fetch(page: 1);
                  },
                  options: GroupDefaultFilter.values
                      .map(
                        (filter) => ShadOption(
                          value: filter,
                          child: Text(_defaultLabel(filter)),
                        ),
                      )
                      .toList(),
                ),
              ),
              SizedBox(
                width: 200,
                child: ShadSelect<GroupStatusFilter>(
                  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: GroupStatusFilter.values
                      .map(
                        (filter) => ShadOption(
                          value: filter,
                          child: Text(_statusLabel(filter)),
                        ),
                      )
                      .toList(),
                ),
              ),
            ],
          ),
          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()),
                  )
                : groups.isEmpty
                ? Padding(
                    padding: const EdgeInsets.all(32),
                    child: Text(
                      '조건에 맞는 그룹이 없습니다.',
                      style: theme.textTheme.muted,
                    ),
                  )
                : _GroupTable(
                    groups: groups,
                    dateFormat: _dateFormat,
                    onRowTap: _controller.isSubmitting
                        ? null
                        : _openGroupDetailDialog,
                  ),
          ),
        );
      },
    );
  }

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

  String _defaultLabel(GroupDefaultFilter filter) {
    switch (filter) {
      case GroupDefaultFilter.all:
        return '전체(기본/일반)';
      case GroupDefaultFilter.defaultOnly:
        return '기본 그룹만';
      case GroupDefaultFilter.nonDefault:
        return '일반 그룹만';
    }
  }

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

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

  Future<void> _openGroupDetailDialog(Group group) async {
    final groupId = group.id;
    if (groupId == null) {
      _showSnack('ID 정보가 없어 상세를 열 수 없습니다.');
      return;
    }
    final result = await showGroupDetailDialog(
      context: context,
      dateFormat: _dateFormat,
      group: group,
      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 _GroupTable extends StatelessWidget {
  const _GroupTable({
    required this.groups,
    required this.dateFormat,
    required this.onRowTap,
  });

  final List<Group> groups;
  final DateFormat dateFormat;
  final void Function(Group group)? onRowTap;

  @override
  Widget build(BuildContext context) {
    final columns = const [
      Text('ID'),
      Text('그룹명'),
      Text('설명'),
      Text('기본'),
      Text('사용'),
      Text('삭제'),
      Text('비고'),
      Text('변경일시'),
    ];

    final rows = groups
        .map(
          (group) => <Widget>[
            Text(group.id?.toString() ?? '-'),
            Text(group.groupName),
            Text(group.description?.isEmpty ?? true ? '-' : group.description!),
            Text(group.isDefault ? 'Y' : 'N'),
            Text(group.isActive ? 'Y' : 'N'),
            Text(group.isDeleted ? 'Y' : '-'),
            Text(group.note?.isEmpty ?? true ? '-' : group.note!),
            Text(
              group.updatedAt == null
                  ? '-'
                  : dateFormat.format(group.updatedAt!.toLocal()),
            ),
          ],
        )
        .toList();

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