import 'dart:async';

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 '../../domain/entities/warehouse.dart';
import '../../domain/repositories/warehouse_repository.dart';
import '../controllers/warehouse_controller.dart';
import '../dialogs/warehouse_detail_dialog.dart';

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

  final Uri routeUri;

  @override
  Widget build(BuildContext context) {
    final enabled = Environment.flag('FEATURE_WAREHOUSES_ENABLED');
    if (!enabled) {
      return const SpecPage(
        title: '입고지(창고) 관리',
        summary: '창고 코드, 주소, 사용여부를 관리합니다.',
        sections: [
          SpecSection(
            title: '입력 폼',
            items: [
              '창고코드 [Text]',
              '창고명 [Text]',
              '우편번호 [Text+검색]',
              '상세주소 [Text]',
              '사용여부 [Switch]',
              '비고 [Text]',
            ],
          ),
          SpecSection(
            title: '수정 폼',
            items: ['창고코드 [ReadOnly]', '생성일시 [ReadOnly]'],
          ),
          SpecSection(
            title: '테이블 리스트',
            description: '1행 예시',
            table: SpecTable(
              columns: [
                '번호',
                '창고코드',
                '창고명',
                '우편번호',
                '상세주소',
                '사용여부',
                '비고',
                '변경일시',
              ],
              rows: [
                [
                  '1',
                  'WH-001',
                  '서울 1창고',
                  '06000',
                  '강남대로 123',
                  'Y',
                  '-',
                  '2024-03-01 10:00',
                ],
              ],
            ),
          ),
        ],
      );
    }

    return _WarehouseEnabledPage(routeUri: routeUri);
  }
}

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

  final Uri routeUri;

  @override
  State<_WarehouseEnabledPage> createState() => _WarehouseEnabledPageState();
}

/// 창고 목록과 필터 상태를 관리하는 상태 클래스.
class _WarehouseEnabledPageState extends State<_WarehouseEnabledPage> {
  late final WarehouseController _controller;
  final TextEditingController _searchController = TextEditingController();
  final FocusNode _searchFocus = FocusNode();
  final intl.DateFormat _dateFormat = intl.DateFormat('yyyy-MM-dd HH:mm');
  String? _lastError;
  String? _lastAppliedRoute;

  @override
  void initState() {
    super.initState();
    _controller = WarehouseController(
      repository: GetIt.I<WarehouseRepository>(),
    )..addListener(_handleControllerUpdate);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _applyRouteIfNeeded();
  }

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

  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 warehouses = result?.items ?? const <Warehouse>[];
        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.statusFilter != WarehouseStatusFilter.all;

        return AppLayout(
          title: '입고지(창고) 관리',
          subtitle: '창고 코드, 주소, 사용여부를 관리합니다.',
          breadcrumbs: const [
            AppBreadcrumbItem(label: '대시보드', path: dashboardRoutePath),
            AppBreadcrumbItem(label: '마스터', path: '/masters/warehouses'),
            AppBreadcrumbItem(label: '창고'),
          ],
          actions: [
            ShadButton(
              leading: const Icon(LucideIcons.plus, size: 16),
              onPressed: _controller.isSubmitting
                  ? null
                  : _openWarehouseCreateDialog,
              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.updateStatusFilter(
                            WarehouseStatusFilter.all,
                          );
                          _updateRoute(
                            page: 1,
                            queryOverride: '',
                            statusOverride: WarehouseStatusFilter.all,
                          );
                        },
                  child: const Text('초기화'),
                ),
            ],
            children: [
              ConstrainedBox(
                constraints: const BoxConstraints(maxWidth: 260),
                child: ShadInput(
                  controller: _searchController,
                  focusNode: _searchFocus,
                  placeholder: const Text('창고코드, 창고명 검색'),
                  leading: const Icon(LucideIcons.search, size: 16),
                  onSubmitted: (_) => _applyFilters(),
                ),
              ),
              ConstrainedBox(
                constraints: const BoxConstraints(maxWidth: 200),
                child: ShadSelect<WarehouseStatusFilter>(
                  key: ValueKey(_controller.statusFilter),
                  initialValue: _controller.statusFilter,
                  selectedOptionBuilder: (context, filter) =>
                      Text(_statusLabel(filter)),
                  onChanged: (value) {
                    if (value == null) return;
                    _controller.updateStatusFilter(value);
                    _updateRoute(page: 1, statusOverride: value);
                  },
                  options: WarehouseStatusFilter.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()),
                  )
                : warehouses.isEmpty
                ? Padding(
                    padding: const EdgeInsets.all(32),
                    child: Text(
                      '조건에 맞는 창고가 없습니다.',
                      style: theme.textTheme.muted,
                    ),
                  )
                : _WarehouseTable(
                    warehouses: warehouses,
                    dateFormat: _dateFormat,
                    onWarehouseTap: _controller.isSubmitting
                        ? null
                        : _openWarehouseDetailDialog,
                  ),
          ),
        );
      },
    );
  }

  void _applyRouteIfNeeded() {
    final current = widget.routeUri.toString();
    if (_lastAppliedRoute == current) {
      return;
    }
    _lastAppliedRoute = current;
    _applyRouteParameters();
  }

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

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

  void _applyRouteParameters() {
    final params = widget.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 int totalPages;
    if (result == null || result.pageSize == 0) {
      totalPages = 1;
    } else {
      final calculated = (result.total / result.pageSize).ceil();
      totalPages = calculated < 1 ? 1 : calculated;
    }
    if (page < 1) {
      page = 1;
    } else if (page > totalPages) {
      page = totalPages;
    }
    _updateRoute(page: page);
  }

  void _updateRoute({
    required int page,
    String? queryOverride,
    WarehouseStatusFilter? 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 != WarehouseController.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);
  }

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

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

  Future<void> _openWarehouseCreateDialog() async {
    final result = await showWarehouseDetailDialog(
      context: context,
      dateFormat: _dateFormat,
      onCreate: _controller.create,
      onUpdate: _controller.update,
      onDelete: _controller.delete,
      onRestore: _controller.restore,
    );

    if (result != null && mounted) {
      _showSnack(result.message);
      switch (result.action) {
        case WarehouseDetailDialogAction.created:
          unawaited(_controller.fetch(page: 1));
          break;
        case WarehouseDetailDialogAction.updated:
        case WarehouseDetailDialogAction.deleted:
        case WarehouseDetailDialogAction.restored:
          unawaited(_controller.fetch(page: _controller.result?.page ?? 1));
          break;
      }
    }
  }

  Future<void> _openWarehouseDetailDialog(Warehouse warehouse) async {
    final id = warehouse.id;
    if (id == null) {
      _showSnack('ID 정보가 없어 상세를 열 수 없습니다.');
      return;
    }

    final result = await showWarehouseDetailDialog(
      context: context,
      dateFormat: _dateFormat,
      warehouse: warehouse,
      onCreate: _controller.create,
      onUpdate: _controller.update,
      onDelete: _controller.delete,
      onRestore: _controller.restore,
    );

    if (result != null && mounted) {
      _showSnack(result.message);
      unawaited(_controller.fetch(page: _controller.result?.page ?? 1));
    }
  }

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

class _WarehouseTable extends StatelessWidget {
  const _WarehouseTable({
    required this.warehouses,
    required this.dateFormat,
    required this.onWarehouseTap,
  });

  final List<Warehouse> warehouses;
  final intl.DateFormat dateFormat;
  final void Function(Warehouse warehouse)? onWarehouseTap;

  @override
  Widget build(BuildContext context) {
    final columns = const [
      Text('ID'),
      Text('창고코드'),
      Text('창고명'),
      Text('우편번호'),
      Text('상세주소'),
      Text('사용'),
      Text('삭제'),
      Text('비고'),
      Text('변경일시'),
    ];

    final rows = warehouses
        .map(
          (warehouse) => <Widget>[
            Text(warehouse.id?.toString() ?? '-'),
            Text(warehouse.warehouseCode),
            Text(warehouse.warehouseName),
            Text(warehouse.zipcode?.zipcode ?? '-'),
            Text(
              warehouse.addressDetail?.isEmpty ?? true
                  ? '-'
                  : warehouse.addressDetail!,
            ),
            Text(warehouse.isActive ? 'Y' : 'N'),
            Text(warehouse.isDeleted ? 'Y' : '-'),
            Text(warehouse.note?.isEmpty ?? true ? '-' : warehouse.note!),
            Text(
              warehouse.updatedAt == null
                  ? '-'
                  : dateFormat.format(warehouse.updatedAt!.toLocal()),
            ),
          ],
        )
        .toList();

    return SuperportTable(
      columns: columns,
      rows: rows,
      rowHeight: 56,
      maxHeight: 520,
      onRowTap: onWarehouseTap == null
          ? null
          : (index) => onWarehouseTap!(warehouses[index]),
      columnSpanExtent: (index) => switch (index) {
        1 => const FixedTableSpanExtent(140),
        2 => const FixedTableSpanExtent(200),
        4 => const FixedTableSpanExtent(220),
        8 => const FixedTableSpanExtent(160),
        _ => const FixedTableSpanExtent(120),
      },
    );
  }
}
