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

import '../../services/club_service.dart';
import '../../services/member_service.dart';
import '../../services/event_service.dart';
import '../../services/score_service.dart';

class ScoreEntryScreen extends StatefulWidget {
  final String? memberId;
  final String? eventId;

  const ScoreEntryScreen({
    super.key,
    this.memberId,
    this.eventId,
  });

  @override
  State<ScoreEntryScreen> createState() => _ScoreEntryScreenState();
}

class _ScoreEntryScreenState extends State<ScoreEntryScreen> {
  final _formKey = GlobalKey<FormState>();
  bool _isLoading = false;
  
  // 점수 입력 관련 상태
  final List<TextEditingController> _frameControllers = List.generate(
    10,
    (_) => TextEditingController(),
  );
  final TextEditingController _notesController = TextEditingController();
  
  // 선택된 회원 및 이벤트
  String? _selectedMemberId;
  String? _selectedEventId;
  DateTime _selectedDate = DateTime.now();
  
  @override
  void initState() {
    super.initState();
    _selectedMemberId = widget.memberId;
    _selectedEventId = widget.eventId;
  }

  @override
  void dispose() {
    for (var controller in _frameControllers) {
      controller.dispose();
    }
    _notesController.dispose();
    super.dispose();
  }

  // 총점 계산
  int _calculateTotalScore() {
    int total = 0;
    for (var controller in _frameControllers) {
      final value = int.tryParse(controller.text) ?? 0;
      total += value;
    }
    return total;
  }

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

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

    // await 전에 필요한 파생 객체 캡처 (catch에서도 사용 가능하도록 try 밖)
    final navigator = Navigator.of(context);
    final messenger = ScaffoldMessenger.of(context);

    try {
      final scoreService = Provider.of<ScoreService>(context, listen: false);
      final clubService = Provider.of<ClubService>(context, listen: false);
      
      if (clubService.currentClub != null) {
        // 프레임 점수 배열 생성
        final frames = _frameControllers
            .map((controller) => int.tryParse(controller.text) ?? 0)
            .toList();
        
        // 총점 계산
        final totalScore = _calculateTotalScore();
        
        // 점수 데이터 생성
        final scoreData = {
          'memberId': _selectedMemberId,
          'eventId': _selectedEventId,
          'clubId': clubService.currentClub!.id,
          'frames': frames,
          'totalScore': totalScore,
          'date': _selectedDate.toIso8601String(),
          'notes': _notesController.text.isNotEmpty ? _notesController.text : null,
        };
        
        // 점수 저장
        await scoreService.addScore(scoreData);
        // 성공 알림 및 화면 닫기
        messenger.showSnackBar(
          const SnackBar(content: Text('점수가 저장되었습니다')),
        );
        navigator.pop();
      }
    } catch (e) {
      // 에러 알림 (사전 캡처한 messenger 사용)
      messenger.showSnackBar(
        SnackBar(content: Text('점수 저장에 실패했습니다: $e')),
      );
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('점수 입력'),
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : Form(
              key: _formKey,
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 회원 선택
                    _buildMemberSelector(),
                    const SizedBox(height: 16),
                    
                    // 이벤트 선택
                    _buildEventSelector(),
                    const SizedBox(height: 16),
                    
                    // 날짜 선택
                    _buildDateSelector(),
                    const SizedBox(height: 24),
                    
                    // 프레임 점수 입력
                    _buildFrameInputs(),
                    const SizedBox(height: 24),
                    
                    // 총점 표시
                    _buildTotalScore(),
                    const SizedBox(height: 16),
                    
                    // 메모 입력
                    TextFormField(
                      controller: _notesController,
                      decoration: const InputDecoration(
                        labelText: '메모',
                        border: OutlineInputBorder(),
                      ),
                      maxLines: 3,
                    ),
                    const SizedBox(height: 24),
                    
                    // 저장 버튼
                    SizedBox(
                      width: double.infinity,
                      height: 50,
                      child: ElevatedButton(
                        onPressed: _saveScore,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.blue,
                          foregroundColor: Colors.white,
                        ),
                        child: const Text('점수 저장'),
                      ),
                    ),
                  ],
                ),
              ),
            ),
    );
  }

  Widget _buildMemberSelector() {
    return Consumer<MemberService>(
      builder: (context, memberService, _) {
        final members = memberService.members;
        
        return DropdownButtonFormField<String>(
          key: const Key('score_entry_member_dropdown'),
          decoration: const InputDecoration(
            labelText: '회원 선택',
            border: OutlineInputBorder(),
          ),
          value: _selectedMemberId,
          isExpanded: true,
          items: members.map((member) {
            return DropdownMenuItem<String>(
              value: member.id,
              child: Text(
                member.name,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            );
          }).toList(),
          onChanged: (value) {
            setState(() {
              _selectedMemberId = value;
            });
          },
          validator: (value) {
            if (value == null || value.isEmpty) {
              return '회원을 선택해주세요';
            }
            return null;
          },
        );
      },
    );
  }

  Widget _buildEventSelector() {
    return Consumer<EventService>(
      builder: (context, eventService, _) {
        final events = eventService.events;
        
        return DropdownButtonFormField<String>(
          key: const Key('score_entry_event_dropdown'),
          decoration: const InputDecoration(
            labelText: '이벤트 선택 (선택사항)',
            border: OutlineInputBorder(),
          ),
          value: _selectedEventId,
          isExpanded: true,
          items: [
            const DropdownMenuItem<String>(
              value: null,
              child: Text('이벤트 없음'),
            ),
            ...events.map((event) {
              return DropdownMenuItem<String>(
                value: event.id,
                child: Text(
                  event.title,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              );
            }),
          ],
          onChanged: (value) {
            setState(() {
              _selectedEventId = value;
            });
          },
        );
      },
    );
  }

  Widget _buildDateSelector() {
    return InkWell(
      onTap: () async {
        final pickedDate = await showDatePicker(
          context: context,
          initialDate: _selectedDate,
          firstDate: DateTime.now().subtract(const Duration(days: 365)),
          lastDate: DateTime.now(),
        );
        
        if (pickedDate != null) {
          setState(() {
            _selectedDate = pickedDate;
          });
        }
      },
      child: InputDecorator(
        decoration: const InputDecoration(
          labelText: '날짜',
          border: OutlineInputBorder(),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(DateFormat('yyyy년 MM월 dd일').format(_selectedDate)),
            const Icon(Icons.calendar_today),
          ],
        ),
      ),
    );
  }

  Widget _buildFrameInputs() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '프레임 점수',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 8),
        GridView.builder(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 5,
            childAspectRatio: 1.5,
            crossAxisSpacing: 8,
            mainAxisSpacing: 8,
          ),
          itemCount: 10,
          itemBuilder: (context, index) {
            return TextFormField(
              controller: _frameControllers[index],
              keyboardType: TextInputType.number,
              textAlign: TextAlign.center,
              decoration: InputDecoration(
                labelText: '${index + 1}프레임',
                border: const OutlineInputBorder(),
              ),
              onChanged: (_) {
                setState(() {});
              },
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '입력';
                }
                final score = int.tryParse(value);
                if (score == null) {
                  return '숫자';
                }
                if (score < 0 || score > 30) {
                  return '0-30';
                }
                return null;
              },
            );
          },
        ),
      ],
    );
  }

  Widget _buildTotalScore() {
    final totalScore = _calculateTotalScore();
    
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.blue.shade50,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.blue.shade200),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          const Text(
            '총점',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          Text(
            '$totalScore',
            style: const TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.bold,
              color: Colors.blue,
            ),
          ),
        ],
      ),
    );
  }
}
