import 'dart:async';

import 'package:flutter/material.dart';
import 'package:intl/intl.dart' as intl;
import 'package:shadcn_ui/shadcn_ui.dart';

import '../../../../../widgets/components/superport_detail_dialog.dart';
import '../../../../../features/util/postal_search/presentation/models/postal_search_result.dart';
import '../../../../../features/util/postal_search/presentation/widgets/postal_search_dialog.dart';
import '../../domain/entities/warehouse.dart';

/// 창고 상세 다이얼로그에서 발생하는 액션 유형이다.
enum WarehouseDetailDialogAction { created, updated, deleted, restored }

/// 창고 상세 다이얼로그 결과 모델이다.
class WarehouseDetailDialogResult {
  const WarehouseDetailDialogResult({
    required this.action,
    required this.message,
    this.warehouse,
  });

  final WarehouseDetailDialogAction action;
  final String message;

  /// 최신 창고 엔티티. 삭제 액션에서는 null일 수 있다.
  final Warehouse? warehouse;
}

typedef WarehouseCreateCallback =
    Future<Warehouse?> Function(WarehouseInput input);
typedef WarehouseUpdateCallback =
    Future<Warehouse?> Function(int id, WarehouseInput input);
typedef WarehouseDeleteCallback = Future<bool> Function(int id);
typedef WarehouseRestoreCallback = Future<Warehouse?> Function(int id);

/// 창고 상세 다이얼로그를 표시한다.
Future<WarehouseDetailDialogResult?> showWarehouseDetailDialog({
  required BuildContext context,
  required intl.DateFormat dateFormat,
  Warehouse? warehouse,
  required WarehouseCreateCallback onCreate,
  required WarehouseUpdateCallback onUpdate,
  required WarehouseDeleteCallback onDelete,
  required WarehouseRestoreCallback onRestore,
}) {
  final metadata = warehouse == null
      ? const <SuperportDetailMetadata>[]
      : [
          SuperportDetailMetadata.text(
            label: 'ID',
            value: warehouse.id?.toString() ?? '-',
          ),
          SuperportDetailMetadata.text(
            label: '창고코드',
            value: warehouse.warehouseCode,
          ),
          SuperportDetailMetadata.text(
            label: '사용 상태',
            value: warehouse.isActive ? '사용중' : '미사용',
          ),
          SuperportDetailMetadata.text(
            label: '삭제 여부',
            value: warehouse.isDeleted ? '삭제됨' : '정상',
          ),
          SuperportDetailMetadata.text(
            label: '우편번호',
            value: warehouse.zipcode?.zipcode ?? '-',
          ),
          SuperportDetailMetadata.text(
            label: '기본주소',
            value: _composeFullAddress(warehouse.zipcode),
          ),
          SuperportDetailMetadata.text(
            label: '상세주소',
            value: warehouse.addressDetail?.isEmpty ?? true
                ? '-'
                : warehouse.addressDetail!,
          ),
          SuperportDetailMetadata.text(
            label: '비고',
            value: warehouse.note?.isEmpty ?? true ? '-' : warehouse.note!,
          ),
          SuperportDetailMetadata.text(
            label: '생성일시',
            value: warehouse.createdAt == null
                ? '-'
                : dateFormat.format(warehouse.createdAt!.toLocal()),
          ),
          SuperportDetailMetadata.text(
            label: '변경일시',
            value: warehouse.updatedAt == null
                ? '-'
                : dateFormat.format(warehouse.updatedAt!.toLocal()),
          ),
        ];

  return showSuperportDetailDialog<WarehouseDetailDialogResult>(
    context: context,
    title: warehouse == null ? '창고 등록' : '창고 상세',
    description: warehouse == null
        ? '입고지(창고) 기본 정보를 입력하세요.'
        : '창고 기본 정보와 주소를 확인하고 관리할 수 있습니다.',
    sections: [
      _WarehouseFormSection(
        id: warehouse == null
            ? _WarehouseSections.create
            : _WarehouseSections.edit,
        label: warehouse == null ? '등록' : '수정',
        warehouse: warehouse,
        onSubmit: (input) async {
          if (warehouse == null) {
            final created = await onCreate(input);
            if (created == null) {
              return null;
            }
            return WarehouseDetailDialogResult(
              action: WarehouseDetailDialogAction.created,
              message: '창고를 등록했습니다.',
              warehouse: created,
            );
          }
          final updated = await onUpdate(warehouse.id!, input);
          if (updated == null) {
            return null;
          }
          return WarehouseDetailDialogResult(
            action: WarehouseDetailDialogAction.updated,
            message: '창고를 수정했습니다.',
            warehouse: updated,
          );
        },
      ),
      if (warehouse != null)
        _WarehouseDangerSection(
          warehouse: warehouse,
          onDelete: () async {
            final id = warehouse.id;
            if (id == null) {
              return null;
            }
            final success = await onDelete(id);
            if (!success) {
              return null;
            }
            return WarehouseDetailDialogResult(
              action: WarehouseDetailDialogAction.deleted,
              message: '창고를 삭제했습니다.',
              warehouse: warehouse,
            );
          },
          onRestore: () async {
            final id = warehouse.id;
            if (id == null) {
              return null;
            }
            final restored = await onRestore(id);
            if (restored == null) {
              return null;
            }
            return WarehouseDetailDialogResult(
              action: WarehouseDetailDialogAction.restored,
              message: '창고를 복구했습니다.',
              warehouse: restored,
            );
          },
        ),
    ],
    summary: warehouse == null
        ? null
        : Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                warehouse.warehouseName,
                style: ShadTheme.of(context).textTheme.h4,
              ),
              const SizedBox(height: 4),
              Text(
                '창고코드 ${warehouse.warehouseCode}',
                style: ShadTheme.of(context).textTheme.muted,
              ),
            ],
          ),
    summaryBadges: warehouse == null
        ? const []
        : [
            if (warehouse.isActive)
              const ShadBadge(child: Text('사용중'))
            else
              const ShadBadge.outline(child: Text('미사용')),
            if (warehouse.isDeleted)
              const ShadBadge.destructive(child: Text('삭제됨')),
          ],
    metadata: metadata,
    initialSectionId: warehouse == null
        ? _WarehouseSections.create
        : _WarehouseSections.edit,
    emptyPlaceholder: const Text('표시할 창고 정보가 없습니다.'),
  );
}

class _WarehouseSections {
  static const edit = 'edit';
  static const delete = 'delete';
  static const restore = 'restore';
  static const create = 'create';
}

/// 창고 입력 폼을 제공하는 섹션이다.
class _WarehouseFormSection extends SuperportDetailDialogSection {
  _WarehouseFormSection({
    required super.id,
    required super.label,
    required Warehouse? warehouse,
    required this.onSubmit,
  }) : super(
         icon: LucideIcons.pencil,
         builder: (context) =>
             _WarehouseForm(warehouse: warehouse, onSubmit: onSubmit),
       );

  final Future<WarehouseDetailDialogResult?> Function(WarehouseInput input)
  onSubmit;
}

/// 삭제/복구 섹션이다.
class _WarehouseDangerSection extends SuperportDetailDialogSection {
  _WarehouseDangerSection({
    required this.warehouse,
    required this.onDelete,
    required this.onRestore,
  }) : super(
         id: warehouse.isDeleted
             ? _WarehouseSections.restore
             : _WarehouseSections.delete,
         label: warehouse.isDeleted ? '복구' : '삭제',
         icon: warehouse.isDeleted ? LucideIcons.history : LucideIcons.trash2,
         builder: (context) => _WarehouseDangerContent(
           warehouse: warehouse,
           onDelete: onDelete,
           onRestore: onRestore,
         ),
         scrollable: false,
       );

  final Warehouse warehouse;
  final Future<WarehouseDetailDialogResult?> Function() onDelete;
  final Future<WarehouseDetailDialogResult?> Function() onRestore;
}

class _WarehouseDangerContent extends StatelessWidget {
  const _WarehouseDangerContent({
    required this.warehouse,
    required this.onDelete,
    required this.onRestore,
  });

  final Warehouse warehouse;
  final Future<WarehouseDetailDialogResult?> Function() onDelete;
  final Future<WarehouseDetailDialogResult?> Function() onRestore;

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    final isDeleted = warehouse.isDeleted;
    final description = isDeleted
        ? '창고를 복구하면 다시 목록에 노출되고 입출고 등록 시 선택할 수 있습니다.'
        : '삭제하면 창고가 목록에서 숨겨지며 기존 데이터는 유지됩니다.';
    final confirmLabel = isDeleted ? '복구' : '삭제';

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(description, style: theme.textTheme.small),
        const SizedBox(height: 16),
        if (isDeleted)
          ShadButton(
            onPressed: () async {
              final navigator = Navigator.of(context, rootNavigator: true);
              final result = await onRestore();
              if (result != null && navigator.mounted) {
                navigator.pop(result);
              }
            },
            child: Text(confirmLabel),
          )
        else
          ShadButton.destructive(
            onPressed: () async {
              final navigator = Navigator.of(context, rootNavigator: true);
              final result = await onDelete();
              if (result != null && navigator.mounted) {
                navigator.pop(result);
              }
            },
            child: Text(confirmLabel),
          ),
      ],
    );
  }
}

/// 창고 입력 폼 구현이다.
class _WarehouseForm extends StatefulWidget {
  const _WarehouseForm({required this.warehouse, required this.onSubmit});

  final Warehouse? warehouse;
  final Future<WarehouseDetailDialogResult?> Function(WarehouseInput input)
  onSubmit;

  @override
  State<_WarehouseForm> createState() => _WarehouseFormState();
}

class _WarehouseFormState extends State<_WarehouseForm> {
  late final TextEditingController _codeController;
  late final TextEditingController _nameController;
  late final TextEditingController _zipcodeController;
  late final TextEditingController _addressController;
  late final TextEditingController _noteController;
  late final ValueNotifier<PostalSearchResult?> _selectedPostalNotifier;
  late final ValueNotifier<bool> _isActiveNotifier;
  String? _codeError;
  String? _nameError;
  String? _zipcodeError;
  String? _submitError;
  bool _isSubmitting = false;
  bool _isApplyingPostalSelection = false;

  bool get _isEdit => widget.warehouse != null;

  @override
  void initState() {
    super.initState();
    final warehouse = widget.warehouse;
    _codeController = TextEditingController(
      text: warehouse?.warehouseCode ?? '',
    );
    _nameController = TextEditingController(
      text: warehouse?.warehouseName ?? '',
    );
    _zipcodeController = TextEditingController(
      text: warehouse?.zipcode?.zipcode ?? '',
    );
    _addressController = TextEditingController(
      text: warehouse?.addressDetail ?? '',
    );
    _noteController = TextEditingController(text: warehouse?.note ?? '');
    _selectedPostalNotifier = ValueNotifier<PostalSearchResult?>(
      warehouse?.zipcode == null
          ? null
          : PostalSearchResult(
              zipcode: warehouse!.zipcode!.zipcode,
              sido: warehouse.zipcode!.sido,
              sigungu: warehouse.zipcode!.sigungu,
              roadName: warehouse.zipcode!.roadName,
            ),
    );
    _isActiveNotifier = ValueNotifier<bool>(warehouse?.isActive ?? true);

    _zipcodeController.addListener(_handleZipcodeChange);
    _selectedPostalNotifier.addListener(_handlePostalSelection);
  }

  @override
  void dispose() {
    _zipcodeController.removeListener(_handleZipcodeChange);
    _selectedPostalNotifier.removeListener(_handlePostalSelection);
    _codeController.dispose();
    _nameController.dispose();
    _zipcodeController.dispose();
    _addressController.dispose();
    _noteController.dispose();
    _selectedPostalNotifier.dispose();
    _isActiveNotifier.dispose();
    super.dispose();
  }

  void _handleZipcodeChange() {
    if (_isApplyingPostalSelection) {
      return;
    }
    final text = _zipcodeController.text.trim();
    final selection = _selectedPostalNotifier.value;
    if (text.isEmpty) {
      if (selection != null) {
        _selectedPostalNotifier.value = null;
      }
      setState(() {
        _zipcodeError = null;
      });
      return;
    }
    if (selection != null && selection.zipcode != text) {
      _selectedPostalNotifier.value = null;
    }
    if (_zipcodeError != null) {
      setState(() {
        _zipcodeError = null;
      });
    }
  }

  void _handlePostalSelection() {
    if (_selectedPostalNotifier.value != null && _zipcodeError != null) {
      setState(() {
        _zipcodeError = null;
      });
    }
  }

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

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _WarehouseFormField(
          label: '창고코드',
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ShadInput(
                controller: _codeController,
                readOnly: _isEdit,
                onChanged: (_) {
                  if (_codeController.text.trim().isNotEmpty) {
                    setState(() {
                      _codeError = null;
                    });
                  }
                },
              ),
              if (_codeError != null)
                Padding(
                  padding: const EdgeInsets.only(top: 6),
                  child: Text(
                    _codeError!,
                    style: theme.textTheme.small.copyWith(
                      color: theme.colorScheme.destructive,
                    ),
                  ),
                ),
            ],
          ),
        ),
        const SizedBox(height: 16),
        _WarehouseFormField(
          label: '창고명',
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ShadInput(
                controller: _nameController,
                onChanged: (_) {
                  if (_nameController.text.trim().isNotEmpty) {
                    setState(() {
                      _nameError = null;
                    });
                  }
                },
              ),
              if (_nameError != null)
                Padding(
                  padding: const EdgeInsets.only(top: 6),
                  child: Text(
                    _nameError!,
                    style: theme.textTheme.small.copyWith(
                      color: theme.colorScheme.destructive,
                    ),
                  ),
                ),
            ],
          ),
        ),
        const SizedBox(height: 16),
        _WarehouseFormField(
          label: '우편번호',
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Expanded(
                    child: ShadInput(
                      controller: _zipcodeController,
                      placeholder: const Text('예: 06000'),
                      keyboardType: TextInputType.number,
                    ),
                  ),
                  const SizedBox(width: 8),
                  ShadButton.outline(
                    onPressed: _isSubmitting ? null : _openPostalSearch,
                    child: const Text('검색'),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              ValueListenableBuilder<PostalSearchResult?>(
                valueListenable: _selectedPostalNotifier,
                builder: (_, selection, __) {
                  if (selection == null) {
                    return Text(
                      '검색 버튼을 눌러 주소를 선택하세요.',
                      style: theme.textTheme.small.copyWith(
                        color: theme.colorScheme.mutedForeground,
                      ),
                    );
                  }
                  return Text(
                    selection.fullAddress.isEmpty
                        ? '선택한 우편번호에 주소 정보가 없습니다.'
                        : selection.fullAddress,
                    style: theme.textTheme.small,
                  );
                },
              ),
              if (_zipcodeError != null)
                Padding(
                  padding: const EdgeInsets.only(top: 6),
                  child: Text(
                    _zipcodeError!,
                    style: theme.textTheme.small.copyWith(
                      color: theme.colorScheme.destructive,
                    ),
                  ),
                ),
            ],
          ),
        ),
        const SizedBox(height: 16),
        _WarehouseFormField(
          label: '상세주소',
          child: ShadInput(
            controller: _addressController,
            placeholder: const Text('상세주소 입력'),
          ),
        ),
        const SizedBox(height: 16),
        _WarehouseFormField(
          label: '사용여부',
          child: ValueListenableBuilder<bool>(
            valueListenable: _isActiveNotifier,
            builder: (_, value, __) {
              return Row(
                children: [
                  ShadSwitch(
                    value: value,
                    onChanged: _isSubmitting
                        ? null
                        : (next) => _isActiveNotifier.value = next,
                  ),
                  const SizedBox(width: 8),
                  Text(value ? '사용' : '미사용'),
                ],
              );
            },
          ),
        ),
        const SizedBox(height: 16),
        _WarehouseFormField(
          label: '비고',
          child: ShadTextarea(
            controller: _noteController,
            minHeight: 96,
            maxHeight: 240,
          ),
        ),
        if (_submitError != null) ...[
          const SizedBox(height: 16),
          Text(
            _submitError!,
            style: theme.textTheme.small.copyWith(
              color: theme.colorScheme.destructive,
            ),
          ),
        ],
        const SizedBox(height: 20),
        Align(
          alignment: Alignment.centerRight,
          child: ShadButton(
            onPressed: _isSubmitting ? null : _handleSubmit,
            child: Text(_isEdit ? '저장' : '등록'),
          ),
        ),
      ],
    );
  }

  Future<void> _openPostalSearch() async {
    final keyword = _zipcodeController.text.trim();
    final result = await showPostalSearchDialog(
      context,
      initialKeyword: keyword.isEmpty ? null : keyword,
    );
    if (result == null) {
      return;
    }
    _isApplyingPostalSelection = true;
    _zipcodeController
      ..text = result.zipcode
      ..selection = TextSelection.collapsed(offset: result.zipcode.length);
    _isApplyingPostalSelection = false;
    _selectedPostalNotifier.value = result;
    if (result.fullAddress.isNotEmpty) {
      _addressController
        ..text = result.fullAddress
        ..selection = TextSelection.collapsed(
          offset: _addressController.text.length,
        );
    }
  }

  Future<void> _handleSubmit() async {
    final code = _codeController.text.trim();
    final name = _nameController.text.trim();
    final zipcode = _zipcodeController.text.trim();
    final address = _addressController.text.trim();
    final selectedPostal = _selectedPostalNotifier.value;

    setState(() {
      _codeError = code.isEmpty ? '창고코드를 입력하세요.' : null;
      _nameError = name.isEmpty ? '창고명을 입력하세요.' : null;
      _zipcodeError = zipcode.isNotEmpty && selectedPostal == null
          ? '우편번호 검색으로 주소를 선택하세요.'
          : null;
      _submitError = null;
    });

    if (_codeError != null || _nameError != null || _zipcodeError != null) {
      return;
    }

    setState(() {
      _isSubmitting = true;
    });

    final input = WarehouseInput(
      warehouseCode: code,
      warehouseName: name,
      zipcode: zipcode.isEmpty ? null : zipcode,
      addressDetail: address.isEmpty ? null : address,
      isActive: _isActiveNotifier.value,
      note: _noteController.text.trim().isEmpty
          ? null
          : _noteController.text.trim(),
    );
    final navigator = Navigator.of(context, rootNavigator: true);
    final result = await widget.onSubmit(input);

    if (!mounted) {
      return;
    }

    setState(() {
      _isSubmitting = false;
      _submitError = result == null ? '요청 처리에 실패했습니다.' : null;
    });

    if (result != null && navigator.mounted) {
      navigator.pop(result);
    }
  }
}

class _WarehouseFormField extends StatelessWidget {
  const _WarehouseFormField({required this.label, required this.child});

  final String label;
  final Widget child;

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label, style: theme.textTheme.small),
        const SizedBox(height: 6),
        child,
      ],
    );
  }
}

String _composeFullAddress(WarehouseZipcode? zipcode) {
  if (zipcode == null) {
    return '-';
  }
  final segments = [zipcode.sido, zipcode.sigungu, zipcode.roadName]
      .where((segment) => segment != null && segment.trim().isNotEmpty)
      .map((segment) => segment!.trim());
  final result = segments.join(' ');
  return result.isEmpty ? '-' : result;
}
