import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:superport/data/models/administrator_dto.dart';
import 'package:superport/screens/administrator/controllers/administrator_controller.dart';
import 'package:superport/screens/common/widgets/pagination.dart';

/// shadcn/ui 스타일로 재설계된 관리자 관리 화면
class AdministratorList extends StatefulWidget {
  const AdministratorList({super.key});

  @override
  State<AdministratorList> createState() => _AdministratorListState();
}

class _AdministratorListState extends State<AdministratorList> {
  final TextEditingController _searchController = TextEditingController();
  late AdministratorController _controller;
  Timer? _debounce;

  @override
  void initState() {
    super.initState();
    _controller = Provider.of<AdministratorController>(context, listen: false);
    
    // 초기 데이터 로드
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _controller.initialize();
    });
    
    // 검색 디바운싱
    _searchController.addListener(() {
      _onSearchChanged(_searchController.text);
    });
  }

  @override
  void dispose() {
    _searchController.dispose();
    _debounce?.cancel();
    super.dispose();
  }

  /// 검색어 변경 처리 (디바운싱)
  void _onSearchChanged(String query) {
    if (_debounce?.isActive ?? false) _debounce!.cancel();
    _debounce = Timer(const Duration(milliseconds: 300), () {
      _controller.setSearchQuery(query);
    });
  }

  /// 관리자 추가 다이얼로그
  void _showAddDialog() {
    showShadDialog(
      context: context,
      builder: (context) => _AdministratorFormDialog(
        title: '관리자 추가',
        onSubmit: (name, phone, mobile, email, password) async {
          final success = await _controller.createAdministrator(
            name: name,
            phone: phone,
            mobile: mobile,
            email: email,
            password: password ?? '',
          );
          
          if (success && mounted) {
            Navigator.of(context).pop();
            ShadToaster.of(context).show(
              const ShadToast(
                title: Text('생성 완료'),
                description: Text('관리자가 생성되었습니다'),
              ),
            );
          }
          
          return success;
        },
      ),
    );
  }

  /// 관리자 수정 다이얼로그
  void _showEditDialog(AdministratorDto administrator) {
    showShadDialog(
      context: context,
      builder: (context) => _AdministratorFormDialog(
        title: '관리자 수정',
        administrator: administrator,
        onSubmit: (name, phone, mobile, email, password) async {
          final success = await _controller.updateAdministrator(
            administrator.id!,
            name: name,
            phone: phone,
            mobile: mobile,
            email: email,
            password: password ?? '',
          );
          
          if (success && mounted) {
            Navigator.of(context).pop();
            ShadToaster.of(context).show(
              const ShadToast(
                title: Text('수정 완료'),
                description: Text('관리자 정보가 수정되었습니다'),
              ),
            );
          }
          
          return success;
        },
      ),
    );
  }

  /// 관리자 삭제 확인 다이얼로그
  void _showDeleteDialog(AdministratorDto administrator) {
    showShadDialog(
      context: context,
      builder: (context) => ShadDialog(
        title: const Text('관리자 삭제'),
        description: Text('"${administrator.name}" 관리자를 정말로 삭제하시겠습니까?'),
        actions: [
          ShadButton.outline(
            child: const Text('취소'),
            onPressed: () => Navigator.of(context).pop(),
          ),
          ShadButton.destructive(
            child: const Text('삭제'),
            onPressed: () async {
              Navigator.of(context).pop();
              
              final success = await _controller.deleteAdministrator(administrator.id!);
              
              if (success && mounted) {
                ShadToaster.of(context).show(
                  const ShadToast(
                    title: Text('삭제 완료'),
                    description: Text('관리자가 삭제되었습니다'),
                  ),
                );
              } else if (mounted && _controller.errorMessage != null) {
                ShadToaster.of(context).show(
                  ShadToast.destructive(
                    title: const Text('삭제 실패'),
                    description: Text(_controller.errorMessage!),
                  ),
                );
              }
            },
          ),
        ],
      ),
    );
  }

  // 기존 DataTable 구현 제거 (ShadTable.list로 이식)

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          // Action Bar
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                // 제목
                const Text(
                  '관리자 관리',
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(width: 16),
                // 검색창
                Expanded(
                  child: Container(
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey.shade300),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Row(
                      children: [
                        const Padding(
                          padding: EdgeInsets.all(12),
                          child: Icon(Icons.search, size: 16, color: Colors.grey),
                        ),
                        Expanded(
                          child: TextField(
                            controller: _searchController,
                            decoration: const InputDecoration(
                              hintText: '이름 또는 이메일로 검색',
                              border: InputBorder.none,
                              contentPadding: EdgeInsets.symmetric(vertical: 12),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                const SizedBox(width: 16),
                // 추가 버튼
                ShadButton(
                  onPressed: _showAddDialog,
                  child: const Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(Icons.add, size: 16),
                      SizedBox(width: 4),
                      Text('관리자 추가'),
                    ],
                  ),
                ),
                const SizedBox(width: 8),
                // 새로고침 버튼
                ShadButton.outline(
                  onPressed: () => _controller.refresh(),
                  child: const Icon(Icons.refresh, size: 16),
                ),
              ],
            ),
          ),
          
          // Content
          Expanded(
            child: Consumer<AdministratorController>(
              builder: (context, controller, child) {
                if (controller.isLoading && controller.administrators.isEmpty) {
                  return const Center(child: CircularProgressIndicator());
                }

                if (controller.errorMessage != null && controller.administrators.isEmpty) {
                  return Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        const Icon(Icons.error_outline, size: 64, color: Colors.red),
                        const SizedBox(height: 16),
                        Text(
                          controller.errorMessage!,
                          textAlign: TextAlign.center,
                          style: const TextStyle(color: Colors.red),
                        ),
                        const SizedBox(height: 16),
                        ShadButton(
                          child: const Text('다시 시도'),
                          onPressed: () => controller.refresh(),
                        ),
                      ],
                    ),
                  );
                }

                return Column(
                  children: [
                    // Summary Card
                    Padding(
                      padding: const EdgeInsets.all(16),
                      child: ShadCard(
                        child: Padding(
                          padding: const EdgeInsets.all(16),
                          child: Row(
                            children: [
                              const Icon(Icons.admin_panel_settings, size: 32),
                              const SizedBox(width: 16),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  const Text(
                                    '전체 관리자',
                                    style: TextStyle(fontSize: 14, color: Colors.grey),
                                  ),
                                  Text(
                                    '${controller.totalCount}명',
                                    style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
                                  ),
                                ],
                              ),
                              const Spacer(),
                              if (controller.isLoading)
                                const SizedBox(
                                  width: 20,
                                  height: 20,
                                  child: CircularProgressIndicator(strokeWidth: 2),
                                ),
                            ],
                          ),
                        ),
                      ),
                    ),

                    // Data Table (ShadTable.list)
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 16),
                        child: ShadCard(
                          child: controller.administrators.isEmpty
                              ? const Padding(
                                  padding: EdgeInsets.all(64),
                                  child: Center(
                                    child: Column(
                                      children: [
                                        Icon(Icons.inbox, size: 64, color: Colors.grey),
                                        SizedBox(height: 16),
                                        Text('관리자가 없습니다', style: TextStyle(fontSize: 18, color: Colors.grey)),
                                      ],
                                    ),
                                  ),
                                )
                              : LayoutBuilder(
                                  builder: (context, constraints) {
                                    // 최소 폭 추정: 이름(160) + 이메일(260) + 전화(160) + 휴대폰(160) + 작업(160) + 여백(24)
                                    const double minW = 160 + 260 + 160 + 160 + 160 + 24;
                                    final double tableW = constraints.maxWidth >= minW ? constraints.maxWidth : minW;
                                    const double emailBase = 260.0;
                                    final double emailW = emailBase; // 고정 폭, 남는 폭은 filler가 흡수

                                    return SingleChildScrollView(
                                      scrollDirection: Axis.horizontal,
                                      child: SizedBox(
                                        width: tableW,
                                        child: ShadTable.list(
                                          columnSpanExtent: (index) {
                                            switch (index) {
                                              case 0:
                                                return const FixedTableSpanExtent(160); // 이름
                                              case 1:
                                                return FixedTableSpanExtent(emailW); // 이메일
                                              case 2:
                                                return const FixedTableSpanExtent(160); // 전화
                                              case 3:
                                                return const FixedTableSpanExtent(160); // 휴대폰
                                              case 4:
                                                return const FixedTableSpanExtent(160); // 작업
                                              case 5:
                                                return const RemainingTableSpanExtent(); // filler
                                              default:
                                                return const FixedTableSpanExtent(100);
                                            }
                                          },
                                          header: [
                                            const ShadTableCell.header(child: Text('이름')),
                                            ShadTableCell.header(child: SizedBox(width: emailW, child: const Text('이메일'))),
                                            const ShadTableCell.header(child: Text('전화번호')),
                                            const ShadTableCell.header(child: Text('휴대폰')),
                                            const ShadTableCell.header(child: Text('작업')),
                                            const ShadTableCell.header(child: SizedBox.shrink()),
                                          ],
                                          children: controller.administrators.map((admin) {
                                            return [
                                              ShadTableCell(child: Text(admin.name, overflow: TextOverflow.ellipsis)),
                                              ShadTableCell(
                                                child: SizedBox(
                                                  width: emailW,
                                                  child: Text(admin.email, overflow: TextOverflow.ellipsis)),
                                              ),
                                              ShadTableCell(child: Text(admin.phone, overflow: TextOverflow.ellipsis)),
                                              ShadTableCell(child: Text(admin.mobile, overflow: TextOverflow.ellipsis)),
                                              ShadTableCell(
                                                child: Row(
                                                  mainAxisSize: MainAxisSize.min,
                                                  children: [
                                                    ShadButton.ghost(
                                                      size: ShadButtonSize.sm,
                                                      onPressed: () => _showEditDialog(admin),
                                                      child: const Icon(Icons.edit, size: 16),
                                                    ),
                                                    const SizedBox(width: 4),
                                                    ShadButton.ghost(
                                                      size: ShadButtonSize.sm,
                                                      onPressed: () => _showDeleteDialog(admin),
                                                      child: const Icon(Icons.delete, size: 16, color: Colors.red),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              const ShadTableCell(child: SizedBox.shrink()),
                                            ];
                                          }).toList(),
                                        ),
                                      ),
                                    );
                                  },
                                ),
                        ),
                      ),
                    ),

                    // Pagination (항상 표시)
                    Padding(
                      padding: const EdgeInsets.all(16),
                      child: Pagination(
                        totalCount: controller.totalCount,
                        currentPage: controller.currentPage,
                        pageSize: controller.pageSize,
                        onPageChanged: (page) => controller.goToPage(page),
                      ),
                    ),
                  ],
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

/// 관리자 추가/수정 다이얼로그
class _AdministratorFormDialog extends StatefulWidget {
  final String title;
  final AdministratorDto? administrator;
  final Future<bool> Function(String name, String phone, String mobile, String email, String? password) onSubmit;

  const _AdministratorFormDialog({
    required this.title,
    this.administrator,
    required this.onSubmit,
  });

  @override
  State<_AdministratorFormDialog> createState() => _AdministratorFormDialogState();
}

class _AdministratorFormDialogState extends State<_AdministratorFormDialog> {
  final _formKey = GlobalKey<FormState>();
  late final TextEditingController _nameController;
  late final TextEditingController _phoneController;
  late final TextEditingController _mobileController;
  late final TextEditingController _emailController;
  late final TextEditingController _passwordController;
  
  bool _isSubmitting = false;

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController(text: widget.administrator?.name ?? '');
    _phoneController = TextEditingController(text: widget.administrator?.phone ?? '');
    _mobileController = TextEditingController(text: widget.administrator?.mobile ?? '');
    _emailController = TextEditingController(text: widget.administrator?.email ?? '');
    _passwordController = TextEditingController();
  }

  @override
  void dispose() {
    _nameController.dispose();
    _phoneController.dispose();
    _mobileController.dispose();
    _emailController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  bool get _isEditMode => widget.administrator != null;

  Future<void> _handleSubmit() async {
    if (!_formKey.currentState!.validate()) return;

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

    try {
      final success = await widget.onSubmit(
        _nameController.text.trim(),
        _phoneController.text.trim(),
        _mobileController.text.trim(),
        _emailController.text.trim(),
        _passwordController.text.isNotEmpty ? _passwordController.text : null,
      );

      if (!success) {
        // 에러는 Controller에서 처리되므로 여기서는 로딩 상태만 해제
        setState(() {
          _isSubmitting = false;
        });
      }
    } catch (e) {
      setState(() {
        _isSubmitting = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return ShadDialog(
      title: Text(widget.title),
      actions: [
        ShadButton.outline(
          onPressed: _isSubmitting ? null : () => Navigator.of(context).pop(),
          child: const Text('취소'),
        ),
        ShadButton(
          onPressed: _isSubmitting ? null : _handleSubmit,
          child: _isSubmitting
              ? const SizedBox(
                  width: 16,
                  height: 16,
                  child: CircularProgressIndicator(strokeWidth: 2),
                )
              : Text(_isEditMode ? '수정' : '생성'),
        ),
      ],
      child: SizedBox(
        width: 500,
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 이름
              ShadInputFormField(
                controller: _nameController,
                label: const Text('이름'),
                validator: (value) {
                  if (value == null || value.trim().isEmpty) {
                    return '이름을 입력해주세요';
                  }
                  if (value.length > 100) {
                    return '이름은 100자 이내로 입력해주세요';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),

              // 이메일
              ShadInputFormField(
                controller: _emailController,
                label: const Text('이메일'),
                keyboardType: TextInputType.emailAddress,
                validator: (value) {
                  if (value == null || value.trim().isEmpty) {
                    return '이메일을 입력해주세요';
                  }
                  if (!RegExp(r'^[^\s@]+@[^\s@]+\.[^\s@]+$').hasMatch(value.trim())) {
                    return '유효한 이메일을 입력해주세요';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),

              // 전화번호
              ShadInputFormField(
                controller: _phoneController,
                label: const Text('전화번호'),
                keyboardType: TextInputType.phone,
                validator: (value) {
                  if (value == null || value.trim().isEmpty) {
                    return '전화번호를 입력해주세요';
                  }
                  final cleaned = value.replaceAll(RegExp(r'[\s\-\(\)]'), '');
                  if (!RegExp(r'^\d{8,11}$').hasMatch(cleaned)) {
                    return '유효한 전화번호를 입력해주세요 (8-11자리 숫자)';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),

              // 휴대폰
              ShadInputFormField(
                controller: _mobileController,
                label: const Text('휴대폰'),
                keyboardType: TextInputType.phone,
                validator: (value) {
                  if (value == null || value.trim().isEmpty) {
                    return '휴대폰 번호를 입력해주세요';
                  }
                  final cleaned = value.replaceAll(RegExp(r'[\s\-\(\)]'), '');
                  if (!RegExp(r'^\d{8,11}$').hasMatch(cleaned)) {
                    return '유효한 휴대폰 번호를 입력해주세요 (8-11자리 숫자)';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),

              // 비밀번호
              ShadInputFormField(
                controller: _passwordController,
                label: Text(_isEditMode ? '새 비밀번호 (선택사항)' : '비밀번호'),
                obscureText: true,
                validator: (value) {
                  // 수정 모드에서는 비밀번호 선택사항
                  if (_isEditMode && (value == null || value.isEmpty)) {
                    return null;
                  }
                  
                  // 생성 모드에서는 비밀번호 필수
                  if (!_isEditMode && (value == null || value.trim().isEmpty)) {
                    return '비밀번호를 입력해주세요';
                  }
                  
                  // 입력된 경우 길이 검증
                  if (value != null && value.isNotEmpty && value.length < 6) {
                    return '비밀번호는 최소 6자 이상이어야 합니다';
                  }
                  
                  return null;
                },
              ),
            ],
          ),
        ),
      ),
      
    );
  }
}
