import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:superport/data/models/vendor_dto.dart';
import 'package:superport/screens/vendor/controllers/vendor_controller.dart';

class VendorFormDialog extends StatefulWidget {
  final VendorDto? vendor;
  final Function(VendorDto) onSave;

  const VendorFormDialog({
    super.key,
    this.vendor,
    required this.onSave,
  });

  @override
  State<VendorFormDialog> createState() => _VendorFormDialogState();
}

class _VendorFormDialogState extends State<VendorFormDialog> {
  final _formKey = GlobalKey<FormState>();
  late final TextEditingController _nameController;
  late bool _isActive;
  
  bool _isLoading = false;
  String? _statusMessage;

  @override
  void initState() {
    super.initState();
    final vendor = widget.vendor;
    
    _nameController = TextEditingController(text: vendor?.name ?? '');
    _isActive = vendor?.isActive ?? true;
  }

  @override
  void dispose() {
    _nameController.dispose();
    super.dispose();
  }

  Future<bool> _checkDuplicate() async {
    final name = _nameController.text.trim();
    if (name.isEmpty) return false;
    
    // 수정 모드일 때 현재 이름과 같으면 검사하지 않음
    if (widget.vendor != null && widget.vendor!.name == name) {
      return false;
    }
    
    try {
      final controller = context.read<VendorController>();
      final isDuplicate = await controller.checkDuplicateName(
        name,
        excludeId: widget.vendor?.id,
      );
      
      return isDuplicate;
    } catch (e) {
      // 네트워크 오류 시 false 반환
      return false;
    }
  }
  
  void _handleSave() async {
    if (!_formKey.currentState!.validate()) return;
    
    setState(() {
      _isLoading = true;
      _statusMessage = '중복 확인 중...';
    });
    
    // 저장 시 중복 검사 수행
    final isDuplicate = await _checkDuplicate();
    
    if (isDuplicate) {
      setState(() {
        _isLoading = false;
        _statusMessage = '이미 존재하는 벤더명입니다.';
      });
      return;
    }
    
    setState(() {
      _statusMessage = '저장 중...';
    });
    
    final vendor = VendorDto(
      id: widget.vendor?.id,
      name: _nameController.text.trim(),
      isDeleted: !_isActive,
      createdAt: widget.vendor?.createdAt,
      updatedAt: DateTime.now(),
    );
    
    await widget.onSave(vendor);
    
    setState(() {
      _isLoading = false;
      _statusMessage = null;
    });
  }

  String? _validateRequired(String? value, String fieldName) {
    if (value == null || value.trim().isEmpty) {
      return '$fieldName은(는) 필수 입력 항목입니다.';
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    final isEdit = widget.vendor != null;
    
    return ShadDialog(
      title: Text(isEdit ? '벤더 수정' : '벤더 등록'),
      description: const Text('벤더 정보를 입력하세요'),
      child: SizedBox(
        width: 500,
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 벤더명 (필수)
              ShadInputFormField(
                controller: _nameController,
                label: const Text('벤더명 *'),
                placeholder: const Text('예: 삼성전자, LG전자, 애플'),
                validator: (value) => _validateRequired(value, '벤더명'),
              ),
              
              // 상태 메시지 영역 (고정 높이)
              SizedBox(
                height: 20,
                child: _statusMessage != null
                    ? Text(
                        _statusMessage!,
                        style: theme.textTheme.muted.copyWith(
                          fontSize: 12,
                          color: _statusMessage!.contains('존재')
                              ? Colors.red
                              : theme.textTheme.muted.color,
                        ),
                      )
                    : const SizedBox.shrink(),
              ),
              const SizedBox(height: 24),
              
              // 활성 상태
              Row(
                children: [
                  ShadCheckbox(
                    value: _isActive,
                    onChanged: (value) {
                      setState(() => _isActive = value ?? true);
                    },
                  ),
                  const SizedBox(width: 8),
                  Text(
                    '활성 벤더',
                    style: theme.textTheme.p,
                  ),
                  const SizedBox(width: 8),
                  Text(
                    '(비활성 시 선택 목록에서 제외됩니다)',
                    style: theme.textTheme.muted,
                  ),
                ],
              ),
              
              // Actions
              const SizedBox(height: 24),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  ShadButton.outline(
                    onPressed: _isLoading ? null : () => Navigator.of(context).pop(),
                    child: const Text('취소'),
                  ),
                  const SizedBox(width: 8),
                  ShadButton(
                    onPressed: _isLoading ? null : _handleSave,
                    child: _isLoading
                        ? const SizedBox(
                            width: 16,
                            height: 16,
                            child: CircularProgressIndicator(strokeWidth: 2),
                          )
                        : Text(isEdit ? '수정' : '등록'),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}