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

import '../../models/club_model.dart';
import '../../models/event_model.dart';
import '../../models/member_model.dart';
import '../../models/participant_model.dart';
import '../../models/score_model.dart';
import '../../models/team_model.dart';
import '../../services/club_service.dart';
import '../../services/event_service.dart';
import '../../services/member_service.dart';
import '../../services/notification_service.dart';
import '../../utils/url_utils.dart';
import '../../widgets/loading_indicator.dart';
import '../../utils/enum_mappings.dart';
// participant_form_screen 제거: 모든 추가는 기존 회원 빠른추가 경로로 통일
import 'score_form_screen.dart';
import 'event_form_screen.dart';
import '../score/score_batch_edit_screen.dart';
import 'tabs/scores_tab.dart';
import 'tabs/basic_info_tab.dart';
import 'tabs/participants_tab.dart';
import 'tabs/teams_tab.dart';

class EventDetailsScreen extends StatefulWidget {
  final Event event;
  // 테스트 시 초기 비동기 로드를 건너뛰기 위한 플래그
  @visibleForTesting
  static bool testMode = false;

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

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

class _EventDetailsScreenState extends State<EventDetailsScreen>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  Event? _event; // 최신 이벤트 정보 보관
  List<Participant> _participants = [];
  List<Score> _scores = [];
  List<Team> _teams = [];
  List<Member> _members = [];
  // 클럽 전체 회원 목록 (빠른추가 드롭다운에 사용)
  List<Member> _clubMembers = [];
  Club? _club;
  bool _isLoading = true;
  int _teamGenerationMethod = 1; // 1: 팀 인원수로 나누기, 2: 팀 개수로 나누기
  final TextEditingController _teamSizeController = TextEditingController(
    text: '4',
  );
  final TextEditingController _teamCountController = TextEditingController(
    text: '2',
  );
  bool _showTeamTab = false;
  bool _includeHandicap = true; // 핸디캡 포함 여부
  bool _groupByParticipant = false; // 점수 표시 방식: false=점수별(기존), true=참가자별 그룹
  bool _clubMembersLoading = false;
  VoidCallback? _memberServiceListener;
  MemberService? _memberServiceRef;

  @override
  void initState() {
    super.initState();
    // 테스트를 위해 팀 탭 항상 표시
    _showTeamTab = true;
    // 탭 컨트롤러 길이 동적 설정
    _tabController = TabController(length: _showTeamTab ? 4 : 3, vsync: this);
    // 탭 전환 시 FAB 등 상단 Scaffold 요소가 즉시 갱신되도록 리스너 추가
    _tabController.addListener(() {
      if (!mounted) return;
      // index 변화 시 재빌드하여 floatingActionButton을 갱신
      setState(() {});
    });
    // 프레임 이후 Provider 접근 및 MemberService 구독 설정
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!mounted) return;
      final memberService = Provider.of<MemberService>(context, listen: false);
      _memberServiceRef = memberService;
      // 초기 동기화
      setState(() {
        _clubMembers = memberService.members;
        _clubMembersLoading = memberService.isLoading;
      });
      // 리스너 등록: 회원 목록/로딩 상태 변화 시 동기화
      _memberServiceListener = () {
        if (!mounted) return;
        setState(() {
          _clubMembers = memberService.members;
          _clubMembersLoading = memberService.isLoading;
        });
      };
      memberService.addListener(_memberServiceListener!);
      // 이벤트 상세 로드 (테스트 모드에서는 스킵)
      if (!EventDetailsScreen.testMode) {
        _loadEventDetails();
      } else {
        setState(() {
          _isLoading = false;
        });
      }
    });
  }

  // 드래그앤드롭으로 팀 간 참가자 이동 처리
  void _moveParticipantBetweenTeams(
    Participant participant,
    Team fromTeam,
    Team toTeam,
    int toIndex,
  ) {
    setState(() {
      final fromIdx = _teams.indexWhere((t) => t.id == fromTeam.id);
      final toIdx = _teams.indexWhere((t) => t.id == toTeam.id);
      if (toIdx < 0) return;

      final memberId = participant.memberId;
      // remove from source (미배정에서 오는 경우 fromIdx는 -1이 될 수 있음)
      List<String>? fromMemberIds;
      if (fromIdx >= 0) {
        fromMemberIds = List<String>.from(_teams[fromIdx].memberIds);
        fromMemberIds.remove(memberId);
      }

      // insert into target at index
      final toMemberIds = List<String>.from(_teams[toIdx].memberIds);
      // 중복 방지: 기존에 있으면 먼저 제거 (같은 팀 이동 시 길이가 줄어듦)
      toMemberIds.remove(memberId);
      // 제거 이후 길이에 맞춰 인덱스 보정
      int insertIndex = toIndex.clamp(0, toMemberIds.length);
      toMemberIds.insert(insertIndex, memberId);

      if (fromIdx >= 0 && fromMemberIds != null) {
        _teams[fromIdx] = Team(
          id: _teams[fromIdx].id,
          eventId: _teams[fromIdx].eventId,
          name: _teams[fromIdx].name,
          memberIds: fromMemberIds,
          description: _teams[fromIdx].description,
          createdAt: _teams[fromIdx].createdAt,
          updatedAt: _teams[fromIdx].updatedAt,
        );
      }

      _teams[toIdx] = Team(
        id: _teams[toIdx].id,
        eventId: _teams[toIdx].eventId,
        name: _teams[toIdx].name,
        memberIds: toMemberIds,
        description: _teams[toIdx].description,
        createdAt: _teams[toIdx].createdAt,
        updatedAt: _teams[toIdx].updatedAt,
      );
    });
  }

  

  // 참가자 추가 선택 시트: 기존 회원 추가 vs 게스트 추가
  Future<void> _openAddChooser() async {
    if (!mounted) return;
    await showModalBottomSheet<void>(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (ctx) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                key: const Key('add_existing_member'),
                leading: const Icon(Icons.person_add_alt_1),
                title: const Text('기존 회원 추가'),
                onTap: () async {
                  Navigator.of(ctx).pop();
                  await _openMemberQuickAddModal();
                },
              ),
              ListTile(
                key: const Key('add_guest'),
                leading: const Icon(Icons.group_add),
                title: const Text('게스트 추가'),
                onTap: () async {
                  Navigator.of(ctx).pop();
                  await _openGuestModal();
                },
              ),
              const SizedBox(height: 8),
            ],
          ),
        );
      },
    );
  }

  // 테스트 전용: 탭 전환 없이 모달을 직접 오픈
  @visibleForTesting
  Future<void> openQuickAddForTest() => _openMemberQuickAddModal();

  // 테스트 전용: 탭 전환/ FAB 없이 추가 선택 시트를 직접 오픈
  @visibleForTesting
  Future<void> openAddChooserForTest() => _openAddChooser();

  Future<void> _duplicateEvent() async {
    final messenger = ScaffoldMessenger.of(context);
    try {
      final eventService = Provider.of<EventService>(context, listen: false);
      // cloneEvent에 필요한 clubId 보장
      eventService.setClubId(widget.event.clubId);
      await eventService.cloneEvent(widget.event.id);
      if (!mounted) return;
      messenger.showSnackBar(const SnackBar(content: Text('이벤트가 복제되었습니다')));
      // 목록 화면에서 새로고침할 수 있도록 결과 전달
      Navigator.of(context).pop(true);
    } catch (e) {
      messenger.showSnackBar(SnackBar(content: Text('이벤트 복제에 실패했습니다: $e')));
    }
  }

  @visibleForTesting
  List<Map<String, dynamic>> buildServerTeamsForSave(
    List<Team> teams,
    List<Participant> participants,
  ) {
    final List<Map<String, dynamic>> serverTeams = [];
    for (int i = 0; i < teams.length; i++) {
      final team = teams[i];
      final members = <Map<String, dynamic>>[];
      for (int j = 0; j < team.memberIds.length; j++) {
        final memberId = team.memberIds[j];
        final participant = participants.firstWhere(
          (p) => p.memberId == memberId,
          orElse: () => Participant(id: '', eventId: widget.event.id, memberId: memberId),
        );
        if (participant.id.isNotEmpty) {
          members.add({'id': participant.id, 'order': j + 1});
        }
      }
      serverTeams.add({'teamNumber': i + 1, 'handicap': 0, 'members': members});
    }
    return serverTeams;
  }

  // ===== 테스트 훅들 (TDD 지원) =====
  @visibleForTesting
  void debugSetTeamsAndParticipants(List<Team> teams, List<Participant> participants) {
    setState(() {
      _teams = teams;
      _participants = participants;
    });
  }

  @visibleForTesting
  List<Team> debugGetTeams() => _teams.map((t) => Team(
        id: t.id,
        eventId: t.eventId,
        name: t.name,
        memberIds: List<String>.from(t.memberIds),
        description: t.description,
        createdAt: t.createdAt,
        updatedAt: t.updatedAt,
      )).toList();

  @visibleForTesting
  void testMoveParticipantBetweenTeams(
    Participant participant,
    Team fromTeam,
    Team toTeam,
    int toIndex,
  ) {
    _moveParticipantBetweenTeams(participant, fromTeam, toTeam, toIndex);
  }

  @visibleForTesting
  double debugCalculateTeamAverage(Team team) => _calculateTeamAverage(team);

  @visibleForTesting
  void debugSetScores(List<Score> scores) {
    setState(() {
      _scores = scores;
    });
  }

  // 참가자별 점수 일괄 수정 화면으로 이동
  Future<void> _openBatchEdit(
    Participant participant,
    List<Score> scores,
  ) async {
    if (!mounted) return;
    final messenger = ScaffoldMessenger.of(context);
    final result = await Navigator.of(context).push<bool>(
      MaterialPageRoute(
        builder: (_) => ScoreBatchEditScreen(
          eventId: widget.event.id,
          participant: participant,
          scores: scores,
          gameCount: widget.event.gameCount ?? scores.length,
        ),
      ),
    );
    if (result == true && mounted) {
      await _loadEventDetails();
      messenger.showSnackBar(const SnackBar(content: Text('점수를 일괄 수정했습니다')));
    }
  }

  @override
  void dispose() {
    // MemberService 리스너 해제: dispose 시점의 BuildContext 사용을 피하기 위해 보관한 ref 사용
    if (_memberServiceListener != null && _memberServiceRef != null) {
      try {
        _memberServiceRef!.removeListener(_memberServiceListener!);
      } catch (_) {}
      _memberServiceListener = null;
    }

    _tabController.dispose();
    _teamSizeController.dispose();
    _teamCountController.dispose();
    super.dispose();
  }

  // 게스트 사전입력 모달 열기
  Future<void> _openGuestModal() async {
    // await 이전에 필요한 의존성/서비스를 캡처
    final messenger = ScaffoldMessenger.of(context);
    final eventService = Provider.of<EventService>(context, listen: false);
    final memberService = Provider.of<MemberService>(context, listen: false);

    final nameController = TextEditingController();
    String gender = 'male';
    final phoneController = TextEditingController();
    final emailController = TextEditingController();
    final handicapController = TextEditingController();
    String participantStatus = 'pending';
    String paymentStatus = 'unpaid';
    final commentController = TextEditingController();

    final result = await showModalBottomSheet<bool>(
      context: context,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (ctx) {
        return Padding(
          padding: EdgeInsets.only(
            bottom: MediaQuery.of(ctx).viewInsets.bottom,
            left: 16,
            right: 16,
            top: 16,
          ),
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                const Text(
                  '게스트 정보 입력',
                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                ),
                const SizedBox(height: 12),
                TextField(
                  controller: nameController,
                  decoration: const InputDecoration(
                    labelText: '이름(선택)',
                    border: OutlineInputBorder(),
                    prefixIcon: Icon(Icons.person),
                  ),
                ),
                const SizedBox(height: 8),
                Row(
                  children: [
                    Expanded(
                      child: DropdownButtonFormField<String>(
                        key: const Key('event_details_guest_gender_dropdown'),
                        value: gender,
                        decoration: const InputDecoration(
                          labelText: '성별',
                          border: OutlineInputBorder(),
                          prefixIcon: Icon(Icons.wc),
                        ),
                        isExpanded: true,
                        items: [
                          DropdownMenuItem<String>(
                            value: 'male',
                            child: Text(
                              '남',
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                          DropdownMenuItem<String>(
                            value: 'female',
                            child: Text(
                              '여',
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                        onChanged: (v) => gender = v ?? 'male',
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: TextField(
                        controller: handicapController,
                        decoration: const InputDecoration(
                          labelText: '핸디캡(선택)',
                          border: OutlineInputBorder(),
                          prefixIcon: Icon(Icons.calculate),
                        ),
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly,
                        ],
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: phoneController,
                        decoration: const InputDecoration(
                          labelText: '전화(선택)',
                          border: OutlineInputBorder(),
                          prefixIcon: Icon(Icons.phone),
                        ),
                        keyboardType: TextInputType.phone,
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: TextField(
                        controller: emailController,
                        decoration: const InputDecoration(
                          labelText: '이메일(선택)',
                          border: OutlineInputBorder(),
                          prefixIcon: Icon(Icons.email),
                        ),
                        keyboardType: TextInputType.emailAddress,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 12),
                const Text(
                  '참가 정보',
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 8),
                Row(
                  children: [
                    Expanded(
                      child: DropdownButtonFormField<String>(
                        key: const Key(
                          'event_details_participant_status_dropdown',
                        ),
                        value:
                            (participantStatusOptions.keys.contains(
                              participantStatus,
                            ))
                            ? participantStatus
                            : null,
                        decoration: const InputDecoration(
                          labelText: '상태',
                          border: OutlineInputBorder(),
                          prefixIcon: Icon(Icons.verified_user),
                        ),
                        isExpanded: true,
                        items: participantStatusOptions.entries
                            .map(
                              (e) => DropdownMenuItem<String>(
                                value: e.key,
                                child: Text(
                                  e.value,
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                            )
                            .toList(),
                        onChanged: (v) => participantStatus = v ?? 'pending',
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: DropdownButtonFormField<String>(
                        key: const Key('event_details_payment_status_dropdown'),
                        value:
                            (paymentStatusOptions.keys.contains(paymentStatus))
                            ? paymentStatus
                            : null,
                        decoration: const InputDecoration(
                          labelText: '결제',
                          border: OutlineInputBorder(),
                          prefixIcon: Icon(Icons.payment),
                        ),
                        isExpanded: true,
                        items: paymentStatusOptions.entries
                            .map(
                              (e) => DropdownMenuItem<String>(
                                value: e.key,
                                child: Text(
                                  e.value,
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                            )
                            .toList(),
                        onChanged: (v) => paymentStatus = v ?? 'unpaid',
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                TextField(
                  controller: commentController,
                  decoration: const InputDecoration(
                    labelText: '비고(선택)',
                    border: OutlineInputBorder(),
                    prefixIcon: Icon(Icons.notes),
                  ),
                  maxLines: 2,
                ),
                const SizedBox(height: 12),
                Row(
                  children: [
                    Expanded(
                      child: OutlinedButton(
                        onPressed: () => Navigator.of(ctx).pop(false),
                        child: const Text('취소'),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: ElevatedButton.icon(
                        icon: const Icon(Icons.save),
                        onPressed: () => Navigator.of(ctx).pop(true),
                        label: const Text('저장 후 추가'),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
              ],
            ),
          ),
        );
      },
    );

    if (result != true) {
      return;
    }

    // 저장 처리: 입력값 기반으로 회원 생성 후 참가자 추가
    setState(() => _isLoading = true);
    try {
      final Map<String, dynamic> memberPayload = {
        'name': (nameController.text.trim().isEmpty)
            ? '게스트'
            : nameController.text.trim(),
        'gender': gender, // 백엔드 필수
        'memberType': 'guest',
        'status': 'active',
      };
      if (phoneController.text.trim().isNotEmpty) {
        memberPayload['phone'] = phoneController.text.trim();
      }
      if (emailController.text.trim().isNotEmpty) {
        memberPayload['email'] = emailController.text.trim();
      }
      if (handicapController.text.trim().isNotEmpty) {
        final parsed = int.tryParse(handicapController.text.trim());
        if (parsed != null) memberPayload['handicap'] = parsed;
      }

      final guestMember = await memberService.addMember(memberPayload);

      final Map<String, dynamic> participantPayload = {
        'memberId': guestMember.id,
        // 드롭다운과 백엔드 허용값 정합성: enum 키 사용 (pending/confirmed/canceled)
        'status': participantStatus,
        'paymentStatus': paymentStatus,
      };
      if (commentController.text.trim().isNotEmpty) {
        participantPayload['comment'] = commentController.text.trim();
      }

      await eventService.addParticipant(widget.event.id, participantPayload);
      if (!mounted) {
        return;
      }
      // 서버 재조회로 상세 정보 반영
      await _loadEventDetails();
      messenger.showSnackBar(const SnackBar(content: Text('게스트를 추가했습니다.')));
    } catch (e) {
      messenger.showSnackBar(SnackBar(content: Text('게스트 추가 실패: $e')));
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  Future<void> _loadEventDetails() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final eventService = Provider.of<EventService>(context, listen: false);
      final clubService = Provider.of<ClubService>(context, listen: false);
      final memberService = Provider.of<MemberService>(context, listen: false);
      // EventService가 clubId 없을 경우 참가자/점수/참가자 추가 등에서 인증/클럽 정보 오류가 발생하므로
      // 화면 진입 시점의 이벤트 clubId를 주입하여 안정화한다.
      eventService.setClubId(widget.event.clubId);
      // MemberService도 clubId가 필요하므로 함께 주입한다.
      await memberService.setClubId(widget.event.clubId);

      // 최신 이벤트 상세 로드
      final fetchedEvent = await eventService.fetchEventById(widget.event.id);

      // 참가자 목록 로드
      final participants = await eventService.fetchEventParticipants(
        widget.event.id,
      );

      // 점수 목록 로드
      final scores = await eventService.fetchEventScores(widget.event.id);

      // participantId 누락 데이터 보정: memberId로 매칭하여 participantId 채움
      final Map<String, String> memberIdToParticipantId = {
        for (final p in participants) p.memberId: p.id,
      };
      final adjustedScores = scores.map((s) {
        if (s.participantId == null || s.participantId!.isEmpty) {
          final pid = memberIdToParticipantId[s.memberId];
          if (pid != null) {
            return Score(
              id: s.id,
              memberId: s.memberId,
              eventId: s.eventId,
              clubId: s.clubId,
              participantId: pid,
              frames: s.frames,
              totalScore: s.totalScore,
              handicap: s.handicap,
              gameNumber: s.gameNumber,
              date: s.date,
              notes: s.notes,
              participantName: s.participantName,
            );
          }
        }
        return s;
      }).toList();

      // 클럽 정보 로드
      final club = await clubService.fetchClub(widget.event.clubId);

      // 회원 정보 로드 (동점자 처리 시 생년월일 사용)
      final memberIds = participants.map((p) => p.memberId).toList();
      final members = await memberService.fetchMembersByIds(
        widget.event.clubId,
        memberIds,
      );
      // 참가자 정보 보강: Member에서 handicap/gender/name 보완
      final Map<String, Member> memberById = {for (final m in members) m.id: m};
      final List<Participant> enrichedParticipants = participants.map((p) {
        final m = memberById[p.memberId];
        if (m == null) return p;
        final int? pHcp = p.handicap;
        final bool needHcp = pHcp == null || pHcp <= 0;
        final String? pGender = p.gender;
        final bool needGender = pGender == null || pGender.isEmpty;
        final String? pName = p.name;
        final bool needName = pName == null || pName.isEmpty;
        if (!needHcp && !needGender && !needName) return p;
        return p.copyWith(
          handicap: needHcp ? m.handicap : p.handicap,
          gender: needGender ? m.gender : p.gender,
          name: needName ? m.name : p.name,
        );
      }).toList();
      // 빠른추가용 클럽 전체 회원 목록 로드 (MemberService 리스너로 동기화되므로 별도 setState 없이 호출만)
      await memberService.fetchClubMembers();

      // 팀 목록 로드 (선택적)
      List<Team> teams = [];
      try {
        teams = await eventService.fetchEventTeams(widget.event.id);
      } catch (e) {
        // 팀 기능이 없거나 오류 발생 시 무시
        if (kDebugMode) {
          debugPrint('팀 로드 실패: $e');
        }
      }

      if (mounted) {
        setState(() {
          _event = fetchedEvent;
          _participants = enrichedParticipants;
          _scores = adjustedScores;
          _teams = teams;
          _club = club;
          _members = members;
          _showTeamTab = true; // 테스트를 위해 팀 탭 항상 표시
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('이벤트 정보를 불러오는데 실패했습니다: $e')));
      }
    }
  }

  // 상단 빠른추가 제거로 재조회 핸들러는 더 이상 사용하지 않습니다.

  // 이벤트 공유 기능
  void _shareEvent() {
    // 공유할 내용 구성
    final String eventTitle = widget.event.title;
    final String eventType = getEventTypeLabel(widget.event.type);
    final String eventDate = DateFormat(
      'yyyy-MM-dd HH:mm',
    ).format(widget.event.startDate);
    final String eventLocation = widget.event.location ?? '장소 미정';

    // 공개 URL 생성
    String shareUrl = '';
    if (widget.event.publicHash != null &&
        widget.event.publicHash!.isNotEmpty) {
      shareUrl = UrlUtils.getEventPublicUrl(widget.event.publicHash!);
    }

    // 공유 메시지 구성
    final String shareText =
        '''
[볼링 이벤트 초대]
$eventTitle

유형: $eventType
일시: $eventDate
장소: $eventLocation

참가자: ${_participants.length}명

${shareUrl.isNotEmpty ? '참가 링크: $shareUrl' : ''}
${widget.event.accessPassword != null && widget.event.accessPassword!.isNotEmpty ? '비밀번호: ${widget.event.accessPassword}' : ''}
''';

    // 공유 다이얼로그 표시 (Share는 deprecated)
    SharePlus.instance.share(
      ShareParams(text: shareText, subject: '볼링 이벤트: $eventTitle'),
    );
  }

  

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          (_event ?? widget.event).title,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        actions: _buildAppBarActions(),
        bottom: TabBar(
          controller: _tabController,
          tabs: [
            const Tab(text: '기본 정보'),
            const Tab(text: '참가자'),
            const Tab(text: '점수'),
            if (_showTeamTab) const Tab(text: '팀'),
          ],
        ),
      ),
      body: _isLoading
          ? const LoadingIndicator()
          : TabBarView(
              controller: _tabController,
              children: [
                _buildBasicInfoTab(),
                _buildParticipantsTab(),
                _buildScoresTab(),
                if (_showTeamTab) _buildTeamsTab(),
              ],
            ),
      // FAB 제거: 상단 AppBar actions로 통합
    );
  }

  List<Widget> _buildAppBarActions() {
    final currentTab = _tabController.index;
    final actions = <Widget>[];
    switch (currentTab) {
      case 0: // 기본 정보
        actions.add(
          IconButton(
            tooltip: '이벤트 수정',
            icon: const Icon(Icons.edit),
            onPressed: _editEvent,
          ),
        );
        break;
      case 1: // 참가자
        actions.add(
          IconButton(
            tooltip: '참가자 추가',
            icon: const Icon(Icons.person_add),
            onPressed: _openAddChooser,
          ),
        );
        break;
      case 2: // 점수
        actions.add(
          IconButton(
            tooltip: '점수 추가',
            icon: const Icon(Icons.add_chart),
            onPressed: _addScore,
          ),
        );
        break;
      case 3: // 팀
        if (_showTeamTab) {
          actions.addAll([
            IconButton(
              tooltip: '팀 재생성',
              icon: const Icon(Icons.refresh),
              onPressed: _isLoading ? null : _generateTeams,
            ),
            IconButton(
              tooltip: '팀 저장',
              icon: const Icon(Icons.save),
              onPressed: _isLoading ? null : _saveTeams,
            ),
          ]);
        }
        break;
    }
    return actions;
  }

  // 기본 정보 탭
  Widget _buildBasicInfoTab() {
    return BasicInfoTab(
      event: _event ?? widget.event,
      participantsCount: _participants.length,
      onShareEvent: _shareEvent,
      onSetEventReminders: _setEventReminders,
    );
  }

  

  // 참가자 탭
  Widget _buildParticipantsTab() {
    return ParticipantsTab(
      participants: _participants,
      scores: _scores,
      onEditParticipant: _editParticipant,
    );
  }

  // 상단 빠른추가 제거로 개별 추가 핸들러는 더 이상 사용하지 않습니다.

  // 점수 탭
  Widget _buildScoresTab() {
    return ScoresTab(
      eventId: widget.event.id,
      participants: _participants,
      scores: _scores,
      members: _members,
      clubMembers: _clubMembers,
      club: _club,
      includeHandicap: _includeHandicap,
      onIncludeHandicapChanged: (v) => setState(() => _includeHandicap = v),
      groupByParticipant: _groupByParticipant,
      onGroupByParticipantChanged: (v) => setState(() => _groupByParticipant = v),
      onOpenBatchEdit: _openBatchEdit,
      onEditScore: _editScore,
      onDeleteScore: _deleteScore,
    );
  }

  // 점수 추가
  Future<void> _addScore() async {
    final result = await Navigator.of(context).push<bool>(
      MaterialPageRoute(
        builder: (_) => ScoreFormScreen(
          eventId: widget.event.id,
          participants: _participants,
          gameCount: widget.event.gameCount ?? 1,
        ),
      ),
    );
    if (result == true) {
      _loadEventDetails();
      if (_tabController.index != 2) {
        _tabController.animateTo(2);
      }
    }
  }

  // 점수 수정
  Future<void> _editScore(Score score) async {
    final result = await Navigator.of(context).push<bool>(
      MaterialPageRoute(
        builder: (_) => ScoreFormScreen(
          eventId: widget.event.id,
          score: score,
          participants: _participants,
        ),
      ),
    );
    if (result == true) {
      _loadEventDetails();
      if (_tabController.index != 2) {
        _tabController.animateTo(2);
      }
    }
  }

  // 팀 탭
  Widget _buildTeamsTab() {
    return TeamsTab(
      event: widget.event,
      isLoading: _isLoading,
      teams: _teams,
      participants: _participants,
      scores: _scores,
      teamGenerationMethod: _teamGenerationMethod,
      teamSizeController: _teamSizeController,
      teamCountController: _teamCountController,
      unassignedParticipants: _getUnassignedParticipants(),
      onChangeTeamGenerationMethod: (value) => setState(() => _teamGenerationMethod = value),
      onGenerateTeams: _generateTeams,
      onSaveTeams: _saveTeams,
      onRemoveFromTeam: _removeFromTeam,
      onShowParticipantSelectionDialog: _showParticipantSelectionDialog,
      onShowTeamSelectionDialog: _showTeamSelectionDialog,
      calculateTeamAverage: _calculateTeamAverage,
      onShareEvent: _shareEvent,
      onMoveParticipant: _moveParticipantBetweenTeams,
    );
  }

  

  

  

  

  

  
  // 이벤트 알림 설정 기능
  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;
    final messenger = ScaffoldMessenger.of(context);

    showDialog(
      context: context,
      builder: (dialogContext) => 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 {
                final navigator = Navigator.of(dialogContext);
                navigator.pop();
                await notificationService.scheduleEventStartReminder(
                  widget.event,
                );
                messenger.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 {
                  final navigator = Navigator.of(dialogContext);
                  navigator.pop();
                  await notificationService
                      .scheduleRegistrationDeadlineReminder(widget.event);
                  messenger.showSnackBar(
                    const SnackBar(content: Text('등록 마감 알림이 설정되었습니다')),
                  );
                },
              ),
            ListTile(
              leading: const Icon(Icons.notifications_off),
              title: const Text('알림 취소'),
              subtitle: const Text('이 이벤트에 대한 모든 알림 취소'),
              onTap: () async {
                final navigator = Navigator.of(dialogContext);
                navigator.pop();
                await notificationService.cancelEventNotifications(
                  widget.event.id,
                );
                messenger.showSnackBar(
                  const SnackBar(content: Text('이벤트 알림이 취소되었습니다')),
                );
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(dialogContext).pop(),
            child: const Text('닫기'),
          ),
        ],
      ),
    );
  }

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

    // 배정되지 않은 참가자 목록 반환
    return _participants
        .where((p) => !assignedMemberIds.contains(p.memberId))
        .toList();
  }

  // 팀 평균 점수 계산
  double _calculateTeamAverage(Team team) {
    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, (sum, score) => sum + score.totalScore);
        totalAverage += memberTotal / memberScores.length;
        memberCount++;
      } else {
        // 점수가 없으면 참가자 프로필의 평균을 사용 (있다면, 0은 무시)
        final participant = _participants.firstWhere(
          (p) => p.memberId == memberId,
          orElse: () => Participant(id: 'unknown_$memberId', eventId: widget.event.id, memberId: memberId),
        );
        final avg = participant.average;
        if (avg != null && avg > 0) {
          totalAverage += avg;
          memberCount++;
        }
      }
    }

    return memberCount > 0 ? totalAverage / memberCount : 0.0;
  }

  // 팀 생성: 현재 탭에서 로컬 생성 후 저장
  Future<void> _generateTeams() async {
    // 입력값 검증 및 파라미터 구성
    int? teamSize;
    int? teamCount;
    if (_teamGenerationMethod == 1) {
      teamSize = int.tryParse(_teamSizeController.text.trim());
      if (teamSize == null || teamSize <= 0) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('유효한 인원수를 입력해주세요')),
        );
        return;
      }
    } else if (_teamGenerationMethod == 2) {
      teamCount = int.tryParse(_teamCountController.text.trim());
      if (teamCount == null || teamCount <= 0) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('유효한 팀 수를 입력해주세요')),
        );
        return;
      }
    } else {
      // 기본: 참가자 수 기반 2팀
      teamCount = 2;
    }

    setState(() => _isLoading = true);
    try {
      // 1) 대상 참가자 선택: 취소된 참가자 제외
      final selected = _participants.where((p) {
        final st = (p.status ?? '').toLowerCase();
        return st != 'canceled';
      }).toList();
      if (selected.isEmpty) {
        setState(() => _isLoading = false);
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('팀에 배정할 참가자가 없습니다')),
        );
        return;
      }

      // 2) 팀 수 계산
      int finalTeamCount;
      if (teamSize != null) {
        finalTeamCount = (selected.length / teamSize).ceil();
      } else {
        finalTeamCount = teamCount ?? 2;
      }
      if (finalTeamCount <= 0) finalTeamCount = 1;
      if (finalTeamCount > selected.length) finalTeamCount = selected.length;

      // 3) 셔플 후 라운드로빈 배정(균등 배분)
      selected.shuffle();
      final buckets = List.generate(finalTeamCount, (_) => <Participant>[]);
      for (int i = 0; i < selected.length; i++) {
        buckets[i % finalTeamCount].add(selected[i]);
      }

      // 4) UI용 Team 모델 구성 (memberIds는 memberId 문자열)
      final newTeams = List.generate(
        finalTeamCount,
        (i) => Team(
          id: '',
          eventId: widget.event.id,
          name: '${i + 1}',
          memberIds: buckets[i].map((p) => p.memberId).toList(),
          description: '자동 생성된 팀',
        ),
      );

      if (!mounted) return;
      setState(() {
        _teams = newTeams;
        _isLoading = false;
      });
      if (_showTeamTab && _tabController.index != 3) {
        _tabController.animateTo(3);
      }
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('팀이 생성되었습니다. "팀 저장"을 눌러 저장하세요.')),
      );
    } catch (e) {
      if (!mounted) return;
      setState(() => _isLoading = false);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('팀 생성 실패: $e')),
      );
    }
  }

  // 팀 저장: 현재 _teams 상태를 서버 포맷으로 변환하여 저장
  void _saveTeams() async {
    if (_teams.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('저장할 팀이 없습니다.')),
      );
      return;
    }

    // 서버 저장 포맷으로 변환: teamNumber, members: [{id: participantId, order}]
    final serverTeams = buildServerTeamsForSave(_teams, _participants);

    final eventService = Provider.of<EventService>(context, listen: false);
    setState(() => _isLoading = true);
    try {
      await eventService.createOrUpdateEventTeams(widget.event.id, serverTeams);
      if (!mounted) return;
      // 서버 반영 직후 최신 상태 재조회
      await _loadEventDetails();
      if (!mounted) return;
      setState(() => _isLoading = false);
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('팀이 저장되었습니다.')),
      );
    } catch (e) {
      if (!mounted) return;
      setState(() => _isLoading = false);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('팀 저장 실패: $e')),
      );
    }
  }

  // 팀에서 참가자 제거
  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();
                  setState(() {
                    team.memberIds.add(participant.memberId);
                  });
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Text(
                        '${participant.name}님이 팀 ${team.name}에 추가되었습니다.',
                      ),
                    ),
                  );
                },
              );
            },
          ),
        ),
        actions: DialogActions.confirm(
          onCancel: () => Navigator.of(context).pop(),
          onConfirm: () => Navigator.of(context).pop(),
          confirmText: '닫기',
        ),
      ),
    );
  }

  // 참가자를 추가할 팀 선택 다이얼로그 표시
  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();
                  setState(() {
                    team.memberIds.add(participant.memberId);
                  });
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Text(
                        '${participant.name}님이 팀 ${team.name}에 추가되었습니다.',
                      ),
                    ),
                  );
                },
              );
            },
          ),
        ),
        actions: DialogActions.confirm(
          onCancel: () => Navigator.of(context).pop(),
          onConfirm: () => Navigator.of(context).pop(),
          confirmText: '닫기',
        ),
      ),
    );
  }

  // 이벤트 수정: 생성 폼을 그대로 활용하여 수정에도 사용
  Future<void> _editEvent() async {
    final result = await Navigator.of(context).push<bool>(
      MaterialPageRoute(builder: (_) => EventFormScreen(event: _event ?? widget.event)),
    );
    if (result == true && mounted) {
      await _loadEventDetails();
    }
  }

  // 기존 회원 빠른추가 모달 (상태/결제 선택 포함)
  Future<void> _openMemberQuickAddModal() async {
    if (!mounted) return;
    final messenger = ScaffoldMessenger.of(context);
    final eventService = Provider.of<EventService>(context, listen: false);
    final memberService = Provider.of<MemberService>(context, listen: false);

    String? selectedMemberId;
    String status = 'pending';
    String paymentStatus = 'unpaid';
    final commentCtrl = TextEditingController();

    // 최신 회원 목록 없으면 로드 시도
    if (_clubMembers.isEmpty && !_clubMembersLoading) {
      try {
        await memberService.fetchClubMembers();
        setState(() {
          _clubMembers = memberService.members;
        });
      } catch (_) {}
    }

    // 비동기 작업 이후, context 사용 전 마운트 상태 확인 (lint: use_build_context_synchronously)
    if (!mounted) return;

    // 이미 참가 중인 회원 제외한 드롭다운 목록 구성
    final existingMemberIds = _participants.map((p) => p.memberId).toSet();
    final selectableMembers = _clubMembers
        .where((m) => !existingMemberIds.contains(m.id))
        .toList();

    // ignore: use_build_context_synchronously
    final ok = await showModalBottomSheet<bool>(
      context: context,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (ctx) {
        return Padding(
          padding: EdgeInsets.only(
            left: 16,
            right: 16,
            bottom: MediaQuery.of(ctx).viewInsets.bottom + 16,
            top: 16,
          ),
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                const Text(
                  '기존 회원 빠른추가',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 12),
                if (selectableMembers.isEmpty)
                  const Text('추가 가능한 회원이 없습니다 (이미 모두 참가 중).')
                else
                  DropdownButtonFormField<String>(
                    key: const Key('quick_add_member_dropdown'),
                    value: selectedMemberId,
                    isExpanded: true,
                    decoration: const InputDecoration(
                      labelText: '회원 선택',
                      border: OutlineInputBorder(),
                    ),
                    items: selectableMembers
                        .map(
                          (m) => DropdownMenuItem<String>(
                            value: m.id,
                            child: Text(
                              m.name,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        )
                        .toList(),
                    onChanged: (v) => selectedMemberId = v,
                  ),
                const SizedBox(height: 12),
                Row(
                  children: [
                    Expanded(
                      child: DropdownButtonFormField<String>(
                        key: const Key('quick_add_status_dropdown'),
                        value: status,
                        isExpanded: true,
                        decoration: const InputDecoration(
                          labelText: '상태',
                          border: OutlineInputBorder(),
                        ),
                        items: participantStatusOptions.entries
                            .map(
                              (e) => DropdownMenuItem<String>(
                                value: e.key,
                                child: Text(e.value),
                              ),
                            )
                            .toList(),
                        onChanged: (v) => status = v ?? 'pending',
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: DropdownButtonFormField<String>(
                        key: const Key('quick_add_payment_dropdown'),
                        value: paymentStatus,
                        isExpanded: true,
                        decoration: const InputDecoration(
                          labelText: '결제',
                          border: OutlineInputBorder(),
                        ),
                        items: paymentStatusOptions.entries
                            .map(
                              (e) => DropdownMenuItem<String>(
                                value: e.key,
                                child: Text(e.value),
                              ),
                            )
                            .toList(),
                        onChanged: (v) => paymentStatus = v ?? 'unpaid',
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 12),
                TextField(
                  controller: commentCtrl,
                  decoration: const InputDecoration(
                    labelText: '비고(선택)',
                    border: OutlineInputBorder(),
                    prefixIcon: Icon(Icons.notes),
                  ),
                  maxLines: 2,
                ),
                const SizedBox(height: 12),
                Row(
                  children: [
                    Expanded(
                      child: OutlinedButton(
                        onPressed: () => Navigator.of(ctx).pop(false),
                        child: const Text('취소'),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: ElevatedButton.icon(
                        icon: const Icon(Icons.person_add_alt),
                        onPressed: () {
                          if (selectableMembers.isEmpty) {
                            Navigator.of(ctx).pop(false);
                            return;
                          }
                          if (selectedMemberId == null ||
                              selectedMemberId!.isEmpty) {
                            ScaffoldMessenger.of(ctx).showSnackBar(
                              const SnackBar(content: Text('추가할 회원을 선택하세요')),
                            );
                            return;
                          }
                          Navigator.of(ctx).pop(true);
                        },
                        label: const Text('추가'),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );

    if (ok != true) {
      return;
    }

    try {
      setState(() => _isLoading = true);
      final payload = <String, dynamic>{
        'memberId': selectedMemberId,
        'status': status,
        'paymentStatus': paymentStatus,
      };
      if (commentCtrl.text.trim().isNotEmpty) {
        payload['comment'] = commentCtrl.text.trim();
      }
      await eventService.addParticipant(widget.event.id, payload);
      if (!mounted) return;
      // 서버 데이터 재조회로 중복 없이 정확한 목록을 반영
      await _loadEventDetails();
      messenger.showSnackBar(const SnackBar(content: Text('참가자를 추가했습니다.')));
    } catch (e) {
      if (!mounted) return;
      setState(() => _isLoading = false);
      messenger.showSnackBar(SnackBar(content: Text('참가자 추가 실패: $e')));
    }
  }

  // 참가자 수정(상태/결제만 변경)
  Future<void> _editParticipant(Participant participant) async {
    final messenger = ScaffoldMessenger.of(context);
    final eventService = Provider.of<EventService>(context, listen: false);
    String status = participant.status ?? 'pending';
    String paymentStatus = participant.isPaid ? 'paid' : 'unpaid';
    final commentCtrl = TextEditingController(text: participant.notes ?? '');

    final ok = await showDialog<bool>(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('참가자 수정'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            DropdownButtonFormField<String>(
              value: status,
              isExpanded: true,
              decoration: const InputDecoration(labelText: '상태'),
              items: participantStatusOptions.entries
                  .map(
                    (e) => DropdownMenuItem<String>(
                      value: e.key,
                      child: Text(e.value),
                    ),
                  )
                  .toList(),
              onChanged: (v) => status = v ?? 'pending',
            ),
            const SizedBox(height: 8),
            DropdownButtonFormField<String>(
              value: paymentStatus,
              isExpanded: true,
              decoration: const InputDecoration(labelText: '결제'),
              items: paymentStatusOptions.entries
                  .map(
                    (e) => DropdownMenuItem<String>(
                      value: e.key,
                      child: Text(e.value),
                    ),
                  )
                  .toList(),
              onChanged: (v) => paymentStatus = v ?? 'unpaid',
            ),
            const SizedBox(height: 8),
            TextField(
              controller: commentCtrl,
              decoration: const InputDecoration(labelText: '비고(선택)'),
              maxLines: 2,
            ),
          ],
        ),
        actions: DialogActions.confirm(
          onCancel: () => Navigator.of(ctx).pop(false),
          onConfirm: () => Navigator.of(ctx).pop(true),
          confirmText: '저장',
        ),
      ),
    );

    if (ok != true) return;

    try {
      setState(() => _isLoading = true);
      final payload = <String, dynamic>{
        'status': status,
        'paymentStatus': paymentStatus,
      };
      if (commentCtrl.text.trim().isNotEmpty) {
        payload['comment'] = commentCtrl.text.trim();
      }
      await eventService.updateParticipant(
        widget.event.id,
        participant.id,
        payload,
      );
      await _loadEventDetails();
      messenger.showSnackBar(const SnackBar(content: Text('참가자 정보가 수정되었습니다')));
    } catch (e) {
      setState(() => _isLoading = false);
      messenger.showSnackBar(SnackBar(content: Text('참가자 수정 실패: $e')));
    }
  }

  // 참가자 삭제: 스와이프(Dismissible)로 대체됨

  // 점수 삭제
  void _deleteScore(Score score) {
    showDialog(
      context: context,
      builder: (dialogContext) => AlertDialog(
        title: const Text('점수 삭제'),
        content: const Text('이 점수를 정말 삭제하시겠습니까?'),
        actions: DialogActions.confirm(
          onCancel: () => Navigator.of(dialogContext).pop(),
          onConfirm: () async {
            final navigator = Navigator.of(dialogContext);
            final messenger = ScaffoldMessenger.of(dialogContext);
            final eventService = Provider.of<EventService>(
              dialogContext,
              listen: false,
            );
            navigator.pop();

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

            try {
              await eventService.deleteScore(widget.event.id, score.id);
              if (mounted) {
                setState(() {
                  _scores.removeWhere((s) => s.id == score.id);
                  _isLoading = false;
                });
                messenger.showSnackBar(
                  const SnackBar(content: Text('점수가 삭제되었습니다')),
                );
              }
            } catch (e) {
              if (mounted) {
                setState(() {
                  _isLoading = false;
                });
                messenger.showSnackBar(
                  SnackBar(content: Text('점수 삭제에 실패했습니다: $e')),
                );
              }
            }
          },
          destructive: true,
          confirmText: '삭제',
        ),
      ),
    );
  }
}
