import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import 'package:share_plus/share_plus.dart';

import '../../utils/url_utils.dart';

import '../../models/event_model.dart';
import '../../models/participant_model.dart';
import '../../models/score_model.dart';
import '../../models/team_model.dart';
import '../../services/event_service.dart';
import '../../services/notification_service.dart';
import '../../widgets/loading_indicator.dart';

// 뱃지 위젯 - 회원 유형, 참가자 상태, 결제 상태 등에 사용
class BadgeWidget extends StatelessWidget {
  final String text;
  final Color color;
  final IconData? icon;
  final EdgeInsets? margin;
  final bool outlined;

  const BadgeWidget({
    Key? key,
    required this.text,
    required this.color,
    this.icon,
    this.margin,
    this.outlined = true,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: margin ?? const EdgeInsets.only(right: 8),
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: outlined ? color.withOpacity(0.1) : color,
        borderRadius: BorderRadius.circular(8),
        border: outlined ? Border.all(color: color) : null,
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (icon != null) ...[  
            Icon(
              icon!,
              color: outlined ? color : Colors.white,
              size: 14,
            ),
            const SizedBox(width: 4),
          ],
          Text(
            text,
            style: TextStyle(
              color: outlined ? color : Colors.white,
              fontWeight: FontWeight.bold,
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }
}

class EventDetailsScreen extends StatefulWidget {
  final Event event;

  const EventDetailsScreen({
    Key? key,
    required this.event,
  }) : super(key: key);

  @override
  State<EventDetailsScreen> createState() => _EventDetailsScreenState();
}

class _EventDetailsScreenState extends State<EventDetailsScreen> with SingleTickerProviderStateMixin {
  // 공유 성공 스낵바 표시
  void _showShareSuccessSnackBar() {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('이벤트 정보가 공유되었습니다'),
        duration: Duration(seconds: 2),
      ),
    );
  }

  // 기본 정보만 공유
  void _shareBasicInfo(String title, String type, String date, String location) {
    final text = '[$type] $title\n날짜: $date\n장소: $location';
    Share.share(text);
    _showShareSuccessSnackBar();
  }
  
  // 참가 링크 포함 공유
  void _shareWithLink(String title, String type, String date, String location, String url) {
    final text = '[$type] $title\n날짜: $date\n장소: $location\n\n참가 링크: $url';
    Share.share(text);
    _showShareSuccessSnackBar();
  }
  
  // 상세 정보 포함 공유
  void _shareDetailedInfo(String title, String type, String date, String location, String gameCount, String fee, String url) {
    final text = '[$type] $title\n날짜: $date\n장소: $location\n게임 수: $gameCount\n참가비: ${fee}원\n참가자: ${_participants.length}명\n\n참가 링크: $url';
    Share.share(text);
    _showShareSuccessSnackBar();
  }

  // 이벤트 공유 기능
  void _shareEvent() {
    // 공유할 정보 준비
    final eventTitle = widget.event.title;
    final eventType = widget.event.type ?? '기타';
    final eventDate = DateFormat('yyyy년 MM월 dd일 HH:mm').format(widget.event.startDate);
    final eventLocation = widget.event.location?.isEmpty ?? true ? '장소 미정' : widget.event.location!;
    final gameCount = widget.event.gameCount?.toString() ?? '0';
    final participantFee = NumberFormat('#,###').format(widget.event.participantFee ?? 0);
    
    // 공유 URL - publicHash를 사용하여 URL 생성
    final shareUrl = widget.event.publicHash?.isNotEmpty ?? false 
        ? 'https://bowling.example.com/events/${widget.event.publicHash}' 
        : '';
    
    // 공유 옵션 다이얼로그 표시
    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (context) => Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            padding: const EdgeInsets.all(16),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: Colors.blue.shade50,
              borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
            ),
            child: Column(
              children: [
                Text(
                  '이벤트 공유',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: Colors.blue.shade800,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  '공유 방식을 선택하세요',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.blue.shade600,
                  ),
                ),
              ],
            ),
          ),
          ListTile(
            leading: const Icon(Icons.info_outline),
            title: const Text('기본 정보 공유'),
            subtitle: const Text('이벤트 제목, 유형, 날짜, 장소 정보를 공유합니다'),
            onTap: () {
              Navigator.pop(context);
              _shareBasicInfo(eventTitle, eventType, eventDate, eventLocation);
            },
          ),
          ListTile(
            leading: const Icon(Icons.link),
            title: const Text('참가 링크 포함 공유'),
            subtitle: const Text('기본 정보와 함께 참가 링크를 포함하여 공유합니다'),
            enabled: shareUrl.isNotEmpty,
            onTap: shareUrl.isNotEmpty ? () {
              Navigator.pop(context);
              _shareWithLink(eventTitle, eventType, eventDate, eventLocation, shareUrl);
            } : null,
          ),
          ListTile(
            leading: const Icon(Icons.info),
            title: const Text('상세 정보 포함 공유'),
            subtitle: const Text('기본 정보, 참가 링크, 게임 수, 참가비 등 상세 정보를 포함하여 공유합니다'),
            onTap: () {
              Navigator.pop(context);
              _shareDetailedInfo(eventTitle, eventType, eventDate, eventLocation, gameCount, participantFee, shareUrl);
            },
          ),
          const SizedBox(height: 16),
        ],
      ),
    );
  }

  // 정보 행 위젯
  Widget _buildInfoRow(IconData icon, String text, {bool isSelectable = false}) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(icon, size: 18, color: Colors.grey.shade700),
          const SizedBox(width: 8),
          Expanded(
            child: isSelectable
                ? SelectableText(
                    text,
                    style: TextStyle(color: Colors.grey.shade800),
                  )
                : Text(
                    text,
                    style: TextStyle(color: Colors.grey.shade800),
                  ),
          ),
        ],
      ),
    );
  }

  Widget _buildBadge({
    required String text,
    required Color color,
    IconData? icon,
    bool outlined = true,
    EdgeInsets? margin,
  }) {
    return BadgeWidget(
      text: text,
      color: color,
      icon: icon,
      outlined: outlined,
      margin: margin,
    );
  }

  Color _getParticipantStatusColor(String status) {
    return Colors.grey;
  }

  IconData _getParticipantStatusIcon(String status) {
    return Icons.person;
  }

  List<Participant> _getUnassignedParticipants() {
    return [];
  }

  // 공유 관련 메서드는 아래에 구현되어 있음

  // 스낵바 표시 함수
  void _showSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        duration: const Duration(seconds: 2),
      ),
    );
  }
  
  // 공유 성공 스낵바 표시
  void _showShareSuccessSnackBar() {
    _showSnackBar('이벤트 정보가 공유되었습니다');
  }
  
  // 클립보드에 복사 후 스낵바 표시
  void _copyToClipboard(String text, String message) {
    Clipboard.setData(ClipboardData(text: text));
    _showSnackBar(message);
  }
  
  void _editEvent() {}
  
  void _addParticipant() {}
  
  void _addScore() {}
  
  // 이벤트 알림 설정 기능
  Future<void> _setEventReminders() async {
    final notificationService = NotificationService();
    
    // 알림 권한 확인
    final hasPermission = await notificationService.requestPermission();
    
    if (!hasPermission) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('알림 권한이 없습니다. 설정에서 권한을 허용해주세요.')),
        );
      }
      return;
    }
    
    // 알림 설정 다이얼로그 표시
    if (!mounted) return;
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('이벤트 알림 설정'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.notifications_active),
              title: const Text('이벤트 시작 알림'),
              subtitle: Text('${DateFormat('yyyy-MM-dd HH:mm').format(widget.event.startDate)} 1시간 전'),
              onTap: () async {
                Navigator.of(context).pop();
                await notificationService.scheduleEventStartReminder(widget.event);
                
                if (mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('이벤트 시작 알림이 설정되었습니다')),
                  );
                }
              },
            ),
            if (widget.event.registrationDeadline != null) ListTile(
              leading: const Icon(Icons.timer),
              title: const Text('등록 마감 알림'),
              subtitle: Text('${DateFormat('yyyy-MM-dd HH:mm').format(widget.event.registrationDeadline!)} 1일 전'),
              onTap: () async {
                Navigator.of(context).pop();
                await notificationService.scheduleRegistrationDeadlineReminder(widget.event);
                
                if (mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('등록 마감 알림이 설정되었습니다')),
                  );
                }
              },
            ),
            ListTile(
              leading: const Icon(Icons.notifications_off),
              title: const Text('알림 취소'),
              subtitle: const Text('이 이벤트에 대한 모든 알림 취소'),
              onTap: () async {
                Navigator.of(context).pop();
                await notificationService.cancelEventNotifications(widget.event.id);
                
                if (mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('이벤트 알림이 취소되었습니다')),
                  );
                }
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('닫기'),
          ),
        ],
      ),
    );
  }
  
  void _generateTeams() {}
  
  Color _getEventTypeColor(String type) {
    switch (type.toLowerCase()) {
      case '개인전':
        return Colors.blue;
      case '팀전':
        return Colors.purple;
      case '리그':
        return Colors.teal;
      case '토너먼트':
        return Colors.deepOrange;
      case '친선전':
        return Colors.green;
      default:
        return Colors.blueGrey;
    }
  }
  
  Color _getEventStatusColor(String status) {
    switch (status.toLowerCase()) {
      case '예정':
        return Colors.blue;
      case '진행중':
        return Colors.green;
      case '완료':
        return Colors.purple;
      case '취소':
        return Colors.red;
      case '연기':
        return Colors.orange;
      default:
        return Colors.grey;
    }
  }
  
  void _editParticipant(Participant participant) {}
  
  void _removeParticipant(Participant participant) {}
  
  void _showParticipantDetails(Participant participant) {}
  
  Color _getRankColor(int rank) {
    return Colors.amber;
  }
  
  Color _getScoreColor(int score) {
    return Colors.black;
  }
  
  void _editScore(Score score) {}
  
  void _deleteScore(Score score) {}
  
  void _showScoreDetails(Score score) {}
  

  
  List<Participant> _filteredParticipants() {
    return [];
  }
  
  List<Participant> _sortedParticipants() {
    return [];
  }
  
  List<Score> sortScores(bool withHandicap) {
    return [];
  }
  
  List<Participant> _getTeamMembers(Team team) {
    return [];
  }
  
  double _calculateTeamAverage(Team team) {
    return 0.0;
  }
  
  void _saveTeams() {}
  
  void _removeFromTeam(Team team, Participant participant) {}
  
  void _showParticipantSelectionDialog(Team team) {}
  
  void _showTeamSelectionDialog(Participant participant) {}
  
  Widget _buildFilterChip({required String label, required VoidCallback onRemove}) {
    return const SizedBox();
  }
  late TabController _tabController;
  List<Participant> _participants = [];
  List<Score> _scores = [];
  List<Team> _teams = [];

  // 참가자 모델에 회원 유형 할당
  void _assignMemberTypes() {
    for (var participant in _participants) {
      // 실제 구현에서는 API에서 회원 유형 정보를 가져와야 함
      // 여기서는 임시로 회원 유형을 할당
      participant.memberType = _getRandomMemberType();
    }
  }
  
  // 임시: 랜덤 회원 유형 반환 (실제 구현에서는 API에서 가져와야 함)
  String _getRandomMemberType() {
    final types = ['정회원', '준회원', '게스트'];
    return types[DateTime.now().millisecond % 3];
  }
  
  // 회원 유형에 따른 색상 반환
  Color _getMemberTypeColor(String memberType) {
    switch (memberType.toLowerCase()) {
      case 'regular':
      case '정회원':
        return Colors.indigo;
      case 'associate':
      case '준회원':
        return Colors.amber.shade800;
      case 'guest':
      case '게스트':
        return Colors.teal;
      default:
        return Colors.grey;
    }
  }

  // 탭별 로딩 상태 관리
  bool _isInitialLoading = true; // 초기 로딩 상태
  final Map<int, bool> _tabLoadingStates = {0: false, 1: false, 2: false, 3: false};
  final Map<int, bool> _tabLoadedStates = {0: false, 1: false, 2: false, 3: false};

  int _teamGenerationMethod = 1; // 1: 팀 인원수로 나누기, 2: 팀 개수로 나누기
  final TextEditingController _teamSizeController = TextEditingController(text: '4');
  final TextEditingController _teamCountController = TextEditingController(text: '2');
  bool _showTeamTab = false;

  @override
  void initState() {
    super.initState();
    // 팀 탭 표시 여부에 따라 TabController 길이 설정
    _tabController = TabController(length: _showTeamTab ? 4 : 3, vsync: this);

    // 탭 선택 변경 리스너 추가
    _tabController.addListener(_handleTabChange);

    // 초기 기본 정보 탭 데이터 로드
    _loadBasicInfoData();
  }

  @override
  void dispose() {
    _tabController.removeListener(_handleTabChange);
    _tabController.dispose();
    _teamSizeController.dispose();
    _teamCountController.dispose();
    super.dispose();
  }

  // 탭 변경 시 호출되는 핸들러
  void _handleTabChange() {
    final currentTabIndex = _tabController.index;

    // 현재 탭이 아직 로드되지 않았다면 데이터 로드
    if (!_tabLoadedStates[currentTabIndex]!) {
      switch (currentTabIndex) {
        case 0:
          _loadBasicInfoData();
          break;
        case 1:
          _loadParticipantsData();
          break;
        case 2:
          _loadScoresData();
          break;
        case 3:
          if (_showTeamTab) {
            _loadTeamsData();
          }
          break;
      }
    }
  }

  // 기본 정보 탭 데이터 로드
  Future<void> _loadBasicInfoData() async {
    if (_tabLoadedStates[0]!) return; // 이미 로드된 경우 스킵

    setState(() {
      _isInitialLoading = true;
      _tabLoadingStates[0] = true;
    });

    try {
      // 기본 정보는 이미 widget.event에 있으므로 추가 API 호출 불필요
      // 팀 관련 정보만 확인
      final eventService = Provider.of<EventService>(context, listen: false);

      try {
        // 팀 탭 표시 여부 확인을 위해 팀 정보 간략히 조회
        final hasTeams = await eventService.hasEventTeams(widget.event.id);
        if (mounted) {
          setState(() {
            _showTeamTab = hasTeams || widget.event.type == '팀전';
            _tabLoadedStates[0] = true;
            _tabLoadingStates[0] = false;
            _isInitialLoading = false;
          });
        }
      } catch (e) {
        // 팀 정보 조회 실패 시 기본값 설정
        if (mounted) {
          setState(() {
            _showTeamTab = widget.event.type == '팀전';
            _tabLoadedStates[0] = true;
            _tabLoadingStates[0] = false;
            _isInitialLoading = false;
          });
        }
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _tabLoadedStates[0] = true; // 오류가 나도 로드 시도는 했으므로 표시
          _tabLoadingStates[0] = false;
          _isInitialLoading = false;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('기본 정보를 불러오는데 실패했습니다: $e')),
        );
      }
    }
  }

  // 참가자 탭 데이터 로드
  Future<void> _loadParticipantsData() async {
    if (_tabLoadedStates[1]!) return; // 이미 로드된 경우 스킵

    setState(() {
      _tabLoadingStates[1] = true;
    });

    try {
      final eventService = Provider.of<EventService>(context, listen: false);
      final participants = await eventService.fetchEventParticipants(widget.event.id);

      if (mounted) {
        setState(() {
          _participants = participants;
          _assignMemberTypes(); // 회원 유형 정보 추가
          _tabLoadedStates[1] = true;
          _tabLoadingStates[1] = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _tabLoadedStates[1] = true; // 오류가 나도 로드 시도는 했으므로 표시
          _tabLoadingStates[1] = false;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('참가자 정보를 불러오는데 실패했습니다: $e')),
        );
      }
    }
  }

  // 점수 탭 데이터 로드
  Future<void> _loadScoresData() async {
    if (_tabLoadedStates[2]!) return; // 이미 로드된 경우 스킵

    setState(() {
      _tabLoadingStates[2] = true;
    });

    try {
      final eventService = Provider.of<EventService>(context, listen: false);
      final scores = await eventService.fetchEventScores(widget.event.id);

      if (mounted) {
        setState(() {
          _scores = scores;
          _tabLoadedStates[2] = true;
          _tabLoadingStates[2] = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _tabLoadedStates[2] = true; // 오류가 나도 로드 시도는 했으므로 표시
          _tabLoadingStates[2] = false;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('점수 정보를 불러오는데 실패했습니다: $e')),
        );
      }
    }
  }

  // 팀 탭 데이터 로드
  Future<void> _loadTeamsData() async {
    if (_tabLoadedStates[3]! || !_showTeamTab) return; // 이미 로드된 경우 또는 팀 탭이 없는 경우 스킵

    setState(() {
      _tabLoadingStates[3] = true;
    });

    try {
      final eventService = Provider.of<EventService>(context, listen: false);
      final teams = await eventService.fetchEventTeams(widget.event.id);

      if (mounted) {
        setState(() {
          _teams = teams;
          _tabLoadedStates[3] = true;
          _tabLoadingStates[3] = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _tabLoadedStates[3] = true; // 오류가 나도 로드 시도는 했으므로 표시
          _tabLoadingStates[3] = false;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('팀 정보를 불러오는데 실패했습니다: $e')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.event.title),
        bottom: TabBar(
          controller: _tabController,
          tabs: [
            const Tab(text: '기본 정보'),
            const Tab(text: '참가자'),
            const Tab(text: '점수'),
            if (_showTeamTab) const Tab(text: '팀'),
          ],
        ),
      ),
      body: _isInitialLoading
          ? const LoadingIndicator()
          : TabBarView(
              controller: _tabController,
              children: [
                _buildTabContent(0, _buildBasicInfoTab),
                _buildTabContent(1, _buildParticipantsTab),
                _buildTabContent(2, _buildScoresTab),
                if (_showTeamTab) _buildTabContent(3, _buildTeamsTab),
              ],
            ),
      floatingActionButton: _buildFloatingActionButton(),
    );
  }

  // 탭 콘텐츠 빌더 - 로딩 상태 처리
  Widget _buildTabContent(int tabIndex, Widget Function() contentBuilder) {
    // 탭이 로딩 중이면 로딩 인디케이터 표시
    if (_tabLoadingStates[tabIndex]!) {
      return const Center(child: LoadingIndicator());
    }

    // 탭이 로드되지 않았다면 자동 로드 시도
    if (!_tabLoadedStates[tabIndex]!) {
      // 현재 탭이 활성화된 경우에만 자동 로드
      if (_tabController.index == tabIndex) {
        switch (tabIndex) {
          case 0:
            Future.microtask(() => _loadBasicInfoData());
            break;
          case 1:
            Future.microtask(() => _loadParticipantsData());
            break;
          case 2:
            Future.microtask(() => _loadScoresData());
            break;
          case 3:
            if (_showTeamTab) {
              Future.microtask(() => _loadTeamsData());
            }
            break;
        }
      }
      return const Center(child: LoadingIndicator());
    }

    // 로드가 완료된 경우 콘텐츠 빌드
    return contentBuilder();
  }

  Widget _buildFloatingActionButton() {
    final currentTab = _tabController.index;

    switch (currentTab) {
      case 0: // 기본 정보 탭
        return FloatingActionButton(
          onPressed: _editEvent,
          child: const Icon(Icons.edit),
        );
      case 1: // 참가자 탭
        return FloatingActionButton(
          onPressed: _addParticipant,
          child: const Icon(Icons.person_add),
        );
      case 2: // 점수 탭
        return FloatingActionButton(
          onPressed: _addScore,
          child: const Icon(Icons.add_chart),
        );
      case 3: // 팀 탭 (표시되는 경우)
        if (_showTeamTab) {
          return FloatingActionButton(
            onPressed: _generateTeams,
            child: const Icon(Icons.group_add),
          );
        }
        return Container();
      default:
        return Container();
    }
  }

  // 기본 정보 탭
  Widget _buildBasicInfoTab() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 이벤트 유형 및 상태 뱃지
          Row(
            children: [
              _buildBadge(
                text: widget.event.type ?? '기본',
                color: _getEventTypeColor(widget.event.type ?? '기본'),
                icon: Icons.event,
              ),
              const SizedBox(width: 8),
              _buildBadge(
                text: widget.event.status ?? '기본',
                color: _getEventStatusColor(widget.event.status ?? '기본'),
                icon: Icons.flag,
              ),
              const Spacer(),
              // 공유 버튼 추가
              IconButton(
                icon: const Icon(Icons.share),
                onPressed: () => _shareEvent(),
                tooltip: '이벤트 공유',
              ),
            ],
          ),
          const SizedBox(height: 16),

          // 이벤트 설명
          if (widget.event.description != null && widget.event.description!.isNotEmpty) ...[
            const Text(
              '설명',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 8),
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.grey[100],
                borderRadius: BorderRadius.circular(8),
              ),
              child: Text(widget.event.description ?? ''),
            ),
            const SizedBox(height: 16),
          ],

          // 이벤트 정보
          const Text(
            '이벤트 정보',
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 8),
          _buildInfoRow(
            Icons.calendar_today,
            '시작: ${DateFormat('yyyy-MM-dd HH:mm').format(widget.event.startDate)}',
          ),
          if (widget.event.endDate != null)
            _buildInfoRow(
              Icons.calendar_today,
              '종료: ${DateFormat('yyyy-MM-dd HH:mm').format(widget.event.endDate!)}',
            ),
          if (widget.event.location != null && widget.event.location!.isNotEmpty)
            _buildInfoRow(Icons.location_on, '장소: ${widget.event.location}'),
          if (widget.event.maxParticipants != null)
            _buildInfoRow(
              Icons.people,
              '최대 참가자: ${widget.event.maxParticipants}명',
            ),
          if (widget.event.gameCount != null)
            _buildInfoRow(
              Icons.sports,
              '게임 수: ${widget.event.gameCount}게임',
            ),
          if (widget.event.participantFee != null)
            _buildInfoRow(
              Icons.attach_money,
              '참가비: ${NumberFormat.currency(locale: 'ko_KR', symbol: '₩', decimalDigits: 0).format(widget.event.participantFee)}',
            ),
          if (widget.event.registrationDeadline != null)
            _buildInfoRow(
              Icons.timer,
              '신청마감: ${DateFormat('yyyy-MM-dd HH:mm').format(widget.event.registrationDeadline!)}',
            ),
          const SizedBox(height: 16),

          // 공개 접근 정보
          Row(
            children: [
              const Text(
                '공개 접근',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
              const SizedBox(width: 8),
              if (widget.event.publicHash != null && widget.event.publicHash!.isNotEmpty)
                Tooltip(
                  message: '이 이벤트는 공개 URL을 통해 접근할 수 있습니다',
                  child: const Icon(Icons.public, size: 18, color: Colors.blue),
                ),
              if (widget.event.accessPassword != null && widget.event.accessPassword!.isNotEmpty)
                Tooltip(
                  message: '이 이벤트는 비밀번호로 보호되어 있습니다',
                  child: const Icon(Icons.lock, size: 18, color: Colors.orange),
                ),
            ],
          ),
          const SizedBox(height: 12),
          if (widget.event.publicHash != null && widget.event.publicHash!.isNotEmpty) ...[
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.blue.withOpacity(0.05),
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.blue.withOpacity(0.3)),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      const Icon(Icons.link, size: 18, color: Colors.blue),
                      const SizedBox(width: 8),
                      const Text(
                        '공개 URL',
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                      const Spacer(),
                      ElevatedButton.icon(
                        onPressed: () {
                          final url = UrlUtils.getEventPublicUrl(widget.event.publicHash!);
                          _copyToClipboard(url, '공개 URL이 클립보드에 복사되었습니다');
                        },
                        icon: const Icon(Icons.copy, size: 16),
                        label: const Text('복사'),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.blue,
                          foregroundColor: Colors.white,
                          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 0),
                          minimumSize: const Size(0, 32),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 8),
                  SelectableText(
                    'https://bowling.example.com/events/${widget.event.publicHash}',
                    style: const TextStyle(color: Colors.blue),
                  ),
                  const SizedBox(height: 8),
                  const Text(
                    '이 URL을 공유하여 다른 사람들이 이벤트에 접근할 수 있도록 할 수 있습니다.',
                    style: TextStyle(fontSize: 12, color: Colors.grey),
                  ),
                ],
              ),
            ),
          ],
          const SizedBox(height: 12),
          if (widget.event.accessPassword != null && widget.event.accessPassword!.isNotEmpty) ...[
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.orange.withOpacity(0.05),
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.orange.withOpacity(0.3)),
              ),
              child: Row(
                children: [
                  const Icon(Icons.lock, size: 18, color: Colors.orange),
                  const SizedBox(width: 8),
                  const Text(
                    '접근 비밀번호: ',
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  Text(widget.event.accessPassword!),
                  const Spacer(),
                  IconButton(
                    icon: const Icon(Icons.copy, size: 18),
                    onPressed: () {
                      _copyToClipboard(widget.event.accessPassword!, '비밀번호가 클립보드에 복사되었습니다');
                    },
                    tooltip: '비밀번호 복사',
                    color: Colors.orange,
                    padding: EdgeInsets.zero,
                    constraints: const BoxConstraints(),
                  ),
                ],
              ),
            ),
          ],

          // 참가자 정보
          const SizedBox(height: 16),
          const Text(
            '참가자 정보',
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 8),
          _buildInfoRow(
            Icons.people,
            '현재 참가자: ${_participants.length}명',
          ),
        ],
      ),
    );
  }

  // 참가자 탭
  Widget _buildParticipantsTab() {
    // 필터링 및 정렬을 위한 상태 변수
    final TextEditingController _searchController = TextEditingController();
    String _searchQuery = '';
    String _filterStatus = '전체';
    String _filterPayment = '전체';
    String _filterMemberType = '전체';
    String _sortBy = '이름';
    bool _sortAscending = true;

    // 필터링된 참가자 목록
    List<Participant> _filteredParticipants() {
      return _participants.where((participant) {
        // 검색어 필터링
        final nameMatch = _searchQuery.isEmpty || 
            (participant.name?.toLowerCase().contains(_searchQuery.toLowerCase()) ?? false);
        
        // 상태 필터링
        final statusMatch = _filterStatus == '전체' || 
            participant.status == _filterStatus;
        
        // 결제 상태 필터링
        final paymentMatch = _filterPayment == '전체' || 
            (_filterPayment == '결제완료' && participant.isPaid) || 
            (_filterPayment == '미결제' && !participant.isPaid);
        
        // 회원 유형 필터링
        final memberTypeMatch = _filterMemberType == '전체' || 
            participant.memberType == _filterMemberType;
        
        return nameMatch && statusMatch && paymentMatch && memberTypeMatch;
      }).toList();
    }

    // 정렬된 참가자 목록
    List<Participant> _sortedParticipants() {
      final filtered = _filteredParticipants();
      
      switch (_sortBy) {
        case '이름':
          filtered.sort((a, b) => _sortAscending 
              ? (a.name ?? '').compareTo(b.name ?? '') 
              : (b.name ?? '').compareTo(a.name ?? ''));
          break;
        case '등록일':
          filtered.sort((a, b) => _sortAscending 
              ? (a.registeredAt ?? DateTime.now()).compareTo(b.registeredAt ?? DateTime.now()) 
              : (b.registeredAt ?? DateTime.now()).compareTo(a.registeredAt ?? DateTime.now()));
          break;
        case '상태':
          filtered.sort((a, b) => _sortAscending 
              ? (a.status ?? '').compareTo(b.status ?? '') 
              : (b.status ?? '').compareTo(a.status ?? ''));
          break;
      }
      
      return filtered;
    }

    // 참가자 상태 목록
    final statusOptions = ['전체', '확정', '대기', '취소'];
    final paymentOptions = ['전체', '결제완료', '미결제'];
    final memberTypeOptions = ['전체', '정회원', '준회원', '게스트'];
    final sortOptions = ['이름', '등록일', '상태'];

    if (_participants.isEmpty) {
      return const Center(
        child: Text('참가자가 없습니다.'),
      );
    }

    return StatefulBuilder(
      builder: (context, setState) {
        final displayedParticipants = _sortedParticipants();
        
        return Column(
          children: [
            // 검색 및 필터 영역
            Container(
              padding: const EdgeInsets.all(8),
              color: Colors.grey.shade50,
              child: Column(
                children: [
                  // 검색 필드
                  TextField(
                    controller: _searchController,
                    decoration: InputDecoration(
                      hintText: '참가자 검색',
                      prefixIcon: const Icon(Icons.search),
                      suffixIcon: _searchQuery.isNotEmpty 
                          ? IconButton(
                              icon: const Icon(Icons.clear),
                              onPressed: () {
                                _searchController.clear();
                                setState(() => _searchQuery = '');
                              },
                            )
                          : null,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                        borderSide: BorderSide(color: Colors.grey.shade300),
                      ),
                      contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 16),
                    ),
                    onChanged: (value) {
                      setState(() => _searchQuery = value);
                    },
                  ),
                  
                  const SizedBox(height: 8),
                  
                  // 필터 및 정렬 옵션
                  SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Row(
                      children: [
                        // 상태 필터
                        Container(
                          padding: const EdgeInsets.symmetric(horizontal: 8),
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.grey.shade300),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: DropdownButton<String>(
                            value: _filterStatus,
                            icon: const Icon(Icons.arrow_drop_down),
                            underline: Container(),
                            hint: const Text('상태'),
                            onChanged: (String? newValue) {
                              if (newValue != null) {
                                setState(() => _filterStatus = newValue);
                              }
                            },
                            items: statusOptions.map<DropdownMenuItem<String>>((String value) {
                              return DropdownMenuItem<String>(
                                value: value,
                                child: Text(value),
                              );
                            }).toList(),
                          ),
                        ),
                        
                        const SizedBox(width: 8),
                        
                        // 결제 상태 필터
                        Container(
                          padding: const EdgeInsets.symmetric(horizontal: 8),
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.grey.shade300),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: DropdownButton<String>(
                            value: _filterPayment,
                            icon: const Icon(Icons.arrow_drop_down),
                            underline: Container(),
                            hint: const Text('결제 상태'),
                            onChanged: (String? newValue) {
                              if (newValue != null) {
                                setState(() => _filterPayment = newValue);
                              }
                            },
                            items: paymentOptions.map<DropdownMenuItem<String>>((String value) {
                              return DropdownMenuItem<String>(
                                value: value,
                                child: Text(value),
                              );
                            }).toList(),
                          ),
                        ),
                        
                        const SizedBox(width: 8),
                        
                        // 회원 유형 필터
                        Container(
                          padding: const EdgeInsets.symmetric(horizontal: 8),
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.grey.shade300),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: DropdownButton<String>(
                            value: _filterMemberType,
                            icon: const Icon(Icons.arrow_drop_down),
                            underline: Container(),
                            hint: const Text('회원 유형'),
                            onChanged: (String? newValue) {
                              if (newValue != null) {
                                setState(() => _filterMemberType = newValue);
                              }
                            },
                            items: memberTypeOptions.map<DropdownMenuItem<String>>((String value) {
                              return DropdownMenuItem<String>(
                                value: value,
                                child: Text(value),
                              );
                            }).toList(),
                          ),
                        ),
                        
                        const SizedBox(width: 8),
                        
                        // 정렬 옵션
                        Container(
                          padding: const EdgeInsets.symmetric(horizontal: 8),
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.grey.shade300),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              DropdownButton<String>(
                                value: _sortBy,
                                icon: const Icon(Icons.arrow_drop_down),
                                underline: Container(),
                                hint: const Text('정렬'),
                                onChanged: (String? newValue) {
                                  if (newValue != null) {
                                    setState(() => _sortBy = newValue);
                                  }
                                },
                                items: sortOptions.map<DropdownMenuItem<String>>((String value) {
                                  return DropdownMenuItem<String>(
                                    value: value,
                                    child: Text(value),
                                  );
                                }).toList(),
                              ),
                              IconButton(
                                icon: Icon(_sortAscending ? Icons.arrow_upward : Icons.arrow_downward),
                                onPressed: () {
                                  setState(() => _sortAscending = !_sortAscending);
                                },
                                tooltip: _sortAscending ? '오름차순' : '내림차순',
                                padding: EdgeInsets.zero,
                                constraints: const BoxConstraints(),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  
                  // 필터 적용 상태 표시
                  if (_filterStatus != '전체' || _filterPayment != '전체' || _filterMemberType != '전체' || _searchQuery.isNotEmpty) ...[  
                    const SizedBox(height: 8),
                    Row(
                      children: [
                        const Text('필터: ', style: TextStyle(fontWeight: FontWeight.bold)),
                        if (_searchQuery.isNotEmpty)
                          _buildFilterChip(
                            label: '"$_searchQuery"',
                            onRemove: () {
                              _searchController.clear();
                              setState(() => _searchQuery = '');
                            },
                          ),
                        if (_filterStatus != '전체')
                          _buildFilterChip(
                            label: '상태: $_filterStatus',
                            onRemove: () => setState(() => _filterStatus = '전체'),
                          ),
                        if (_filterPayment != '전체')
                          _buildFilterChip(
                            label: '결제: $_filterPayment',
                            onRemove: () => setState(() => _filterPayment = '전체'),
                          ),
                        if (_filterMemberType != '전체')
                          _buildFilterChip(
                            label: '회원: $_filterMemberType',
                            onRemove: () => setState(() => _filterMemberType = '전체'),
                          ),
                        const Spacer(),
                        TextButton(
                          onPressed: () {
                            _searchController.clear();
                            setState(() {
                              _searchQuery = '';
                              _filterStatus = '전체';
                              _filterPayment = '전체';
                              _filterMemberType = '전체';
                            });
                          },
                          child: const Text('필터 초기화'),
                        ),
                      ],
                    ),
                  ],
                  
                  // 참가자 수 표시
                  Padding(
                    padding: const EdgeInsets.symmetric(vertical: 8),
                    child: Row(
                      children: [
                        Text(
                          '총 ${_participants.length}명 중 ${displayedParticipants.length}명 표시',
                          style: TextStyle(color: Colors.grey.shade700),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            
            // 참가자 목록
            Expanded(
              child: displayedParticipants.isEmpty
                  ? Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          const Icon(Icons.search_off, size: 48, color: Colors.grey),
                          const SizedBox(height: 16),
                          const Text('검색 결과가 없습니다.'),
                          const SizedBox(height: 8),
                          ElevatedButton(
                            onPressed: () {
                              _searchController.clear();
                              setState(() {
                                _searchQuery = '';
                                _filterStatus = '전체';
                                _filterPayment = '전체';
                                _filterMemberType = '전체';
                              });
                            },
                            child: const Text('필터 초기화'),
                          ),
                        ],
                      ),
                    )
                  : ListView.builder(
                      itemCount: displayedParticipants.length,
                      itemBuilder: (context, index) {
                        final participant = displayedParticipants[index];
                        
                        return Card(
                          margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                          elevation: 2,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                            side: BorderSide(color: Colors.grey.shade200),
                          ),
                          child: Padding(
                            padding: const EdgeInsets.all(8),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                // 참가자 기본 정보
                                ListTile(
                                  contentPadding: EdgeInsets.zero,
                                  leading: CircleAvatar(
                                    backgroundColor: Colors.blue.shade100,
                                    child: Text(
                                      participant.name?.substring(0, 1) ?? '?',
                                      style: const TextStyle(color: Colors.blue),
                                    ),
                                  ),
                                  title: Text(
                                    participant.name ?? '이름 없음',
                                    style: const TextStyle(fontWeight: FontWeight.bold),
                                  ),
                                  subtitle: participant.registeredAt != null
                                      ? Text(
                                          '등록일: ${DateFormat('yyyy-MM-dd').format(participant.registeredAt!)}',
                                          style: TextStyle(color: Colors.grey.shade600, fontSize: 12),
                                        )
                                      : null,
                                  trailing: Row(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      IconButton(
                                        icon: const Icon(Icons.edit, size: 20),
                                        tooltip: '참가자 정보 수정',
                                        onPressed: () => _editParticipant(participant),
                                      ),
                                      IconButton(
                                        icon: const Icon(Icons.delete, size: 20),
                                        tooltip: '참가자 삭제',
                                        onPressed: () => _removeParticipant(participant),
                                      ),
                                    ],
                                  ),
                                  onTap: () => _showParticipantDetails(participant),
                                ),
                                
                                // 뱃지 영역
                                Padding(
                                  padding: const EdgeInsets.only(left: 8, right: 8, bottom: 8),
                                  child: Wrap(
                                    spacing: 8,
                                    runSpacing: 8,
                                    children: [
                                      // 회원 유형 뱃지
                                      if (participant.memberType != null && participant.memberType!.isNotEmpty)
                                        _buildBadge(
                                          text: participant.memberType!,
                                          color: _getMemberTypeColor(participant.memberType!),
                                          icon: Icons.person,
                                        ),
                                      
                                      // 참가 상태 뱃지
                                      if (participant.status != null)
                                        _buildBadge(
                                          text: participant.status!,
                                          color: _getParticipantStatusColor(participant.status!),
                                          icon: _getParticipantStatusIcon(participant.status!),
                                        ),
                                      
                                      // 결제 상태 뱃지
                                      Row(
                                        children: [
                                          Expanded(
                                            child: _buildInfoRow(
                                              Icons.password,
                                              participant.isPaid ? '결제완료' : '미결제',
                                              isSelectable: true,
                                            ),
                                          ),
                                          if (participant.isPaid)
                                            IconButton(
                                              icon: const Icon(Icons.copy, size: 20),
                                              onPressed: () => _copyToClipboard(
                                                participant.isPaid ? '결제완료' : '미결제',
                                                '결제 상태가 클립보드에 복사되었습니다',
                                              ),
                                              tooltip: '클립보드에 복사',
                                            ),
                                        ],
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
            ),
          ],
        );
      },
    );
  }
  
  // 필터 칩 위젯
  Widget _buildFilterChip({required String label, required VoidCallback onRemove}) {
    return Container(
      margin: const EdgeInsets.only(right: 8),
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: Colors.blue.shade50,
        borderRadius: BorderRadius.circular(16),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(label, style: TextStyle(fontSize: 12, color: Colors.blue.shade800)),
          const SizedBox(width: 4),
          InkWell(
            onTap: onRemove,
            child: Icon(Icons.close, size: 14, color: Colors.blue.shade800),
          ),
        ],
      ),
    );
  }

  // 점수 탭
  Widget _buildScoresTab() {
    if (_scores.isEmpty) {
      return const Center(
        child: Text('등록된 점수가 없습니다.'),
      );
    }

    // 핸디캡 포함 점수 표시 여부
    bool _showWithHandicap = false;
    
    // 점수를 내림차순으로 정렬하여 순위 계산
    final sortedScores = List<Score>.from(_scores);
    
    // 점수 순위 계산을 위한 맵 (동점자 처리를 위해)
    final Map<String, int> scoreRanks = {};
    
    // 핸디캡 포함 점수로 정렬하는 함수
    void sortScores(bool withHandicap) {
      if (withHandicap) {
        sortedScores.sort((a, b) => b.totalWithHandicap.compareTo(a.totalWithHandicap));
      } else {
        sortedScores.sort((a, b) => b.totalScore.compareTo(a.totalScore));
      }
      
      // 동점자 처리를 위한 순위 계산
      scoreRanks.clear();
      int rank = 1;
      int count = 0;
      int sameRankCount = 0;
      int prevScore = -1;
      
      for (int i = 0; i < sortedScores.length; i++) {
        final score = sortedScores[i];
        final currentScore = withHandicap ? score.totalWithHandicap : score.totalScore;
        
        // 이전 점수와 비교하여 동점자 처리
        if (i > 0 && currentScore == prevScore) {
          // 동점자는 이전 순위와 같은 순위 부여
          scoreRanks[score.id] = rank - sameRankCount;
          sameRankCount++;
        } else {
          // 새로운 점수는 현재까지의 카운트 + 1을 순위로 부여
          rank = count + 1;
          scoreRanks[score.id] = rank;
          sameRankCount = 1;
        }
        
        prevScore = currentScore;
        count++;
      }
    }
    
    // 초기 정렬
    sortScores(false);

    // 평균 점수 계산
    final totalScoreSum = sortedScores.fold<int>(0, (sum, score) => sum + score.totalScore);
    final averageScore = sortedScores.isNotEmpty ? totalScoreSum / sortedScores.length : 0;
    
    // 평균 핸디캡 계산
    final handicapScores = sortedScores.where((score) => score.handicap != null).toList();
    final totalHandicapSum = handicapScores.fold<int>(0, (sum, score) => sum + (score.handicap ?? 0));
    final averageHandicap = handicapScores.isNotEmpty ? totalHandicapSum / handicapScores.length : 0;

    return StatefulBuilder(
      builder: (context, setState) {
        return Column(
          children: [
            // 평균 점수 표시
            Container(
              padding: const EdgeInsets.all(8),
              margin: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: Colors.blue.shade50,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.blue.shade200),
              ),
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const Icon(Icons.score, color: Colors.blue),
                      const SizedBox(width: 8),
                      Text(
                        '평균 점수: ${averageScore.toStringAsFixed(1)}',
                        style: const TextStyle(fontWeight: FontWeight.bold),
                      ),
                    ],
                  ),
                  if (handicapScores.isNotEmpty) ...[  
                    const SizedBox(height: 4),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        const Icon(Icons.add_circle_outline, color: Colors.green),
                        const SizedBox(width: 8),
                        Text(
                          '평균 핸디캡: ${averageHandicap.toStringAsFixed(1)}',
                          style: const TextStyle(fontWeight: FontWeight.bold),
                        ),
                      ],
                    ),
                  ],
                ],
              ),
            ),
            
            // 핸디캡 포함 점수 표시 옵션
            if (handicapScores.isNotEmpty)
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16.0),
                child: Row(
                  children: [
                    const Text('핸디캡 포함 점수 표시'),
                    const Spacer(),
                    Switch(
                      value: _showWithHandicap,
                      onChanged: (value) {
                        setState(() {
                          _showWithHandicap = value;
                          sortScores(value);
                        });
                      },
                    ),
                  ],
                ),
              ),
            

        // 점수 목록
        Expanded(
          child: ListView.builder(
            itemCount: sortedScores.length,
            itemBuilder: (context, index) {
              final score = sortedScores[index];
              // 동점자 처리가 적용된 순위 사용
              final rank = scoreRanks[score.id] ?? (index + 1);

              // 참가자 이름 찾기
              final participant = _participants.firstWhere(
                (p) => p.memberId == score.memberId,
                orElse: () => Participant(
                  id: '',
                  eventId: '',
                  memberId: score.memberId,
                  name: '알 수 없음',
                ),
              );

              return Card(
                margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                child: ListTile(
                  leading: CircleAvatar(
                    backgroundColor: _getRankColor(rank),
                    child: Text(
                      rank.toString(),
                      style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
                    ),
                  ),
                  title: Row(
                    children: [
                      Expanded(
                        child: Text(
                          participant.name ?? '알 수 없음',
                          style: const TextStyle(fontWeight: FontWeight.bold),
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                        decoration: BoxDecoration(
                          color: Colors.blue.shade100,
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Text(
                          _showWithHandicap && score.handicap != null
                              ? '총점: ${score.totalWithHandicap} (⬆${score.handicap})'
                              : '총점: ${score.totalScore}',
                          style: const TextStyle(fontWeight: FontWeight.bold),
                        ),
                      ),
                    ],
                  ),
                  subtitle: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const SizedBox(height: 4),
                      Text(
                        '날짜: ${DateFormat('yyyy-MM-dd').format(score.date)}',
                      ),
                      const SizedBox(height: 4),
                      SingleChildScrollView(
                        scrollDirection: Axis.horizontal,
                        child: Row(
                          children: score.frames.asMap().entries.map((entry) {
                            return Container(
                              width: 30,
                              height: 30,
                              margin: const EdgeInsets.only(right: 4),
                              decoration: BoxDecoration(
                                color: _getScoreColor(entry.value),
                                borderRadius: BorderRadius.circular(4),
                              ),
                              child: Center(
                                child: Text(
                                  entry.value.toString(),
                                  style: const TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                            );
                          }).toList(),
                        ),
                      ),
                    ],
                  ),
                  trailing: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      IconButton(
                        icon: const Icon(Icons.edit, size: 20),
                        tooltip: '점수 수정',
                        onPressed: () => _editScore(score),
                      ),
                      IconButton(
                        icon: const Icon(Icons.delete, size: 20),
                        tooltip: '점수 삭제',
                        onPressed: () => _deleteScore(score),
                      ),
                    ],
                  ),
                  onTap: () => _showScoreDetails(score),
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  // 팀 탭
  Widget _buildTeamsTab() {
    if (_teams.isEmpty) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Icon(Icons.groups, size: 64, color: Colors.blue),
              const SizedBox(height: 16),
              const Text('생성된 팀이 없습니다.', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
              const SizedBox(height: 24),
              // 팀 생성 옵션
              Card(
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text('팀 생성 옵션', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                      const SizedBox(height: 16),
                      // 팀 생성 방법 선택
                      Row(
                        children: [
                          Radio<int>(
                            value: 1,
                            groupValue: _teamGenerationMethod,
                            onChanged: (value) {
                              setState(() {
                                _teamGenerationMethod = value!;
                              });
                            },
                          ),
                          const Text('팀 인원수로 나누기'),
                        ],
                      ),
                      if (_teamGenerationMethod == 1)
                        Padding(
                          padding: const EdgeInsets.only(left: 32.0),
                          child: Row(
                            children: [
                              SizedBox(
                                width: 80,
                                child: TextFormField(
                                  controller: _teamSizeController,
                                  decoration: const InputDecoration(
                                    labelText: '인원수',
                                    suffixText: '명',
                                  ),
                                  keyboardType: TextInputType.number,
                                  inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                                ),
                              ),
                              const SizedBox(width: 16),
                              Text('총 ${_participants.length}명 참가자'),
                            ],
                          ),
                        ),
                      const SizedBox(height: 8),
                      Row(
                        children: [
                          Radio<int>(
                            value: 2,
                            groupValue: _teamGenerationMethod,
                            onChanged: (value) {
                              setState(() {
                                _teamGenerationMethod = value!;
                              });
                            },
                          ),
                          const Text('팀 개수로 나누기'),
                        ],
                      ),
                      if (_teamGenerationMethod == 2)
                        Padding(
                          padding: const EdgeInsets.only(left: 32.0),
                          child: Row(
                            children: [
                              SizedBox(
                                width: 80,
                                child: TextFormField(
                                  controller: _teamCountController,
                                  decoration: const InputDecoration(
                                    labelText: '팀 수',
                                    suffixText: '개',
                                  ),
                                  keyboardType: TextInputType.number,
                                  inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                                ),
                              ),
                              const SizedBox(width: 16),
                              Text('총 ${_participants.length}명 참가자'),
                            ],
                          ),
                        ),
                      const SizedBox(height: 16),
                      // 팀 생성 버튼
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          ElevatedButton.icon(
                            onPressed: _generateTeams,
                            icon: const Icon(Icons.group_add),
                            label: const Text('팀 생성하기'),
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.blue,
                              foregroundColor: Colors.white,
                              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      );
    }

    // 미배정 참가자 목록 조회
    final List<Participant> unassignedParticipants = _getUnassignedParticipants();

    return Column(
      children: [
        // 팀 관리 버튼
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              ElevatedButton.icon(
                onPressed: _generateTeams,
                icon: const Icon(Icons.refresh),
                label: const Text('팀 재생성'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.blue,
                  foregroundColor: Colors.white,
                ),
              ),
              ElevatedButton.icon(
                onPressed: _saveTeams,
                icon: const Icon(Icons.save),
                label: const Text('팀 저장'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.green,
                  foregroundColor: Colors.white,
                ),
              ),
            ],
          ),
        ),

        // 이벤트 설명
        if (widget.event.description != null && widget.event.description!.isNotEmpty)
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '이벤트 설명',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 8),
                Text(widget.event.description!),
              ],
            ),
          ),

        // 버튼 그룹 (공유 및 알림)
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 16.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              // 공유 버튼
              Expanded(
                child: ElevatedButton.icon(
                  onPressed: () => _shareEvent(),
                  icon: const Icon(Icons.share),
                  label: const Text('이벤트 공유'),
                  style: ElevatedButton.styleFrom(
                    foregroundColor: Colors.white,
                    backgroundColor: Colors.blue,
                  ),
                ),
              ),
              const SizedBox(width: 8),
              // 알림 설정 버튼
              Expanded(
                child: ElevatedButton.icon(
                  onPressed: _setEventReminders,
                  icon: const Icon(Icons.notifications_active),
                  label: const Text('알림 설정'),
                  style: ElevatedButton.styleFrom(
                    foregroundColor: Colors.white,
                    backgroundColor: Colors.green,
                  ),
                ),
              ),
            ],
          ),
        ),

        // 미배정 참가자 섹션
        if (unassignedParticipants.isNotEmpty)
          Card(
            margin: const EdgeInsets.all(8),
            color: Colors.amber.shade50,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Row(
                    children: [
                      const Icon(Icons.person_off, color: Colors.amber),
                      const SizedBox(width: 8),
                      Text('미배정 참가자 (${unassignedParticipants.length}명)',
                          style: const TextStyle(fontWeight: FontWeight.bold)),
                    ],
                  ),
                ),
                const Divider(height: 1),
                Wrap(
                  children: unassignedParticipants.map((participant) {
                    return Padding(
                      padding: const EdgeInsets.all(4.0),
                      child: Chip(
                        avatar: const CircleAvatar(
                          child: Icon(Icons.person, size: 16),
                        ),
                        label: Text(participant.name ?? '알 수 없음'),
                        deleteIcon: const Icon(Icons.add_circle, size: 18),
                        onDeleted: () => _showTeamSelectionDialog(participant),
                      ),
                    );
                  }).toList(),
                ),
              ],
            ),
          ),

        // 팀 목록
        Expanded(
          child: ListView.builder(
            itemCount: _teams.length,
            itemBuilder: (context, index) {
              final team = _teams[index];
              final teamMembers = _getTeamMembers(team);
              final teamAverage = _calculateTeamAverage(team);

              return Card(
                margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                child: ExpansionTile(
                  leading: CircleAvatar(
                    backgroundColor: Colors.blue.shade700,
                    child: Text('${index + 1}', style: const TextStyle(color: Colors.white)),
                  ),
                  title: Row(
                    children: [
                      Text('팀 ${team.name}', style: const TextStyle(fontWeight: FontWeight.bold)),
                      const SizedBox(width: 8),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                        decoration: BoxDecoration(
                          color: Colors.blue.shade100,
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Text('${team.memberIds.length}명'),
                      ),
                    ],
                  ),
                  subtitle: Row(
                    children: [
                      const Icon(Icons.bar_chart, size: 16, color: Colors.blue),
                      const SizedBox(width: 4),
                      Text('팀 에버리지: ${teamAverage.toStringAsFixed(1)}'),
                    ],
                  ),
                  children: [
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                      child: Row(
                        children: [
                          const Icon(Icons.info_outline, size: 16, color: Colors.blue),
                          const SizedBox(width: 8),
                          const Text('팀원을 드래그하여 순서를 변경할 수 있습니다', style: TextStyle(fontSize: 12, color: Colors.blue)),
                        ],
                      ),
                    ),
                    ReorderableListView(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      onReorder: (oldIndex, newIndex) {
                        setState(() {
                          if (oldIndex < newIndex) {
                            newIndex -= 1;
                          }
                          final participant = teamMembers.removeAt(oldIndex);
                          teamMembers.insert(newIndex, participant);
                          
                          // 팀 모델의 memberIds 순서 업데이트
                          final updatedMemberIds = teamMembers.map((p) => p.id).toList();
                          final teamIndex = _teams.indexWhere((t) => t.id == team.id);
                          if (teamIndex != -1) {
                            _teams[teamIndex] = Team(
                              id: team.id,
                              eventId: team.eventId,
                              name: team.name,
                              memberIds: updatedMemberIds,
                              description: team.description,
                              createdAt: team.createdAt,
                              updatedAt: DateTime.now(),
                            );
                          }
                        });
                      },
                      children: teamMembers.map((participant) {
                        // 참가자의 평균 점수 계산
                        final participantScores = _scores.where((s) => s.memberId == participant.memberId).toList();
                        final participantAverage = participantScores.isNotEmpty
                            ? participantScores.fold<int>(0, (sum, s) => sum + s.totalScore) / participantScores.length
                            : 0.0;

                        return ListTile(
                          key: Key(participant.id),
                          leading: const CircleAvatar(
                            child: Icon(Icons.person, size: 16),
                          ),
                          title: Text(participant.name ?? '알 수 없음'),
                          subtitle: Text('평균: ${participantAverage.toStringAsFixed(1)}'),
                          trailing: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              const Icon(Icons.drag_handle, color: Colors.grey),
                              const SizedBox(width: 8),
                              IconButton(
                                icon: const Icon(Icons.remove_circle, color: Colors.red),
                                tooltip: '팀에서 제외',
                                onPressed: () => _removeFromTeam(team, participant),
                              ),
                            ],
                          ),
                        );
                      }).toList(),
                    ),
                    // 팀원 추가 버튼
                    if (unassignedParticipants.isNotEmpty)
                      ListTile(
                        leading: const Icon(Icons.add_circle, color: Colors.green),
                        title: const Text('팀원 추가하기'),
                        onTap: () => _showParticipantSelectionDialog(team),
                      ),
                  ],
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  // 정보 행 위젯
  Widget _buildInfoRow(IconData icon, String text, {bool isSelectable = false}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        children: [
          Icon(icon, color: Colors.blue),
          const SizedBox(width: 8),
          isSelectable
              ? Expanded(
                  child: SelectableText(
                    text,
                    style: const TextStyle(fontSize: 16),
                  ),
                )
              : Expanded(
                  child: Text(
                    text,
                    style: const TextStyle(fontSize: 16),
                  ),
                ),
        ],
      ),
    );
  }

  // 뱃지 위젯 빌더 메서드
  Widget _buildBadge({
    required String text,
    required Color color,
    IconData? icon,
    bool outlined = true,
    EdgeInsets? margin,
  }) {
    return BadgeWidget(
      text: text,
      color: color,
      icon: icon,
      outlined: outlined,
      margin: margin,
    );
  }

  // 이벤트 유형에 따른 색상 반환
  Color _getEventTypeColor(String type) {
    switch (type.toLowerCase()) {
      case '개인전':
      case 'individual':
        return Colors.blue;
      case '팀전':
      case 'team':
        return Colors.purple;
      case '리그':
      case 'league':
        return Colors.green;
      case '토너먼트':
      case 'tournament':
        return Colors.orange;
      default:
        return Colors.grey;
    }
  }

  // 이벤트 상태에 따른 색상 반환
  Color _getEventStatusColor(String status) {
    switch (status.toLowerCase()) {
      case 'draft':
      case '초안':
        return Colors.grey;
      case 'published':
      case '공개됨':
        return Colors.blue;
      case 'in_progress':
      case '진행중':
        return Colors.green;
      case 'completed':
      case '완료됨':
        return Colors.purple;
      case 'cancelled':
      case '취소됨':
        return Colors.red;
      default:
        return Colors.grey;
    }
  }

  // 참가자 상태에 따른 색상 반환
  Color _getParticipantStatusColor(String status) {
    switch (status.toLowerCase()) {
      case 'registered':
      case '등록됨':
        return Colors.blue;
      case 'confirmed':
      case '확인됨':
        return Colors.green;
      case 'cancelled':
      case '취소됨':
        return Colors.red;
      default:
        return Colors.grey;
    }
  }

  // 참가자 상태에 따른 아이콘 반환
  IconData _getParticipantStatusIcon(String status) {
    switch (status.toLowerCase()) {
      case 'registered':
      case '등록됨':
        return Icons.how_to_reg;
      case 'confirmed':
      case '확인됨':
        return Icons.verified;
      case 'cancelled':
      case '취소됨':
        return Icons.cancel;
      default:
        return Icons.help_outline;
    }
  }

  // 순위에 따른 색상 반환
  Color _getRankColor(int rank) {
    switch (rank) {
      case 1:
        return Colors.amber.shade700; // 금메달
      case 2:
        return Colors.blueGrey.shade400; // 은메달
      case 3:
        return Colors.brown.shade400; // 동메달
      default:
        return Colors.blue.shade700; // 기본 색상
    }
  }

  // 점수에 따른 색상 반환
  Color _getScoreColor(int score) {
    if (score >= 9) {
      return Colors.red.shade700; // 스트라이크
    } 
    if (score >= 7) {
      return Colors.orange.shade700; // 좋은 점수
    } 
    if (score >= 5) {
      return Colors.green.shade700; // 평균 점수
    } 
    // 낮은 점수
    return Colors.blue.shade700;
  }

  // 미배정 참가자 목록 가져오기
  List<Participant> _getUnassignedParticipants() {
    if (_participants.isEmpty || _teams.isEmpty) {
      return _participants;
    }

    // 현재 팀에 배정된 모든 참가자 ID 목록
    final List<String> assignedMemberIds = [];
    for (final team in _teams) {
      assignedMemberIds.addAll(team.memberIds);
    }

    // 미배정 참가자만 필터링
    return _participants.where((p) => p.memberId != null && !assignedMemberIds.contains(p.memberId)).toList();
  }

  // 팀원 목록 가져오기
  List<Participant> _getTeamMembers(Team team) {
    return _participants
        .where((p) => p.memberId != null && team.memberIds.contains(p.memberId))
        .toList();
  }

  // 팀 평균 점수 계산
  double _calculateTeamAverage(Team team, {bool withHandicap = false}) {
    if (team.memberIds.isEmpty) return 0.0;

    double totalAverage = 0.0;
    int memberCount = 0;

    for (final memberId in team.memberIds) {
      final memberScores = _scores.where((s) => s.memberId == memberId).toList();
      if (memberScores.isNotEmpty) {
        final memberTotal = memberScores.fold<int>(0, (int sum, score) {
          return sum + (withHandicap ? score.totalWithHandicap : score.totalScore);
        });
        totalAverage += memberTotal / memberScores.length;
        memberCount++;
      }
    }

    return memberCount > 0 ? totalAverage / memberCount : 0.0;
  }
  
  // 팀 핸디캡 계산
  int _calculateTeamHandicap(Team team) {
    if (team.memberIds.isEmpty) return 0;
    
    int totalHandicap = 0;
    int memberCount = 0;
    
    for (final memberId in team.memberIds) {
      final memberScores = _scores.where((s) => s.memberId == memberId).toList();
      if (memberScores.isNotEmpty) {
        final memberHandicap = memberScores.fold<int>(0, (sum, score) => sum + (score.handicap ?? 0)) ~/ memberScores.length;
        totalHandicap += memberHandicap;
        memberCount++;
      }
    }
    
    return memberCount > 0 ? (totalHandicap ~/ memberCount) : 0;
  }

  // 팀 생성 방법
  void _generateTeams() {
    if (_participants.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('참가자가 없습니다.')),
      );
      return;
    }

    // 기존 팀 삭제
    setState(() {
      _teams.clear();
    });

    // 참가자 셔플
    final shuffledParticipants = List<Participant>.from(_participants);
    shuffledParticipants.shuffle();

    int teamCount;
    int teamSize;

    // 팀 생성 방법에 따른 팀 개수 계산
    if (_teamGenerationMethod == 1) {
      // 팀 인원수로 나누기
      teamSize = int.tryParse(_teamSizeController.text) ?? 4;
      if (teamSize <= 0) teamSize = 4;
      teamCount = (_participants.length / teamSize).ceil();
    } else {
      // 팀 개수로 나누기
      teamCount = int.tryParse(_teamCountController.text) ?? 2;
      if (teamCount <= 0) teamCount = 2;
      teamSize = (_participants.length / teamCount).ceil();
    }
    
    // 팀 생성
    final List<Team> newTeams = [];
    for (int i = 0; i < teamCount; i++) {
      final teamName = String.fromCharCode(65 + i); // A, B, C, ...
      final team = Team(
        id: 'temp_${DateTime.now().millisecondsSinceEpoch}_$i',
        eventId: widget.event.id,
        name: teamName,
        memberIds: [],
      );
      newTeams.add(team);
    }
    
    // 참가자 배정
    for (int i = 0; i < shuffledParticipants.length; i++) {
      final teamIndex = i % teamCount;
      final participant = shuffledParticipants[i];
      if (participant.memberId != null) {
        newTeams[teamIndex].memberIds.add(participant.memberId);
      }
    }
    
    setState(() {
      _teams = newTeams;
    });
    
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('팀이 생성되었습니다. ($teamCount개 팀)')),
    );
  }
  
  // 팀 저장
  void _saveTeams() async {
    if (_teams.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('저장할 팀이 없습니다.')),
      );
      return;
    }
    
    setState(() {
      _tabLoadingStates[3] = true;
    });
    
    try {
      // 기존 팀 삭제 및 새 팀 저장 로직 구현
      // TODO: API 연동 구현
      
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('팀이 저장되었습니다.')),
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('팀 저장 중 오류가 발생했습니다: $e')),
      );
    } finally {
      setState(() {
        _tabLoadingStates[3] = false;
      });
    }
  }
  
  // 팀에서 참가자 제거
  void _removeFromTeam(Team team, Participant participant) {
    setState(() {
      team.memberIds.remove(participant.memberId);
    });
    
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('${participant.name}님이 팀에서 제외되었습니다.')),
    );
  }
  
  // 참가자 선택 다이얼로그 표시
  void _showParticipantSelectionDialog(Team team) {
    final unassignedParticipants = _getUnassignedParticipants();
    if (unassignedParticipants.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('추가할 참가자가 없습니다.')),
      );
      return;
    }
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('팀 ${team.name}에 참가자 추가'),
        content: SizedBox(
          width: double.maxFinite,
          child: ListView.builder(
            shrinkWrap: true,
            itemCount: unassignedParticipants.length,
            itemBuilder: (context, index) {
              final participant = unassignedParticipants[index];
              return ListTile(
                leading: const CircleAvatar(
                  child: Icon(Icons.person, size: 16),
                ),
                title: Text(participant.name ?? '알 수 없음'),
                onTap: () {
                  Navigator.of(context).pop();
                  if (participant.memberId != null) {
                    setState(() {
                      team.memberIds.add(participant.memberId);
                    });
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('${participant.name}님이 팀 ${team.name}에 추가되었습니다.')),
                    );
                  }
                },
              );
            },
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('취소'),
          ),
        ],
      ),
    );
  }
  
  // 참가자를 추가할 팀 선택 다이얼로그 표시
  void _showTeamSelectionDialog(Participant participant) {
    if (_teams.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('추가할 팀이 없습니다.')),
      );
      return;
    }
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('${participant.name}님을 추가할 팀 선택'),
        content: SizedBox(
          width: double.maxFinite,
          child: ListView.builder(
            shrinkWrap: true,
            itemCount: _teams.length,
            itemBuilder: (context, index) {
              final team = _teams[index];
              return ListTile(
                leading: CircleAvatar(
                  backgroundColor: Colors.blue.shade700,
                  child: Text('${index + 1}', style: const TextStyle(color: Colors.white)),
                ),
                title: Text('팀 ${team.name} (${team.memberIds.length}명)'),
                onTap: () {
                  Navigator.of(context).pop();
                  if (participant.memberId != null) {
                    setState(() {
                      team.memberIds.add(participant.memberId);
                    });
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('${participant.name}님이 팀 ${team.name}에 추가되었습니다.')),
                    );
                  }
                },
              );
            },
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('취소'),
          ),
        ],
      ),
    );
  }

  // 이벤트 수정
  void _editEvent() {
    // 이벤트 수정 다이얼로그 또는 화면으로 이동
    Navigator.of(context).pop(true); // 수정을 위해 이전 화면으로 돌아가기
  }

  // 참가자 추가
  void _addParticipant() {
    // 참가자 추가 다이얼로그 표시
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('참가자 추가'),
        content: const Text('참가자 추가 기능은 아직 구현 중입니다.'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('확인'),
          ),
        ],
      ),
    );
  }

  // 참가자 수정
  void _editParticipant(Participant participant) {
    // 참가자 수정 다이얼로그 표시
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('참가자 수정'),
        content: Text('${participant.name} 참가자 수정 기능은 아직 구현 중입니다.'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('확인'),
          ),
        ],
      ),
    );
  }

  // 참가자 삭제
  void _removeParticipant(Participant participant) {
    // 참가자 삭제 확인 다이얼로그
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('참가자 삭제'),
        content: Text('${participant.name} 참가자를 정말 삭제하시겠습니까?'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('취소'),
          ),
          TextButton(
            onPressed: () async {
              Navigator.of(context).pop();
              
              setState(() {
                _tabLoadingStates[1] = true;
              });
              
              try {
                final eventService = Provider.of<EventService>(context, listen: false);
                await eventService.removeParticipant(widget.event.id, participant.id);
                
                if (mounted) {
                  setState(() {
                    _participants.removeWhere((p) => p.id == participant.id);
                    _tabLoadingStates[1] = false;
                  });
                  
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('참가자가 삭제되었습니다')),
                  );
                }
              } catch (e) {
                if (mounted) {
                  setState(() {
                    _tabLoadingStates[1] = false;
                  });
                  
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('참가자 삭제에 실패했습니다: $e')),
                  );
                }
              }
            },
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('삭제'),
          ),
        ],
      ),
    );
  }

  // 참가자 상세 정보 표시
  void _showParticipantDetails(Participant participant) {
    // 참가자 상세 정보 다이얼로그
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(participant.name ?? '이름 없음'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (participant.email != null)
              _buildInfoRow(Icons.email, participant.email!),
            if (participant.phoneNumber != null)
              _buildInfoRow(Icons.phone, participant.phoneNumber!),
            
            // 회원 유형 표시
            if (participant.memberType != null && participant.memberType!.isNotEmpty)
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 8.0),
                child: Row(
                  children: [
                    const Icon(Icons.person, size: 20, color: Colors.grey),
                    const SizedBox(width: 8),
                    const Text('회원 유형: ', style: TextStyle(fontWeight: FontWeight.bold)),
                    _buildBadge(
                      text: participant.memberType!,
                      color: _getMemberTypeColor(participant.memberType!),
                      icon: Icons.person,
                    ),
                  ],
                ),
              ),
            
            // 참가 상태 표시
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 8.0),
              child: Row(
                children: [
                  const Icon(Icons.info, size: 20, color: Colors.grey),
                  const SizedBox(width: 8),
                  const Text('참가 상태: ', style: TextStyle(fontWeight: FontWeight.bold)),
                  if (participant.status != null)
                    _buildBadge(
                      text: participant.status!,
                      color: _getParticipantStatusColor(participant.status!),
                      icon: _getParticipantStatusIcon(participant.status!),
                    )
                  else
                    const Text('없음'),
                ],
              ),
            ),
            
            // 결제 상태 표시
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 8.0),
              child: Row(
                children: [
                  const Icon(Icons.payment, size: 20, color: Colors.grey),
                  const SizedBox(width: 8),
                  const Text('결제 상태: ', style: TextStyle(fontWeight: FontWeight.bold)),
                  _buildBadge(
                    text: participant.isPaid ? '결제완료' : '미결제',
                    color: participant.isPaid ? Colors.green : Colors.red,
                    icon: participant.isPaid ? Icons.check_circle : Icons.cancel,
                  ),
                  if (participant.paidAmount != null)
                    Padding(
                      padding: const EdgeInsets.only(left: 8.0),
                      child: Text('(${participant.paidAmount}원)'),
                    ),
                ],
              ),
            ),
            if (participant.notes != null) ...[
              const Divider(),
              const Text('메모:', style: TextStyle(fontWeight: FontWeight.bold)),
              Text(participant.notes!),
            ],
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('닫기'),
          ),
        ],
      ),
    );
  }

  // 점수 추가
  void _addScore() {
    // 점수 추가 다이얼로그 표시
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('점수 추가'),
        content: const Text('점수 추가 기능은 아직 구현 중입니다.'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('확인'),
          ),
        ],
      ),
    );
  }

  // 점수 수정
  void _editScore(Score score) {
    // 점수 수정 다이얼로그 표시
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('점수 수정'),
        content: Text('점수 ID: ${score.id} 수정 기능은 아직 구현 중입니다.'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('확인'),
          ),
        ],
      ),
    );
  }

  // 점수 삭제
  void _deleteScore(Score score) {
    // 점수 삭제 확인 다이얼로그
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('점수 삭제'),
        content: const Text('이 점수를 정말 삭제하시겠습니까?'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('취소'),
          ),
          TextButton(
            onPressed: () async {
              Navigator.of(context).pop();
              
              setState(() {
                _tabLoadingStates[2] = true;
              });
              
              try {
                final eventService = Provider.of<EventService>(context, listen: false);
                await eventService.deleteScore(widget.event.id, score.id);
                
                if (mounted) {
                  setState(() {
                    _scores.removeWhere((s) => s.id == score.id);
                    _tabLoadingStates[2] = false;
                  });
                  
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('점수가 삭제되었습니다')),
                  );
                }
              } catch (e) {
                if (mounted) {
                  setState(() {
                    _tabLoadingStates[2] = false;
                  });
                  
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('점수 삭제에 실패했습니다: $e')),
                  );
                }
              }
            },
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('삭제'),
          ),
        ],
      ),
    );
  }

  // 점수 상세 정보 표시
  void _showScoreDetails(Score score) {
    // 참가자 이름 찾기
    final participant = _participants.firstWhere(
      (p) => p.memberId == score.memberId,
      orElse: () => Participant(
        id: '',
        eventId: '',
        memberId: score.memberId,
        name: '알 수 없음',
      ),
    );
    
    // 점수 상세 정보 다이얼로그
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('${participant.name} 점수'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildInfoRow(Icons.score, '총점: ${score.totalScore}'),
            _buildInfoRow(
              Icons.calendar_today,
              '날짜: ${DateFormat('yyyy-MM-dd').format(score.date)}',
            ),
            const Divider(),
            const Text('프레임별 점수:', style: TextStyle(fontWeight: FontWeight.bold)),
            const SizedBox(height: 8),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: score.frames.asMap().entries.map((entry) {
                final frameIndex = entry.key;
                final frameValue = entry.value;
                
                // 스트라이크와 스페어 표시 로직
                String displayText = frameValue.toString();
                Color backgroundColor = Colors.white;
                Color textColor = Colors.black;
                
                // 스트라이크인 경우 (10점)
                if (frameValue == 10) {
                  displayText = 'X';
                  backgroundColor = Colors.red.shade100;
                  textColor = Colors.red;
                }
                // 스페어인 경우 (첫 투구와 두 번째 투구의 합이 10점)
                // 스페어 판별은 이전 프레임과 현재 프레임을 비교해서 추정
                else if (frameIndex > 0 && 
                         score.frames[frameIndex-1] < 10 && 
                         score.frames[frameIndex-1] + frameValue == 10) {
                  displayText = '/';
                  backgroundColor = Colors.blue.shade100;
                  textColor = Colors.blue;
                }
                
                return Container(
                  width: 40,
                  height: 40,
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.blue),
                    borderRadius: BorderRadius.circular(4),
                    color: backgroundColor,
                  ),
                  child: Center(
                    child: Text(
                      displayText,
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        color: textColor,
                      ),
                    ),
                  ),
                );
              }).toList(),
            ),
            if (score.notes != null) ...[  
              const Divider(),
              const Text('메모:', style: TextStyle(fontWeight: FontWeight.bold)),
              Text(score.notes ?? ''),
            ],
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('닫기'),
          ),
        ],
      ),
    );
  }

  // 공유 성공 스낵바 표시
}
