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/customer.dart';
import '../../domain/repositories/customer_repository.dart';
import '../dialogs/customer_detail_dialog.dart';
import '../controllers/customer_controller.dart';

/// 고객 관리 화면. 기능 플래그에 따라 사양 페이지를 보여주거나 실제 목록을 노출한다.
class CustomerPage extends StatelessWidget {
  const CustomerPage({super.key, required this.routeUri});

  final Uri routeUri;

  @override
  Widget build(BuildContext context) {
    final enabled = Environment.flag('FEATURE_CUSTOMERS_ENABLED');
    if (!enabled) {
      return const SpecPage(
        title: '회사(고객사) 관리',
        summary: '고객사 기본 정보와 연락처, 주소를 관리합니다.',
        sections: [
          SpecSection(
            title: '입력 폼',
            items: [
              '고객사코드 [Text]',
              '고객사명 [Text]',
              '유형 (파트너/일반) [Dropdown]',
              '이메일 [Text]',
              '연락처 [Text]',
              '우편번호 [검색 연동], 상세주소 [Text]',
              '사용여부 [Switch]',
              '비고 [Text]',
            ],
          ),
          SpecSection(
            title: '수정 폼',
            items: ['고객사코드 [ReadOnly]', '생성일시 [ReadOnly]'],
          ),
          SpecSection(
            title: '테이블 리스트',
            description: '1행 예시',
            table: SpecTable(
              columns: [
                '번호',
                '고객사코드',
                '고객사명',
                '유형',
                '이메일',
                '연락처',
                '우편번호',
                '상세주소',
                '사용여부',
                '비고',
              ],
              rows: [
                [
                  '1',
                  'C-001',
                  '슈퍼포트 파트너',
                  '파트너',
                  'partner@superport.com',
                  '02-1234-5678',
                  '04532',
                  '서울시 중구 을지로 100',
                  'Y',
                  '-',
                ],
              ],
            ),
          ),
        ],
      );
    }

    return _CustomerEnabledPage(routeUri: routeUri);
  }
}

class _CustomerTable extends StatelessWidget {
  const _CustomerTable({required this.customers, required this.onCustomerTap});

  final List<Customer> customers;
  final void Function(Customer customer)? onCustomerTap;

  @override
  Widget build(BuildContext context) {
    final columns = const [
      Text('ID'),
      Text('고객사코드'),
      Text('고객사명'),
      Text('담당자'),
      Text('유형'),
      Text('이메일'),
      Text('연락처'),
      Text('우편번호'),
      Text('상세주소'),
      Text('사용'),
      Text('삭제'),
      Text('비고'),
    ];

    String resolveType(Customer customer) {
      if (customer.isPartner && customer.isGeneral) {
        return '파트너/일반';
      }
      if (customer.isPartner) return '파트너';
      if (customer.isGeneral) return '일반';
      return '-';
    }

    final rows = customers
        .map(
          (customer) => <Widget>[
            Text(customer.id?.toString() ?? '-'),
            Text(customer.customerCode),
            Text(customer.customerName),
            Text(
              customer.contactName?.isEmpty ?? true
                  ? '-'
                  : customer.contactName!,
            ),
            Text(resolveType(customer)),
            Text(customer.email?.isEmpty ?? true ? '-' : customer.email!),
            Text(customer.mobileNo?.isEmpty ?? true ? '-' : customer.mobileNo!),
            Text(customer.zipcode?.zipcode ?? '-'),
            Text(
              customer.addressDetail?.isEmpty ?? true
                  ? '-'
                  : customer.addressDetail!,
            ),
            Text(customer.isActive ? 'Y' : 'N'),
            Text(customer.isDeleted ? 'Y' : '-'),
            Text(customer.note?.isEmpty ?? true ? '-' : customer.note!),
          ],
        )
        .toList();

    return SuperportTable(
      columns: columns,
      rows: rows,
      rowHeight: 56,
      maxHeight: 56.0 * (customers.length + 1),
      onRowTap: onCustomerTap == null
          ? null
          : (index) => onCustomerTap!(customers[index]),
      columnSpanExtent: (index) => switch (index) {
        2 => const FixedTableSpanExtent(180),
        5 => const FixedTableSpanExtent(200),
        8 => const FixedTableSpanExtent(220),
        11 => const FixedTableSpanExtent(200),
        _ => const FixedTableSpanExtent(140),
      },
    );
  }
}

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

  final Uri routeUri;

  @override
  State<_CustomerEnabledPage> createState() => _CustomerEnabledPageState();
}

/// 고객 목록 UI와 라우트 파라미터 싱크를 담당하는 상태 클래스.
class _CustomerEnabledPageState extends State<_CustomerEnabledPage> {
  late final CustomerController _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 = CustomerController(repository: GetIt.I<CustomerRepository>())
      ..addListener(_handleControllerUpdate);
  }

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

  @override
  void didUpdateWidget(covariant _CustomerEnabledPage 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();
    }
  }

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

  void _applyRouteParameters(Uri route) {
    final params = route.queryParameters;
    final query = params['q'] ?? '';
    final type = _typeFromParam(params['type']);
    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.updateTypeFilter(type);
    _controller.updateStatusFilter(status);
    if (pageSizeParam != null && pageSizeParam > 0) {
      _controller.updatePageSize(pageSizeParam);
    }

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

  @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 customers = result?.items ?? const <Customer>[];
        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.typeFilter != CustomerTypeFilter.all ||
            _controller.statusFilter != CustomerStatusFilter.all;

        return AppLayout(
          title: '회사(고객사) 관리',
          subtitle: '고객사 기본 정보와 연락처, 주소를 관리합니다.',
          breadcrumbs: const [
            AppBreadcrumbItem(label: '대시보드', path: dashboardRoutePath),
            AppBreadcrumbItem(label: '마스터', path: '/masters/customers'),
            AppBreadcrumbItem(label: '고객사'),
          ],
          actions: [
            ShadButton(
              leading: const Icon(LucideIcons.plus, size: 16),
              onPressed: _controller.isSubmitting
                  ? null
                  : _openCustomerCreateDialog,
              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.updateTypeFilter(CustomerTypeFilter.all);
                          _controller.updateStatusFilter(
                            CustomerStatusFilter.all,
                          );
                          _updateRoute(
                            page: 1,
                            queryOverride: '',
                            typeOverride: CustomerTypeFilter.all,
                            statusOverride: CustomerStatusFilter.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<CustomerTypeFilter>(
                  key: ValueKey(_controller.typeFilter),
                  initialValue: _controller.typeFilter,
                  selectedOptionBuilder: (context, value) =>
                      Text(_typeLabel(value)),
                  onChanged: (value) {
                    if (value == null) return;
                    _controller.updateTypeFilter(value);
                  },
                  options: CustomerTypeFilter.values
                      .map(
                        (filter) => ShadOption(
                          value: filter,
                          child: Text(_typeLabel(filter)),
                        ),
                      )
                      .toList(),
                ),
              ),
              ConstrainedBox(
                constraints: const BoxConstraints(maxWidth: 200),
                child: ShadSelect<CustomerStatusFilter>(
                  key: ValueKey(_controller.statusFilter),
                  initialValue: _controller.statusFilter,
                  selectedOptionBuilder: (context, value) =>
                      Text(_statusLabel(value)),
                  onChanged: (value) {
                    if (value == null) return;
                    _controller.updateStatusFilter(value);
                  },
                  options: CustomerStatusFilter.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()),
                  )
                : customers.isEmpty
                ? Padding(
                    padding: const EdgeInsets.all(32),
                    child: Text(
                      '조건에 맞는 고객사가 없습니다.',
                      style: theme.textTheme.muted,
                    ),
                  )
                : _CustomerTable(
                    customers: customers,
                    onCustomerTap: _controller.isSubmitting
                        ? null
                        : _openCustomerDetailDialog,
                  ),
          ),
        );
      },
    );
  }

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

  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,
    CustomerTypeFilter? typeOverride,
    CustomerStatusFilter? statusOverride,
    int? pageSizeOverride,
  }) {
    final query = queryOverride ?? _controller.query;
    final type = typeOverride ?? _controller.typeFilter;
    final status = statusOverride ?? _controller.statusFilter;
    final pageSize = pageSizeOverride ?? _controller.pageSize;

    final params = <String, String>{};
    if (query.isNotEmpty) {
      params['q'] = query;
    }
    final typeParam = _encodeType(type);
    if (typeParam != null) {
      params['type'] = typeParam;
    }
    final statusParam = _encodeStatus(status);
    if (statusParam != null) {
      params['status'] = statusParam;
    }
    if (page > 1) {
      params['page'] = page.toString();
    }
    if (pageSize > 0 && pageSize != CustomerController.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);
  }

  /// URL 파라미터에서 고객 유형 필터 값을 파싱한다.
  CustomerTypeFilter _typeFromParam(String? value) {
    switch (value) {
      case 'partner':
        return CustomerTypeFilter.partner;
      case 'general':
        return CustomerTypeFilter.general;
      default:
        return CustomerTypeFilter.all;
    }
  }

  /// 고객 유형 필터를 URL 파라미터 문자열로 변환한다.
  String? _encodeType(CustomerTypeFilter filter) {
    switch (filter) {
      case CustomerTypeFilter.all:
        return null;
      case CustomerTypeFilter.partner:
        return 'partner';
      case CustomerTypeFilter.general:
        return 'general';
    }
  }

  /// URL 파라미터에서 고객 활성 상태를 파싱한다.
  CustomerStatusFilter _statusFromParam(String? value) {
    switch (value) {
      case 'active':
        return CustomerStatusFilter.activeOnly;
      case 'inactive':
        return CustomerStatusFilter.inactiveOnly;
      default:
        return CustomerStatusFilter.all;
    }
  }

  /// 고객 상태 필터를 URL 파라미터 문자열로 변환한다.
  String? _encodeStatus(CustomerStatusFilter filter) {
    switch (filter) {
      case CustomerStatusFilter.all:
        return null;
      case CustomerStatusFilter.activeOnly:
        return 'active';
      case CustomerStatusFilter.inactiveOnly:
        return 'inactive';
    }
  }

  Future<void> _openCustomerCreateDialog() async {
    final result = await showCustomerDetailDialog(
      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> _openCustomerDetailDialog(Customer customer) async {
    final customerId = customer.id;
    if (customerId == null) {
      _showSnack('ID 정보가 없어 상세를 열 수 없습니다.');
      return;
    }
    final result = await showCustomerDetailDialog(
      context: context,
      dateFormat: _dateFormat,
      customer: customer,
      onCreate: _controller.create,
      onUpdate: _controller.update,
      onDelete: _controller.delete,
      onRestore: _controller.restore,
    );
    if (result != null && mounted) {
      _showSnack(result.message);
    }
  }

  String _typeLabel(CustomerTypeFilter filter) {
    switch (filter) {
      case CustomerTypeFilter.all:
        return '전체(파트너/일반)';
      case CustomerTypeFilter.partner:
        return '파트너';
      case CustomerTypeFilter.general:
        return '일반';
    }
  }

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

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