import 'package:flutter/material.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart' as lucide;
import 'package:shadcn_ui/shadcn_ui.dart';

import '../../../../../widgets/components/feedback.dart';
import '../../../shared/domain/entities/approval_approver_candidate.dart';
import '../../../shared/widgets/approver_autocomplete_field.dart';
import '../controllers/approval_request_controller.dart';

/// 결재 단계 테이블에서 단일 행을 편집하기 위한 위젯.
///
/// - 순번, 승인자 자동완성, 역할/메모 입력, 삭제 버튼을 한 번에 제공한다.
class ApprovalStepRow extends StatefulWidget {
  const ApprovalStepRow({
    super.key,
    required this.controller,
    required this.step,
    required this.index,
    this.onRemove,
    this.isFinal = false,
    this.hasDuplicateApprover = false,
    this.isRequesterConflict = false,
    this.readOnly = false,
  });

  /// 결재 단계 상태를 관리하는 컨트롤러.
  final ApprovalRequestController controller;

  /// 현재 행에 해당하는 단계 데이터.
  final ApprovalRequestStep step;

  /// 행 인덱스(0-base).
  final int index;

  /// 행 삭제 시 실행할 콜백.
  final VoidCallback? onRemove;

  /// 마지막 단계(최종 승인자)인지 여부.
  final bool isFinal;

  /// 승인자 중복 오류가 있는지 여부.
  final bool hasDuplicateApprover;

  /// 상신자와 중복되는 승인자인지 여부.
  final bool isRequesterConflict;

  /// 읽기 전용 모드 여부.
  final bool readOnly;

  @override
  State<ApprovalStepRow> createState() => _ApprovalStepRowState();
}

class _ApprovalStepRowState extends State<ApprovalStepRow> {
  late final TextEditingController _approverIdController;
  late final TextEditingController _noteController;
  late ApprovalRequestParticipant _currentApprover;
  int _fieldVersion = 0;

  @override
  void initState() {
    super.initState();
    _currentApprover = widget.step.approver;
    _approverIdController = TextEditingController(
      text: widget.step.approverId.toString(),
    );
    _noteController = TextEditingController(text: widget.step.note ?? '');
  }

  @override
  void didUpdateWidget(covariant ApprovalStepRow oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.step.approverId != widget.step.approverId) {
      _currentApprover = widget.step.approver;
      _approverIdController.text = widget.step.approverId.toString();
      _refreshAutocompleteField();
    }
    if (oldWidget.step.note != widget.step.note &&
        widget.step.note != _noteController.text) {
      _noteController.text = widget.step.note ?? '';
    }
  }

  @override
  void dispose() {
    _approverIdController.dispose();
    _noteController.dispose();
    super.dispose();
  }

  void _refreshAutocompleteField() {
    setState(() {
      _fieldVersion += 1;
    });
  }

  Future<void> _handleApproverSelected(
    BuildContext context,
    ApprovalApproverCandidate? candidate,
  ) async {
    if (widget.readOnly) {
      return;
    }
    ApprovalRequestParticipant? nextParticipant;

    if (candidate != null) {
      nextParticipant = ApprovalRequestParticipant(
        id: candidate.id,
        name: candidate.name,
        employeeNo: candidate.employeeNo,
      );
    } else {
      SuperportToast.warning(context, '승인자를 다시 선택해주세요.');
      _restorePreviousApprover();
      return;
    }

    final updated = widget.controller.updateStep(
      widget.index,
      approver: nextParticipant,
    );
    if (!updated) {
      SuperportToast.error(
        context,
        widget.controller.errorMessage ?? '승인자 변경에 실패했습니다.',
      );
      _restorePreviousApprover();
      return;
    }
    setState(() {
      _currentApprover = nextParticipant!;
      _approverIdController.text = nextParticipant.id.toString();
    });
    if (widget.hasDuplicateApprover) {
      SuperportToast.warning(context, '동일한 승인자가 존재하지 않도록 구성해주세요.');
    } else {
      SuperportToast.info(
        context,
        '단계 ${widget.step.stepOrder} 승인자를 ${nextParticipant.name} 님으로 변경했습니다.',
      );
    }
  }

  void _restorePreviousApprover() {
    _approverIdController.text = _currentApprover.id.toString();
    _refreshAutocompleteField();
  }

  void _handleNoteChanged(String value) {
    if (widget.readOnly) {
      return;
    }
    final trimmed = value.trim();
    widget.controller.updateStep(
      widget.index,
      note: trimmed.isEmpty ? null : trimmed,
    );
  }

  void _handleMove(int offset) {
    if (widget.readOnly) {
      return;
    }
    final targetIndex = widget.index + offset;
    final total = widget.controller.totalSteps;
    if (targetIndex < 0 || targetIndex >= total) {
      return;
    }
    widget.controller.moveStep(widget.index, targetIndex);
    final direction = offset < 0 ? '위로' : '아래로';
    SuperportToast.info(context, '결재 단계 순서를 $direction 조정했습니다.');
  }

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    final hasError = widget.hasDuplicateApprover || widget.isRequesterConflict;
    final borderColor = hasError
        ? theme.colorScheme.destructive
        : theme.colorScheme.border;
    final badgeColor = hasError
        ? theme.colorScheme.destructive
        : theme.colorScheme.secondary;

    return Container(
      decoration: BoxDecoration(
        border: Border.all(color: borderColor, width: 1),
        borderRadius: BorderRadius.circular(12),
      ),
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _StepBadge(order: widget.step.stepOrder, badgeColor: badgeColor),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      widget.isFinal ? '최종 승인자' : '승인자',
                      style: theme.textTheme.small.copyWith(
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    const SizedBox(height: 8),
                    IgnorePointer(
                      ignoring: widget.readOnly,
                      child: Opacity(
                        opacity: widget.readOnly ? 0.6 : 1,
                        child: ApprovalApproverAutocompleteField(
                          key: ValueKey(
                            'approver_field_${widget.index}_$_fieldVersion',
                          ),
                          idController: _approverIdController,
                          onSelected: (item) =>
                              _handleApproverSelected(context, item),
                          hintText: '승인자 이름 또는 사번 검색',
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 12),
              SizedBox(
                width: 220,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '역할/메모',
                      style: theme.textTheme.small.copyWith(
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    const SizedBox(height: 8),
                    ShadInput(
                      controller: _noteController,
                      onChanged: _handleNoteChanged,
                      enabled: !widget.readOnly,
                      placeholder: const Text('예: 팀장 승인'),
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 12),
              SizedBox(
                width: 44,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    IconButton(
                      onPressed: widget.readOnly || widget.index == 0
                          ? null
                          : () => _handleMove(-1),
                      tooltip: '위로 이동',
                      icon: const Icon(lucide.LucideIcons.chevronUp, size: 18),
                    ),
                    IconButton(
                      onPressed:
                          widget.readOnly ||
                              widget.index >= widget.controller.totalSteps - 1
                          ? null
                          : () => _handleMove(1),
                      tooltip: '아래로 이동',
                      icon: const Icon(
                        lucide.LucideIcons.chevronDown,
                        size: 18,
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 4),
              IconButton(
                onPressed: widget.readOnly || widget.onRemove == null
                    ? null
                    : widget.onRemove,
                tooltip: '단계 삭제',
                icon: Icon(
                  lucide.LucideIcons.trash2,
                  color: widget.readOnly || widget.onRemove == null
                      ? theme.colorScheme.mutedForeground
                      : theme.colorScheme.destructive,
                ),
              ),
            ],
          ),
          if (hasError)
            Padding(
              padding: const EdgeInsets.only(top: 12),
              child: Row(
                children: [
                  Icon(
                    lucide.LucideIcons.triangleAlert,
                    size: 16,
                    color: theme.colorScheme.destructive,
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      widget.hasDuplicateApprover
                          ? '동일한 승인자가 중복되어 있습니다. 다른 승인자를 선택해주세요.'
                          : '상신자는 승인자로 지정할 수 없습니다. 다른 승인자를 선택해주세요.',
                      style: theme.textTheme.small.copyWith(
                        color: theme.colorScheme.destructive,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          if (widget.isFinal && !hasError)
            Padding(
              padding: const EdgeInsets.only(top: 12),
              child: Row(
                children: [
                  Icon(
                    lucide.LucideIcons.circleCheck,
                    size: 16,
                    color: theme.colorScheme.primary,
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      '마지막 단계가 최종 승인자로 처리됩니다.',
                      style: theme.textTheme.small.copyWith(
                        color: theme.colorScheme.primary,
                      ),
                    ),
                  ),
                ],
              ),
            ),
        ],
      ),
    );
  }
}

class _StepBadge extends StatelessWidget {
  const _StepBadge({required this.order, required this.badgeColor});

  final int order;
  final Color badgeColor;

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    return Container(
      width: 44,
      height: 44,
      decoration: BoxDecoration(
        color: badgeColor.withValues(alpha: 0.12),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: badgeColor.withValues(alpha: 0.4)),
      ),
      alignment: Alignment.center,
      child: Text(
        order.toString(),
        style: theme.textTheme.large.copyWith(
          fontWeight: FontWeight.w700,
          color: badgeColor,
        ),
      ),
    );
  }
}
