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

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

class ScoreFormScreen extends StatefulWidget {
  final String eventId;
  final Score? score; // null이면 새 점수 추가, 아니면 점수 수정
  final List<Participant> participants;
  final int gameCount; // 이벤트의 게임 수 (추가 모드에서 사용)

  const ScoreFormScreen({
    super.key,
    required this.eventId,
    this.score,
    required this.participants,
    this.gameCount = 1,
  });

  @override
  State<ScoreFormScreen> createState() => _ScoreFormScreenState();
}

class _ScoreFormScreenState extends State<ScoreFormScreen> {
  final _formKey = GlobalKey<FormState>();
  bool _isLoading = false;

  // 폼 필드 컨트롤러
  final _notesController = TextEditingController();
  final _totalScoreController = TextEditingController(); // 총점 컨트롤러 추가
  List<TextEditingController> _gameScoreControllers = [];
  List<TextEditingController> _gameHandicapControllers = [];

  // 점수 데이터
  String? _selectedParticipantId;
  DateTime _scoreDate = DateTime.now();
  int _totalScore = 0;
  final _handicapController = TextEditingController(); // 핸디캡 컨트롤러

  @override
  void initState() {
    super.initState();

    // 수정 모드인 경우 기존 데이터 로드
    if (widget.score != null) {
      _notesController.text = widget.score!.notes ?? '';
      // 편집 모드: 기존 점수의 participantId를 우선 사용, 없으면 memberId와 매칭되는 참가자 id를 탐색
      _selectedParticipantId = widget.score!.participantId;
      if (_selectedParticipantId == null || _selectedParticipantId!.isEmpty) {
        final match = widget.participants.firstWhere(
          (p) => p.memberId == widget.score!.memberId,
          orElse: () => widget.participants.isNotEmpty
              ? widget.participants.first
              : Participant(id: '', eventId: widget.eventId, memberId: '', name: '알 수 없음'),
        );
        _selectedParticipantId = match.id;
      }
      _scoreDate = widget.score!.date;
      _totalScoreController.text = widget.score!.totalScore.toString();
      _totalScore = widget.score!.totalScore;

      // 핸디캡 설정
      if (widget.score!.handicap != null) {
        _handicapController.text = widget.score!.handicap.toString();
      }
      // 편집 모드에서는 게임별 입력을 사용하지 않음(단일 점수 수정)
      _gameScoreControllers = const [];
      _gameHandicapControllers = const [];
    } else {
      // 추가 모드: 참가자 유무와 무관하게 gameCount를 기준으로 컨트롤러 생성
      if (widget.participants.isNotEmpty) {
        // 새 점수 추가 시 기본 선택: participant.id 사용
        _selectedParticipantId = widget.participants.first.id;
      }
      final count = widget.gameCount > 0 ? widget.gameCount : 1;
      _gameScoreControllers = List.generate(
        count,
        (_) => TextEditingController(),
      );
      _gameHandicapControllers = List.generate(
        count,
        (_) => TextEditingController(),
      );
    }
  }

  @override
  void dispose() {
    _notesController.dispose();
    _handicapController.dispose();
    _totalScoreController.dispose();
    for (var controller in _gameScoreControllers) {
      controller.dispose();
    }
    for (var controller in _gameHandicapControllers) {
      controller.dispose();
    }
    super.dispose();
  }

  // 총점 계산은 편집 모드에서만 필요(단일 필드)
  void _calculateTotalScore() {
    setState(() {
      _totalScore = int.tryParse(_totalScoreController.text) ?? 0;
    });
  }

  // 점수 저장
  Future<void> _saveScore() async {
    if (!_formKey.currentState!.validate()) {
      return;
    }

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

    try {
      final eventService = Provider.of<EventService>(context, listen: false);

      // 공통 메타 (add는 participantId/score/gameNumber만 필수)
      final common = {
        'eventId': widget.eventId,
        // notes/date는 백엔드 add에서 사용하지 않으므로 제외
      };

      if (widget.score == null) {
        // 새 점수 추가: 게임 수 만큼 배치 생성 (게임별 핸디캡 포함)
        for (int i = 0; i < _gameScoreControllers.length; i++) {
          final scoreText = _gameScoreControllers[i].text.trim();
          final handicapText = _gameHandicapControllers[i].text.trim();
          if (scoreText.isEmpty && handicapText.isEmpty) {
            continue; // 완전 비어있으면 건너뜀
          }
          final gameScore = int.tryParse(scoreText) ?? 0;
          final gameHandicap = int.tryParse(handicapText) ?? 0;
          final payload = {
            ...common,
            'participantId': _selectedParticipantId,
            'gameNumber': i + 1,
            'score': gameScore,
            'handicap': gameHandicap,
          };
          await eventService.addScore(widget.eventId, payload);
        }
        if (mounted) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('점수가 추가되었습니다')));
        }
      } else {
        // 기존 점수 수정: 서버 요구 필드와 날짜 보존
        final total = int.tryParse(_totalScoreController.text) ?? 0;
        final payload = {
          ...common,
          if (_selectedParticipantId != null) 'participantId': _selectedParticipantId,
          'gameNumber': widget.score!.gameNumber ?? 1,
          'score': total,
          'totalScore': total, // 호환 목적
          'handicap': _handicapController.text.isEmpty
              ? null
              : int.parse(_handicapController.text),
          'date': _scoreDate.toIso8601String(),
        };
        await eventService.updateScore(widget.eventId, widget.score!.id, payload);
        if (mounted) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('점수가 수정되었습니다')));
        }
      }

      if (mounted) {
        Navigator.of(context).pop(true); // 성공 결과와 함께 이전 화면으로 돌아가기
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });

        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('점수 저장에 실패했습니다: $e')));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.score == null ? '점수 추가' : '점수 수정'),
        actions: [
          IconButton(icon: const Icon(Icons.save), onPressed: _saveScore),
        ],
      ),
      body: _isLoading
          ? const LoadingIndicator()
          : SingleChildScrollView(
              padding: const EdgeInsets.all(16.0),
              child: Form(
                key: _formKey,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 기본 정보 섹션
                    _buildSectionTitle('기본 정보'),

                    // 참가자 선택
                    DropdownButtonFormField<String>(
                      key: const Key('score_form_participant_dropdown'),
                      value: _selectedParticipantId,
                      decoration: const InputDecoration(labelText: '참가자 *'),
                      isExpanded: true,
                      items: widget.participants.map((participant) {
                        return DropdownMenuItem(
                          value: participant.id,
                          child: Text(
                            participant.name ?? '이름 없음',
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        );
                      }).toList(),
                      onChanged: (value) {
                        setState(() {
                          _selectedParticipantId = value;
                        });
                      },
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '참가자를 선택해주세요';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 16),

                    // 날짜 선택
                    ListTile(
                      title: const Text('점수 기록 날짜 *'),
                      subtitle: Text(
                        DateFormat('yyyy년 MM월 dd일').format(_scoreDate),
                      ),
                      trailing: const Icon(Icons.calendar_today),
                      onTap: () async {
                        final date = await showDatePicker(
                          context: context,
                          initialDate: _scoreDate,
                          firstDate: DateTime(2020),
                          lastDate: DateTime(2030),
                        );

                        if (date != null && mounted) {
                          setState(() {
                            _scoreDate = date;
                          });
                        }
                      },
                    ),
                    const SizedBox(height: 24),

                    // 점수 입력 섹션
                    _buildSectionTitle('점수 입력'),

                    // 추가 모드: 게임 수만큼 (점수 + 핸디캡 + 합계) 행, 수정 모드: 단일 점수/핸디캡
                    if (widget.score == null) ...[
                      // 런타임에서도 리스트 길이 보정 (hot reload/동적 변경 대비)
                      _ensureGameControllersLength(
                        widget.gameCount > 0 ? widget.gameCount : 1,
                      ),
                      Column(
                        children: [
                          for (int i = 0; i < _gameScoreControllers.length; i++)
                            Padding(
                              padding: const EdgeInsets.only(bottom: 12.0),
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: [
                                  Expanded(
                                    child: TextFormField(
                                      controller: _gameScoreControllers[i],
                                      keyboardType: TextInputType.number,
                                      decoration: InputDecoration(
                                        labelText: '${i + 1}G 점수',
                                        hintText: '0-300',
                                        prefixIcon: const Icon(Icons.score),
                                      ),
                                      validator: (value) {
                                        if (value != null && value.isNotEmpty) {
                                          final score = int.tryParse(value);
                                          if (score == null) {
                                            return '숫자만 입력';
                                          }
                                          if (score < 0 || score > 300) {
                                            return '0-300';
                                          }
                                        }
                                        return null;
                                      },
                                      onChanged: (_) => setState(() {}),
                                    ),
                                  ),
                                  const SizedBox(width: 8),
                                  Expanded(
                                    child: TextFormField(
                                      controller: _gameHandicapControllers[i],
                                      keyboardType: TextInputType.number,
                                      decoration: const InputDecoration(
                                        labelText: '핸디캡',
                                        prefixIcon: Icon(
                                          Icons.add_circle_outline,
                                        ),
                                      ),
                                      validator: (value) {
                                        if (value != null && value.isNotEmpty) {
                                          final handicap = int.tryParse(value);
                                          if (handicap == null) {
                                            return '숫자만 입력';
                                          }
                                        }
                                        return null;
                                      },
                                      onChanged: (_) => setState(() {}),
                                    ),
                                  ),
                                  const SizedBox(width: 8),
                                  _PerRowSum(
                                    scoreText:
                                        (i < _gameScoreControllers.length)
                                        ? _gameScoreControllers[i].text
                                        : '',
                                    handicapText:
                                        (i < _gameHandicapControllers.length)
                                        ? _gameHandicapControllers[i].text
                                        : '',
                                  ),
                                ],
                              ),
                            ),
                          // 전체 합계 표시
                          const SizedBox(height: 8),
                          _TotalsSummary(
                            totalScore: _sumGameScores(),
                            totalWithHandicap: _sumGameScoresWithHandicap(),
                          ),
                        ],
                      ),
                    ] else
                      TextFormField(
                        controller: _totalScoreController,
                        keyboardType: TextInputType.number,
                        decoration: const InputDecoration(
                          labelText: '총점 *',
                          hintText: '게임 총점을 입력하세요',
                          prefixIcon: Icon(Icons.score),
                        ),
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return '총점을 입력해주세요';
                          }
                          final score = int.tryParse(value);
                          if (score == null) {
                            return '숫자만 입력해주세요';
                          }
                          if (score < 0 || score > 300) {
                            return '0-300 사이의 값을 입력해주세요';
                          }
                          return null;
                        },
                        onChanged: (_) => _calculateTotalScore(),
                      ),
                    const SizedBox(height: 16),

                    const SizedBox(height: 16),

                    // 수정 모드에서만 단일 핸디캡과 합계 표시
                    if (widget.score != null) ...[
                      TextFormField(
                        controller: _handicapController,
                        keyboardType: TextInputType.number,
                        decoration: const InputDecoration(
                          labelText: '핸디캡',
                          hintText: '핸디캡 점수를 입력하세요',
                          prefixIcon: Icon(Icons.add_circle_outline),
                        ),
                        validator: (value) {
                          if (value != null && value.isNotEmpty) {
                            final handicap = int.tryParse(value);
                            if (handicap == null) {
                              return '숫자만 입력해주세요';
                            }
                          }
                          return null;
                        },
                        onChanged: (_) => setState(() {}),
                      ),
                      Padding(
                        padding: const EdgeInsets.symmetric(vertical: 8.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            const Text(
                              '핸디캡 포함 총점: ',
                              style: TextStyle(fontWeight: FontWeight.bold),
                            ),
                            Text(
                              '${_totalScore + (int.tryParse(_handicapController.text) ?? 0)}',
                              style: const TextStyle(
                                fontWeight: FontWeight.bold,
                                color: Colors.green,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                    const SizedBox(height: 24),

                    // 메모 섹션
                    _buildSectionTitle('추가 정보'),

                    // 메모
                    TextFormField(
                      controller: _notesController,
                      decoration: const InputDecoration(
                        labelText: '메모',
                        hintText: '점수에 대한 메모를 입력하세요',
                      ),
                      maxLines: 3,
                    ),
                    const SizedBox(height: 32),

                    // 저장 버튼
                    SizedBox(
                      width: double.infinity,
                      child: ElevatedButton(
                        onPressed: _saveScore,
                        style: ElevatedButton.styleFrom(
                          padding: const EdgeInsets.symmetric(vertical: 16),
                        ),
                        child: Text(
                          widget.score == null ? '점수 추가' : '점수 수정',
                          style: const TextStyle(fontSize: 16),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
    );
  }

  // 프레임 입력 UI 제거됨

  // 섹션 제목 위젯
  Widget _buildSectionTitle(String title) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          title,
          style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
        ),
        const Divider(),
        const SizedBox(height: 8),
      ],
    );
  }

  // 컨트롤러 리스트 길이 보정 (gameCount 변화나 hot reload 대비)
  Widget _ensureGameControllersLength(int desired) {
    if (desired < 1) desired = 1;
    // 점수 컨트롤러 보정
    while (_gameScoreControllers.length < desired) {
      _gameScoreControllers.add(TextEditingController());
    }
    if (_gameScoreControllers.length > desired) {
      _gameScoreControllers = _gameScoreControllers.sublist(0, desired);
    }
    // 핸디캡 컨트롤러 보정
    while (_gameHandicapControllers.length < desired) {
      _gameHandicapControllers.add(TextEditingController());
    }
    if (_gameHandicapControllers.length > desired) {
      _gameHandicapControllers = _gameHandicapControllers.sublist(0, desired);
    }
    return const SizedBox.shrink();
  }

  // 합계 계산: 점수 합
  int _sumGameScores() {
    int sum = 0;
    for (final c in _gameScoreControllers) {
      final v = int.tryParse(c.text.trim());
      if (v != null) sum += v;
    }
    return sum;
  }

  // 합계 계산: 점수+핸디캡 합
  int _sumGameScoresWithHandicap() {
    int sum = 0;
    for (int i = 0; i < _gameScoreControllers.length; i++) {
      final s = int.tryParse(_gameScoreControllers[i].text.trim()) ?? 0;
      final hText = (i < _gameHandicapControllers.length)
          ? _gameHandicapControllers[i].text.trim()
          : '';
      final h = int.tryParse(hText) ?? 0;
      sum += s + h;
    }
    return sum;
  }
}

// 행 우측 합계 표시 위젯
class _PerRowSum extends StatelessWidget {
  final String scoreText;
  final String handicapText;
  const _PerRowSum({required this.scoreText, required this.handicapText});

  @override
  Widget build(BuildContext context) {
    final score = int.tryParse(scoreText.trim()) ?? 0;
    final handicap = int.tryParse(handicapText.trim()) ?? 0;
    final total = score + handicap;
    return SizedBox(
      width: 64,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          const Text('합계'),
          Text(
            '$total',
            style: const TextStyle(
              fontWeight: FontWeight.bold,
              color: Colors.blue,
              fontSize: 16,
            ),
          ),
        ],
      ),
    );
  }
}

// 전체 합계 표시 위젯
class _TotalsSummary extends StatelessWidget {
  final int totalScore;
  final int totalWithHandicap;
  const _TotalsSummary({
    required this.totalScore,
    required this.totalWithHandicap,
  });

  @override
  Widget build(BuildContext context) {
    return Align(
      alignment: Alignment.centerRight,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text('총점: '),
              Text(
                '$totalScore',
                style: const TextStyle(fontWeight: FontWeight.bold),
              ),
            ],
          ),
          const SizedBox(height: 4),
          Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text('핸디캡 포함 총점: '),
              Text(
                '$totalWithHandicap',
                style: const TextStyle(
                  fontWeight: FontWeight.bold,
                  color: Colors.green,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
