import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:intl/intl.dart' as intl;
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 '../../../../../core/permissions/permission_manager.dart';
import '../../../../../widgets/spec_page.dart';
import '../../../group/domain/entities/group.dart';
import '../../../group/domain/repositories/group_repository.dart';
import '../../../group_permission/domain/repositories/group_permission_repository.dart';
import '../../domain/entities/user.dart';
import '../../domain/repositories/user_repository.dart';
import '../controllers/user_controller.dart';
import '../dialogs/user_detail_dialog.dart';

/// 사용자 관리 페이지. 기능 플래그에 따라 사양/실제 화면을 보여준다.
class UserPage extends StatelessWidget {
  const UserPage({super.key});

  @override
  Widget build(BuildContext context) {
    final enabled = Environment.flag('FEATURE_USERS_ENABLED');
    if (!enabled) {
      return const SpecPage(
        title: '사용자(사원) 관리',
        summary: '사번 기반 계정과 그룹, 사용 상태를 관리합니다.',
        sections: [
          SpecSection(
            title: '입력 폼',
            items: [
              '사번 [Text]',
              '성명 [Text]',
              '이메일 [Text]',
              '연락처 [Text]',
              '그룹 [Dropdown]',
              '사용여부 [Switch]',
              '비고 [Text]',
            ],
          ),
          SpecSection(
            title: '수정 폼',
            items: ['사번 [ReadOnly]', '생성일시 [ReadOnly]'],
          ),
          SpecSection(
            title: '테이블 리스트',
            description: '1행 예시',
            table: SpecTable(
              columns: [
                '번호',
                '사번',
                '성명',
                '이메일',
                '연락처',
                '그룹',
                '사용여부',
                '비고',
                '변경일시',
              ],
              rows: [
                [
                  '1',
                  'A0001',
                  '김철수',
                  'kim@superport.com',
                  '010-1111-2222',
                  '관리자',
                  'Y',
                  '-',
                  '2024-03-01 10:00',
                ],
              ],
            ),
          ),
        ],
      );
    }

    return const _UserEnabledPage();
  }
}

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

  @override
  State<_UserEnabledPage> createState() => _UserEnabledPageState();
}

/// 사용자 목록과 필터 상태를 관리하는 상태 클래스.
class _UserEnabledPageState extends State<_UserEnabledPage> {
  late final UserController _controller;
  final TextEditingController _searchController = TextEditingController();
  final FocusNode _searchFocus = FocusNode();
  bool _groupsLoaded = false;
  String? _lastError;
  bool _initialized = false;
  final intl.DateFormat _dateFormat = intl.DateFormat('yyyy-MM-dd HH:mm');

  @override
  void initState() {
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (_initialized) {
      return;
    }
    final permissionManager = PermissionScope.of(context);
    _controller = UserController(
      userRepository: GetIt.I<UserRepository>(),
      groupRepository: GetIt.I<GroupRepository>(),
      permissionRepository: GetIt.I<GroupPermissionRepository>(),
      permissionManager: permissionManager,
    )..addListener(_handleControllerUpdate);
    _initialized = true;
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await _controller.loadGroups();
      await _controller.fetch();
      if (!mounted) return;
      setState(() {
        _groupsLoaded = true;
      });
    });
  }

  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 users = result?.items ?? const <UserAccount>[];
        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.groupFilter != null ||
            _controller.statusFilter != UserStatusFilter.all;

        return AppLayout(
          title: '사용자(사원) 관리',
          subtitle: '사번 기반 계정과 그룹, 사용 상태를 관리합니다.',
          breadcrumbs: const [
            AppBreadcrumbItem(label: '대시보드', path: dashboardRoutePath),
            AppBreadcrumbItem(label: '마스터', path: '/masters/users'),
            AppBreadcrumbItem(label: '사용자'),
          ],
          actions: [
            ShadButton(
              leading: const Icon(LucideIcons.plus, size: 16),
              onPressed: _controller.isSubmitting
                  ? null
                  : _openUserCreateDialog,
              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.updateGroupFilter(null);
                          _controller.updateStatusFilter(UserStatusFilter.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: 220,
                child: ShadSelect<int?>(
                  key: ValueKey(_controller.groupFilter),
                  initialValue: _controller.groupFilter,
                  placeholder: Text(_groupsLoaded ? '그룹 전체' : '그룹 로딩중...'),
                  selectedOptionBuilder: (context, value) {
                    if (value == null) {
                      return Text(_groupsLoaded ? '그룹 전체' : '그룹 로딩중...');
                    }
                    final group = _controller.groups.firstWhere(
                      (g) => g.id == value,
                      orElse: () => Group(id: value, groupName: ''),
                    );
                    return Text(group.groupName);
                  },
                  onChanged: _controller.isLoadingGroups
                      ? null
                      : (value) {
                          _controller.updateGroupFilter(value);
                        },
                  options: [
                    const ShadOption<int?>(value: null, child: Text('그룹 전체')),
                    ..._controller.groups.map(
                      (group) => ShadOption<int?>(
                        value: group.id,
                        child: Text(group.groupName),
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(
                width: 200,
                child: ShadSelect<UserStatusFilter>(
                  key: ValueKey(_controller.statusFilter),
                  initialValue: _controller.statusFilter,
                  selectedOptionBuilder: (context, filter) =>
                      Text(_statusLabel(filter)),
                  onChanged: (value) {
                    if (value == null) return;
                    _controller.updateStatusFilter(value);
                  },
                  options: UserStatusFilter.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()),
                  )
                : users.isEmpty
                ? Padding(
                    padding: const EdgeInsets.all(32),
                    child: Text(
                      '조건에 맞는 사용자가 없습니다.',
                      style: theme.textTheme.muted,
                    ),
                  )
                : _UserTable(
                    users: users,
                    dateFormat: _dateFormat,
                    onUserTap: _controller.isSubmitting
                        ? null
                        : _openUserDetailDialog,
                  ),
          ),
        );
      },
    );
  }

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

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

  Future<void> _openUserCreateDialog() async {
    if (!_groupsLoaded) {
      _showSnack('그룹 정보를 불러오는 중입니다. 잠시 후 다시 시도하세요.');
      return;
    }

    final result = await showUserDetailDialog(
      context: context,
      dateFormat: _dateFormat,
      groupOptions: _controller.groups,
      onCreate: _controller.create,
      onUpdate: _controller.update,
      onDelete: _controller.delete,
      onRestore: _controller.restore,
      onResetPassword: _controller.resetPassword,
    );

    if (result != null && mounted) {
      _showSnack(result.message);
    }
  }

  Future<void> _openUserDetailDialog(UserAccount user) async {
    final userId = user.id;
    if (userId == null) {
      _showSnack('ID 정보가 없어 상세를 열 수 없습니다.');
      return;
    }
    if (!_groupsLoaded) {
      _showSnack('그룹 정보를 불러오는 중입니다. 잠시 후 다시 시도하세요.');
      return;
    }

    final result = await showUserDetailDialog(
      context: context,
      dateFormat: _dateFormat,
      user: user,
      groupOptions: _controller.groups,
      onCreate: _controller.create,
      onUpdate: _controller.update,
      onDelete: _controller.delete,
      onRestore: _controller.restore,
      onResetPassword: _controller.resetPassword,
    );

    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 _UserTable extends StatelessWidget {
  const _UserTable({
    required this.users,
    required this.dateFormat,
    required this.onUserTap,
  });

  final List<UserAccount> users;
  final intl.DateFormat dateFormat;
  final void Function(UserAccount user)? onUserTap;

  @override
  Widget build(BuildContext context) {
    final columns = const [
      Text('ID'),
      Text('사번'),
      Text('성명'),
      Text('이메일'),
      Text('연락처'),
      Text('그룹'),
      Text('사용'),
      Text('삭제'),
      Text('비고'),
      Text('변경일시'),
    ];

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

    return SuperportTable(
      columns: columns,
      rows: rows,
      rowHeight: 56,
      maxHeight: 56.0 * (users.length + 1),
      onRowTap: onUserTap == null
          ? null
          : (index) {
              if (index < 0 || index >= users.length) {
                return;
              }
              onUserTap!(users[index]);
            },
      columnSpanExtent: (index) => switch (index) {
        2 => const FixedTableSpanExtent(180),
        3 => const FixedTableSpanExtent(220),
        4 => const FixedTableSpanExtent(180),
        8 => const FixedTableSpanExtent(220),
        9 => const FixedTableSpanExtent(180),
        _ => const FixedTableSpanExtent(140),
      },
    );
  }
}
