import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:go_router/go_router.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 'package:superport_v2/widgets/components/responsive_section.dart';

import '../../../../../core/config/environment.dart';
import '../../../../../widgets/spec_page.dart';
import '../../../vendor/domain/entities/vendor.dart';
import '../../../vendor/domain/repositories/vendor_repository.dart';
import '../dialogs/vendor_detail_dialog.dart';
import '../controllers/vendor_controller.dart';

/// 벤더 관리 페이지. 기능 플래그에 따라 사양/실제 화면을 전환한다.
class VendorPage extends StatelessWidget {
  const VendorPage({super.key, required this.routeUri});

  final Uri routeUri;

  @override
  Widget build(BuildContext context) {
    final enabled = Environment.flag('FEATURE_VENDORS_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]', '벤더명 [Text]', '사용여부 [Switch]', '비고 [Text]'],
          ),
          SpecSection(
            title: '수정 폼',
            items: ['벤더코드 [ReadOnly]', '생성일시 [ReadOnly]', '수정일시 [ReadOnly]'],
          ),
          SpecSection(
            title: '테이블 리스트',
            description: '1행 예시',
            table: SpecTable(
              columns: ['번호', '벤더코드', '벤더명', '사용여부', '비고', '변경일시'],
              rows: [
                ['1', 'V-001', '슈퍼벤더', 'Y', '-', '2024-03-01 10:00'],
              ],
            ),
          ),
        ],
      );
    }

    return _VendorEnabledPage(routeUri: routeUri);
  }
}

/// 벤더 기능이 활성화된 경우 사용하는 실제 화면 위젯.
class _VendorEnabledPage extends StatefulWidget {
  const _VendorEnabledPage({required this.routeUri});

  final Uri routeUri;

  @override
  State<_VendorEnabledPage> createState() => _VendorEnabledPageState();
}

/// 벤더 목록과 필터/폼 상태를 관리하는 상태 클래스.
class _VendorEnabledPageState extends State<_VendorEnabledPage> {
  late final VendorController _controller;
  final TextEditingController _searchController = TextEditingController();
  final FocusNode _searchFocusNode = FocusNode();
  final intl.DateFormat _dateFormat = intl.DateFormat('yyyy-MM-dd HH:mm');
  String? _lastError;
  String? _lastRouteSignature;

  @override
  void initState() {
    super.initState();
    _controller = VendorController(repository: GetIt.I<VendorRepository>())
      ..addListener(_onControllerChanged);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _syncWithRoute(widget.routeUri);
  }

  @override
  void didUpdateWidget(covariant _VendorEnabledPage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.routeUri != widget.routeUri) {
      _syncWithRoute(widget.routeUri);
    }
  }

  @override
  void dispose() {
    _controller.removeListener(_onControllerChanged);
    _controller.dispose();
    _searchController.dispose();
    _searchFocusNode.dispose();
    super.dispose();
  }

  void _onControllerChanged() {
    final error = _controller.errorMessage;
    if (error != null && error != _lastError && mounted) {
      _lastError = error;
      // 스캐폴드 메시지는 프레임 빌드 이후 안전하게 호출한다.
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (!mounted) {
          return;
        }
        final messenger = ScaffoldMessenger.maybeOf(context);
        if (messenger != null) {
          messenger.showSnackBar(SnackBar(content: Text(error)));
        }
        _controller.clearError();
      });
    }
  }

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

    return AnimatedBuilder(
      animation: _controller,
      builder: (context, _) {
        final result = _controller.result;
        final vendors = result?.items ?? const <Vendor>[];
        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);

        return AppLayout(
          title: '제조사(벤더) 관리',
          subtitle: '벤더코드, 명칭, 사용여부, 삭제 상태를 관리합니다.',
          breadcrumbs: const [
            AppBreadcrumbItem(label: '대시보드', path: dashboardRoutePath),
            AppBreadcrumbItem(label: '마스터', path: '/masters/vendors'),
            AppBreadcrumbItem(label: '벤더'),
          ],
          actions: [
            ShadButton(
              leading: const Icon(LucideIcons.plus, size: 16),
              onPressed: _controller.isSubmitting
                  ? null
                  : _openVendorCreateDialog,
              child: const Text('신규 등록'),
            ),
          ],
          toolbar: FilterBar(
            actions: [
              ShadButton.outline(
                onPressed: _controller.isLoading ? null : _applyFilters,
                child: const Text('검색 적용'),
              ),
              if (_searchController.text.isNotEmpty ||
                  _controller.statusFilter != VendorStatusFilter.all)
                ShadButton.ghost(
                  onPressed: _controller.isLoading
                      ? null
                      : () {
                          _searchController.clear();
                          _searchFocusNode.requestFocus();
                          _controller.updateQuery('');
                          _controller.updateStatusFilter(
                            VendorStatusFilter.all,
                          );
                          _updateRoute(
                            page: 1,
                            queryOverride: '',
                            statusOverride: VendorStatusFilter.all,
                          );
                        },
                  child: const Text('초기화'),
                ),
            ],
            children: [
              ConstrainedBox(
                constraints: const BoxConstraints(maxWidth: 280),
                child: ShadInput(
                  controller: _searchController,
                  focusNode: _searchFocusNode,
                  placeholder: const Text('벤더코드, 벤더명 검색'),
                  leading: const Icon(LucideIcons.search, size: 16),
                  onSubmitted: (_) => _applyFilters(),
                ),
              ),
              ConstrainedBox(
                constraints: const BoxConstraints(maxWidth: 220),
                child: ShadSelect<VendorStatusFilter>(
                  key: ValueKey(_controller.statusFilter),
                  initialValue: _controller.statusFilter,
                  selectedOptionBuilder: (context, value) =>
                      Text(_statusLabel(value)),
                  onChanged: (value) {
                    if (value == null) return;
                    _controller.updateStatusFilter(value);
                    _updateRoute(page: 1, statusOverride: value);
                  },
                  options: VendorStatusFilter.values
                      .map(
                        (filter) => ShadOption(
                          value: filter,
                          child: Text(_statusLabel(filter)),
                        ),
                      )
                      .toList(),
                ),
              ),
            ],
          ),
          child: ShadCard(
            title: ResponsiveStackedRow(
              leading: Text('벤더 목록', style: theme.textTheme.h3),
              trailing: Align(
                alignment: Alignment.centerRight,
                child: Text('$totalCount건', style: theme.textTheme.muted),
              ),
            ),
            footer: ResponsiveStackedRow(
              gap: 8,
              breakpoint: 420,
              leading: Text(
                '페이지 $currentPage / $totalPages',
                style: theme.textTheme.small,
              ),
              trailing: Align(
                alignment: Alignment.centerRight,
                child: Wrap(
                  spacing: 8,
                  runSpacing: 8,
                  alignment: WrapAlignment.end,
                  runAlignment: WrapAlignment.end,
                  children: [
                    SuperportPaginationControls(
                      currentPage: currentPage,
                      totalPages: totalPages,
                      isBusy: _controller.isLoading,
                      onPageSelected: _goToPage,
                    ),
                  ],
                ),
              ),
            ),
            child: _controller.isLoading
                ? const Padding(
                    padding: EdgeInsets.all(48),
                    child: Center(child: CircularProgressIndicator()),
                  )
                : vendors.isEmpty
                ? Padding(
                    padding: const EdgeInsets.all(32),
                    child: Text(
                      '조건에 맞는 벤더가 없습니다.',
                      style: theme.textTheme.muted,
                    ),
                  )
                : _VendorTable(
                    vendors: vendors,
                    dateFormat: _dateFormat,
                    onVendorTap: _controller.isSubmitting
                        ? null
                        : _openVendorDetailDialog,
                  ),
          ),
        );
      },
    );
  }

  void _applyFilters() {
    final keyword = _searchController.text.trim();
    _controller.updateQuery(keyword);
    _updateRoute(page: 1, queryOverride: keyword);
  }

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

  void _syncWithRoute(Uri routeUri) {
    final signature = routeUri.toString();
    if (_lastRouteSignature == signature) {
      return;
    }
    _lastRouteSignature = signature;
    _applyRouteParameters(routeUri);
  }

  void _applyRouteParameters(Uri routeUri) {
    final params = routeUri.queryParameters;
    final query = params['q'] ?? '';
    final status = _statusFromParam(params['status']);
    final pageSizeParam = int.tryParse(params['page_size'] ?? '');
    final pageParam = int.tryParse(params['page'] ?? '');

    _searchController.text = query;
    _controller.updateQuery(query);
    _controller.updateStatusFilter(status);
    if (pageSizeParam != null && pageSizeParam > 0) {
      _controller.updatePageSize(pageSizeParam);
    }

    final page = pageParam != null && pageParam > 0 ? pageParam : 1;
    _controller.fetch(page: page);
  }

  void _goToPage(int page) {
    final result = _controller.result;
    final totalPages = result == null || result.pageSize == 0
        ? 1
        : (result.total / result.pageSize).ceil().clamp(1, 9999);
    if (page < 1) {
      page = 1;
    } else if (page > totalPages) {
      page = totalPages;
    }
    _updateRoute(page: page);
  }

  void _updateRoute({
    required int page,
    String? queryOverride,
    VendorStatusFilter? statusOverride,
    int? pageSizeOverride,
  }) {
    final query = queryOverride ?? _controller.query;
    final status = statusOverride ?? _controller.statusFilter;
    final pageSize = pageSizeOverride ?? _controller.pageSize;

    final params = <String, String>{};
    if (query.isNotEmpty) {
      params['q'] = query;
    }
    final statusParam = _encodeStatus(status);
    if (statusParam != null) {
      params['status'] = statusParam;
    }
    if (page > 1) {
      params['page'] = page.toString();
    }
    if (pageSize > 0 && pageSize != VendorController.defaultPageSize) {
      params['page_size'] = pageSize.toString();
    }

    final uri = Uri(
      path: widget.routeUri.path,
      queryParameters: params.isEmpty ? null : params,
    );
    final newLocation = uri.toString();
    if (widget.routeUri.toString() == newLocation) {
      _controller.fetch(page: page);
      return;
    }
    GoRouter.of(context).go(newLocation);
  }

  VendorStatusFilter _statusFromParam(String? value) {
    switch (value) {
      case 'active':
        return VendorStatusFilter.activeOnly;
      case 'inactive':
        return VendorStatusFilter.inactiveOnly;
      default:
        return VendorStatusFilter.all;
    }
  }

  String? _encodeStatus(VendorStatusFilter filter) {
    switch (filter) {
      case VendorStatusFilter.all:
        return null;
      case VendorStatusFilter.activeOnly:
        return 'active';
      case VendorStatusFilter.inactiveOnly:
        return 'inactive';
    }
  }

  Future<void> _openVendorCreateDialog() async {
    final result = await showVendorDetailDialog(
      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> _openVendorDetailDialog(Vendor vendor) async {
    final vendorId = vendor.id;
    if (vendorId == null) {
      _showSnack('ID 정보가 없어 상세를 열 수 없습니다.');
      return;
    }
    final result = await showVendorDetailDialog(
      context: context,
      dateFormat: _dateFormat,
      vendor: vendor,
      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 _VendorTable extends StatelessWidget {
  const _VendorTable({
    required this.vendors,
    required this.dateFormat,
    required this.onVendorTap,
  });

  final List<Vendor> vendors;
  final intl.DateFormat dateFormat;
  final void Function(Vendor vendor)? onVendorTap;

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

    final rows = vendors
        .map(
          (vendor) => <Widget>[
            Text(vendor.id?.toString() ?? '-'),
            Text(vendor.vendorCode),
            Text(vendor.vendorName),
            Text(vendor.isActive ? 'Y' : 'N'),
            Text(vendor.isDeleted ? 'Y' : '-'),
            Text(vendor.note?.isEmpty ?? true ? '-' : vendor.note!),
            Text(
              vendor.updatedAt == null
                  ? '-'
                  : dateFormat.format(vendor.updatedAt!.toLocal()),
            ),
          ],
        )
        .toList();

    return SuperportTable(
      columns: columns,
      rows: rows,
      rowHeight: 56,
      maxHeight: 520,
      onRowTap: onVendorTap == null
          ? null
          : (index) => onVendorTap!(vendors[index]),
      columnSpanExtent: (index) => switch (index) {
        2 => const FixedTableSpanExtent(180),
        5 => const FixedTableSpanExtent(220),
        6 => const FixedTableSpanExtent(160),
        _ => const FixedTableSpanExtent(120),
      },
    );
  }
}
