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

import '../../common/theme_shadcn.dart';
import '../../../data/models/equipment/equipment_dto.dart';
import '../../../injection_container.dart';
import '../controllers/equipment_controller.dart';

/// 장비 복구 확인 다이얼로그
class EquipmentRestoreDialog extends StatefulWidget {
  final EquipmentDto equipment;
  final VoidCallback? onRestored;

  const EquipmentRestoreDialog({
    super.key,
    required this.equipment,
    this.onRestored,
  });

  @override
  State<EquipmentRestoreDialog> createState() => _EquipmentRestoreDialogState();
}

class _EquipmentRestoreDialogState extends State<EquipmentRestoreDialog> {
  late final EquipmentController _controller;
  bool _isRestoring = false;

  @override
  void initState() {
    super.initState();
    _controller = sl<EquipmentController>();
  }

  Future<void> _restore() async {
    setState(() {
      _isRestoring = true;
    });

    final success = await _controller.restoreEquipment(widget.equipment.id);

    if (mounted) {
      if (success) {
        Navigator.of(context).pop(true);
        if (widget.onRestored != null) {
          widget.onRestored!();
        }
        
        // 성공 메시지
        ShadToaster.of(context).show(
          ShadToast(
            title: const Text('복구 완료'),
            description: Text('${widget.equipment.serialNumber} 장비가 복구되었습니다.'),
          ),
        );
      } else {
        setState(() {
          _isRestoring = false;
        });
        
        // 실패 메시지
        ShadToaster.of(context).show(
          ShadToast.destructive(
            title: const Text('복구 실패'),
            description: Text(_controller.error ?? '장비 복구에 실패했습니다.'),
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return ShadDialog(
      child: SizedBox(
        width: 400,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 헤더
            Row(
              children: [
                Icon(Icons.restore, color: Colors.green, size: 24),
                const SizedBox(width: 12),
                Expanded(
                  child: Text('장비 복구', style: ShadcnTheme.headingH3),
                ),
              ],
            ),
            const SizedBox(height: 24),

            // 복구 정보
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.green.withValues(alpha: 0.1),
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.green.withValues(alpha: 0.2)),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '다음 장비를 복구하시겠습니까?',
                    style: ShadcnTheme.bodyLarge.copyWith(fontWeight: FontWeight.w500),
                  ),
                  const SizedBox(height: 12),
                  _buildInfoRow('시리얼 번호', widget.equipment.serialNumber),
                  if (widget.equipment.barcode != null)
                    _buildInfoRow('바코드', widget.equipment.barcode!),
                  if (widget.equipment.modelName != null)
                    _buildInfoRow('모델명', widget.equipment.modelName!),
                  if (widget.equipment.companyName != null)
                    _buildInfoRow('소속 회사', widget.equipment.companyName!),
                ],
              ),
            ),
            
            const SizedBox(height: 16),
            
            Text(
              '복구된 장비는 다시 활성 상태로 변경됩니다.',
              style: ShadcnTheme.bodyMedium.copyWith(
                color: ShadcnTheme.foregroundMuted,
              ),
            ),

            const SizedBox(height: 24),

            // 버튼들
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                ShadButton.outline(
                  onPressed: _isRestoring ? null : () => Navigator.of(context).pop(false),
                  child: const Text('취소'),
                ),
                const SizedBox(width: 12),
                ShadButton(
                  onPressed: _isRestoring ? null : _restore,
                  child: _isRestoring
                    ? Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          SizedBox(
                            width: 16,
                            height: 16,
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                              color: ShadcnTheme.primaryForeground,
                            ),
                          ),
                          const SizedBox(width: 8),
                          const Text('복구 중...'),
                        ],
                      )
                    : const Text('복구'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              '$label:',
              style: ShadcnTheme.bodySmall.copyWith(
                color: ShadcnTheme.foregroundMuted,
              ),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: ShadcnTheme.bodySmall.copyWith(
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

/// 장비 복구 다이얼로그 표시 유틸리티
Future<bool?> showEquipmentRestoreDialog(
  BuildContext context, {
  required EquipmentDto equipment,
  VoidCallback? onRestored,
}) async {
  return await showDialog<bool>(
    context: context,
    barrierDismissible: false,
    builder: (context) => EquipmentRestoreDialog(
      equipment: equipment,
      onRestored: onRestored,
    ),
  );
}
