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 '../../../uom/domain/entities/uom.dart';
import '../../../vendor/domain/entities/vendor.dart';
import '../../domain/entities/product.dart';
import '../widgets/uom_autocomplete_field.dart';
import '../widgets/vendor_autocomplete_field.dart';

/// 제품 상세 다이얼로그에서 발생 가능한 액션 종류이다.
enum ProductDetailDialogAction { created, updated, deleted, restored }

/// 제품 상세 다이얼로그가 반환하는 결과 모델이다.
class ProductDetailDialogResult {
  const ProductDetailDialogResult({
    required this.action,
    required this.message,
    this.product,
  });

  final ProductDetailDialogAction action;
  final String message;

  /// 갱신된 제품 엔터티. 삭제 동작의 경우 null일 수 있다.
  final Product? product;
}

typedef ProductCreateCallback = Future<Product?> Function(ProductInput input);
typedef ProductUpdateCallback =
    Future<Product?> Function(int id, ProductInput input);
typedef ProductDeleteCallback = Future<bool> Function(int id);
typedef ProductRestoreCallback = Future<Product?> Function(int id);

/// 제품 상세 다이얼로그를 노출한다.
Future<ProductDetailDialogResult?> showProductDetailDialog({
  required BuildContext context,
  required intl.DateFormat dateFormat,
  Product? product,
  required List<Vendor> vendorOptions,
  required List<Uom> uomOptions,
  required ProductCreateCallback onCreate,
  required ProductUpdateCallback onUpdate,
  required ProductDeleteCallback onDelete,
  required ProductRestoreCallback onRestore,
}) {
  final metadata = product == null
      ? const <SuperportDetailMetadata>[]
      : [
          SuperportDetailMetadata.text(
            label: 'ID',
            value: product.id?.toString() ?? '-',
          ),
          SuperportDetailMetadata.text(
            label: '제품코드',
            value: product.productCode,
          ),
          SuperportDetailMetadata.text(
            label: '사용 상태',
            value: product.isActive ? '사용중' : '미사용',
          ),
          SuperportDetailMetadata.text(
            label: '삭제 여부',
            value: product.isDeleted ? '삭제됨' : '정상',
          ),
          SuperportDetailMetadata.text(
            label: '제조사',
            value: product.vendor == null
                ? '-'
                : '${product.vendor!.vendorName} (${product.vendor!.vendorCode})',
          ),
          SuperportDetailMetadata.text(
            label: '단위',
            value: product.uom?.uomName ?? '-',
          ),
          SuperportDetailMetadata.text(
            label: '비고',
            value: product.note?.isEmpty ?? true ? '-' : product.note!,
          ),
          SuperportDetailMetadata.text(
            label: '생성일시',
            value: product.createdAt == null
                ? '-'
                : dateFormat.format(product.createdAt!.toLocal()),
          ),
          SuperportDetailMetadata.text(
            label: '변경일시',
            value: product.updatedAt == null
                ? '-'
                : dateFormat.format(product.updatedAt!.toLocal()),
          ),
        ];

  return showSuperportDetailDialog<ProductDetailDialogResult>(
    context: context,
    title: product == null ? '제품 등록' : '제품 상세',
    description: product == null
        ? '새로운 장비 모델(제품) 정보를 입력하세요.'
        : '제품 기본 정보와 연결된 제조사·단위 정보를 확인하고 관리합니다.',
    sections: [
      if (product != null)
        SuperportDetailDialogSection(
          id: _ProductDetailSections.relations,
          label: '연결 관계',
          icon: LucideIcons.link,
          builder: (_) => _ProductRelationsSection(product: product),
        ),
      if (product != null)
        SuperportDetailDialogSection(
          id: _ProductDetailSections.history,
          label: '히스토리',
          icon: LucideIcons.clock3,
          builder: (_) => const _ProductHistorySection(),
        ),
      _ProductFormSection(
        id: product == null
            ? _ProductDetailSections.create
            : _ProductDetailSections.edit,
        label: product == null ? '등록' : '수정',
        product: product,
        vendorOptions: vendorOptions,
        uomOptions: uomOptions,
        onSubmit: (input) async {
          if (product == null) {
            final created = await onCreate(input);
            if (created == null) {
              return null;
            }
            return ProductDetailDialogResult(
              action: ProductDetailDialogAction.created,
              message: '제품을 등록했습니다.',
              product: created,
            );
          }
          final updated = await onUpdate(product.id!, input);
          if (updated == null) {
            return null;
          }
          return ProductDetailDialogResult(
            action: ProductDetailDialogAction.updated,
            message: '제품을 수정했습니다.',
            product: updated,
          );
        },
      ),
      if (product != null)
        _ProductDangerSection(
          product: product,
          onDelete: () async {
            final id = product.id;
            if (id == null) {
              return null;
            }
            final success = await onDelete(id);
            if (!success) {
              return null;
            }
            return ProductDetailDialogResult(
              action: ProductDetailDialogAction.deleted,
              message: '제품을 삭제했습니다.',
              product: product,
            );
          },
          onRestore: () async {
            final id = product.id;
            if (id == null) {
              return null;
            }
            final restored = await onRestore(id);
            if (restored == null) {
              return null;
            }
            return ProductDetailDialogResult(
              action: ProductDetailDialogAction.restored,
              message: '제품을 복구했습니다.',
              product: restored,
            );
          },
        ),
    ],
    summary: product == null
        ? null
        : Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                product.productName,
                style: ShadTheme.of(context).textTheme.h4,
              ),
              const SizedBox(height: 4),
              Text(
                '제품코드 ${product.productCode}',
                style: ShadTheme.of(context).textTheme.muted,
              ),
            ],
          ),
    summaryBadges: product == null
        ? const []
        : [
            if (product.isActive)
              const ShadBadge(child: Text('사용중'))
            else
              const ShadBadge.outline(child: Text('미사용')),
            if (product.isDeleted)
              const ShadBadge.destructive(child: Text('삭제됨')),
          ],
    metadata: metadata,
    initialSectionId: product == null
        ? _ProductDetailSections.create
        : _ProductDetailSections.relations,
    emptyPlaceholder: const Text('표시할 세부 정보가 없습니다.'),
  );
}

/// 제품 상세 다이얼로그 섹션 정의 모음이다.
class _ProductDetailSections {
  static const relations = 'relations';
  static const history = 'history';
  static const edit = 'edit';
  static const delete = 'delete';
  static const restore = 'restore';
  static const create = 'create';
}

/// 제품과 연결된 제조사/단위 정보를 표시하는 섹션이다.
class _ProductRelationsSection extends StatelessWidget {
  const _ProductRelationsSection({required this.product});

  final Product product;

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

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _RelationTile(
          icon: LucideIcons.factory,
          title: '제조사',
          description: vendor == null
              ? '연결된 제조사가 없습니다.'
              : '${vendor.vendorName} (${vendor.vendorCode})',
        ),
        const SizedBox(height: 16),
        _RelationTile(
          icon: LucideIcons.scale,
          title: '단위(UOM)',
          description: uom == null ? '연결된 단위 정보가 없습니다.' : uom.uomName,
        ),
        const SizedBox(height: 16),
        Text(
          '하단의 수정 섹션에서 제조사와 단위를 변경할 수 있습니다.',
          style: theme.textTheme.small.copyWith(
            color: theme.colorScheme.mutedForeground,
          ),
        ),
      ],
    );
  }
}

/// 제품 변경 이력을 안내하는 섹션이다.
class _ProductHistorySection extends StatelessWidget {
  const _ProductHistorySection();

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('현재 제품 변경 이력 데이터는 준비 중입니다.', style: theme.textTheme.small),
        const SizedBox(height: 12),
        Text(
          '재고 입출고 추적 기능이 추가되면 히스토리를 통해 상태 변화를 확인할 수 있습니다.',
          style: theme.textTheme.small.copyWith(
            color: theme.colorScheme.mutedForeground,
          ),
        ),
      ],
    );
  }
}

/// 제품 등록/수정 폼을 제공하는 섹션이다.
class _ProductFormSection extends SuperportDetailDialogSection {
  _ProductFormSection({
    required super.id,
    required super.label,
    required Product? product,
    required this.vendorOptions,
    required this.uomOptions,
    required this.onSubmit,
  }) : super(
         icon: LucideIcons.pencil,
         builder: (context) => _ProductForm(
           product: product,
           vendorOptions: vendorOptions,
           uomOptions: uomOptions,
           onSubmit: onSubmit,
         ),
       );

  final List<Vendor> vendorOptions;
  final List<Uom> uomOptions;
  final Future<ProductDetailDialogResult?> Function(ProductInput input)
  onSubmit;
}

/// 제품 삭제/복구 액션을 제공하는 섹션이다.
class _ProductDangerSection extends SuperportDetailDialogSection {
  _ProductDangerSection({
    required this.product,
    required this.onDelete,
    required this.onRestore,
  }) : super(
         id: product.isDeleted
             ? _ProductDetailSections.restore
             : _ProductDetailSections.delete,
         label: product.isDeleted ? '복구' : '삭제',
         icon: product.isDeleted ? LucideIcons.history : LucideIcons.trash2,
         builder: (context) => _ProductDangerContent(
           product: product,
           onDelete: onDelete,
           onRestore: onRestore,
         ),
         scrollable: false,
       );

  final Product product;
  final Future<ProductDetailDialogResult?> Function() onDelete;
  final Future<ProductDetailDialogResult?> Function() onRestore;
}

/// 제품 삭제/복구 안내 레이아웃이다.
class _ProductDangerContent extends StatelessWidget {
  const _ProductDangerContent({
    required this.product,
    required this.onDelete,
    required this.onRestore,
  });

  final Product product;
  final Future<ProductDetailDialogResult?> Function() onDelete;
  final Future<ProductDetailDialogResult?> Function() onRestore;

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    final isDeleted = product.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 _ProductForm extends StatefulWidget {
  const _ProductForm({
    required this.product,
    required this.vendorOptions,
    required this.uomOptions,
    required this.onSubmit,
  });

  final Product? product;
  final List<Vendor> vendorOptions;
  final List<Uom> uomOptions;
  final Future<ProductDetailDialogResult?> Function(ProductInput input)
  onSubmit;

  @override
  State<_ProductForm> createState() => _ProductFormState();
}

class _ProductFormState extends State<_ProductForm> {
  late final TextEditingController _codeController;
  late final TextEditingController _nameController;
  late final TextEditingController _noteController;
  late final ValueNotifier<int?> _vendorNotifier;
  late final ValueNotifier<int?> _uomNotifier;
  late final ValueNotifier<bool> _isActiveNotifier;
  String? _codeError;
  String? _nameError;
  String? _vendorError;
  String? _uomError;
  String? _submitError;
  bool _isSubmitting = false;

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

  @override
  void initState() {
    super.initState();
    final product = widget.product;
    _codeController = TextEditingController(text: product?.productCode ?? '');
    _nameController = TextEditingController(text: product?.productName ?? '');
    _noteController = TextEditingController(text: product?.note ?? '');
    _vendorNotifier = ValueNotifier<int?>(product?.vendor?.id);
    _uomNotifier = ValueNotifier<int?>(product?.uom?.id);
    _isActiveNotifier = ValueNotifier<bool>(product?.isActive ?? true);
  }

  @override
  void dispose() {
    _codeController.dispose();
    _nameController.dispose();
    _noteController.dispose();
    _vendorNotifier.dispose();
    _uomNotifier.dispose();
    _isActiveNotifier.dispose();
    super.dispose();
  }

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

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _ProductFormField(
          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),
        _ProductFormField(
          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),
        _ProductFormField(
          label: '제조사',
          child: ValueListenableBuilder<int?>(
            valueListenable: _vendorNotifier,
            builder: (_, vendorId, __) {
              final initialLabel = widget.product?.vendor == null
                  ? null
                  : '${widget.product!.vendor!.vendorName} '
                        '(${widget.product!.vendor!.vendorCode})';
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  VendorAutocompleteField(
                    initialOptions: widget.vendorOptions,
                    selectedVendorId: vendorId,
                    initialLabel: initialLabel,
                    onSelected: (id) {
                      _vendorNotifier.value = id;
                      setState(() {
                        _vendorError = null;
                      });
                    },
                  ),
                  if (_vendorError != null)
                    Padding(
                      padding: const EdgeInsets.only(top: 6),
                      child: Text(
                        _vendorError!,
                        style: theme.textTheme.small.copyWith(
                          color: theme.colorScheme.destructive,
                        ),
                      ),
                    ),
                ],
              );
            },
          ),
        ),
        const SizedBox(height: 16),
        _ProductFormField(
          label: '단위',
          child: ValueListenableBuilder<int?>(
            valueListenable: _uomNotifier,
            builder: (_, uomId, __) {
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  UomAutocompleteField(
                    initialOptions: widget.uomOptions,
                    selectedUomId: uomId,
                    initialLabel: widget.product?.uom?.uomName,
                    onSelected: (id) {
                      _uomNotifier.value = id;
                      setState(() {
                        _uomError = null;
                      });
                    },
                  ),
                  if (_uomError != null)
                    Padding(
                      padding: const EdgeInsets.only(top: 6),
                      child: Text(
                        _uomError!,
                        style: theme.textTheme.small.copyWith(
                          color: theme.colorScheme.destructive,
                        ),
                      ),
                    ),
                ],
              );
            },
          ),
        ),
        const SizedBox(height: 16),
        _ProductFormField(
          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),
        _ProductFormField(
          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> _handleSubmit() async {
    final code = _codeController.text.trim();
    final name = _nameController.text.trim();
    final vendorId = _vendorNotifier.value;
    final uomId = _uomNotifier.value;

    setState(() {
      _codeError = code.isEmpty ? '제품코드를 입력하세요.' : null;
      _nameError = name.isEmpty ? '제품명을 입력하세요.' : null;
      _vendorError = vendorId == null ? '제조사를 선택하세요.' : null;
      _uomError = uomId == null ? '단위를 선택하세요.' : null;
      _submitError = null;
    });

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

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

    final input = ProductInput(
      productCode: code,
      productName: name,
      vendorId: vendorId!,
      uomId: uomId!,
      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 _ProductFormField extends StatelessWidget {
  const _ProductFormField({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,
      ],
    );
  }
}

/// 관계 타일을 렌더링하는 위젯이다.
class _RelationTile extends StatelessWidget {
  const _RelationTile({
    required this.icon,
    required this.title,
    required this.description,
  });

  final IconData icon;
  final String title;
  final String description;

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    return ShadCard(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.only(right: 12, top: 4),
            child: Icon(icon, size: 18),
          ),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: theme.textTheme.small.copyWith(
                    fontWeight: FontWeight.w600,
                  ),
                ),
                const SizedBox(height: 6),
                Text(description, style: theme.textTheme.small),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

/// 키-값 행 데이터를 표현하는 모델이다.
