package com.example.shiftalarm

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.example.shiftalarm.databinding.FragmentSettingsLabBinding
import kotlinx.coroutines.launch
import kotlinx.coroutines.delay

class FragmentSettingsLab : Fragment() {

    private var _binding: FragmentSettingsLabBinding? = null
    private val binding get() = _binding!!
    private var isInitialLoad = true

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentSettingsLabBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        setupSpinner()
        loadAnnualLeave()
        loadSaturdayOvertime()
    }

    private fun setupSpinner() {
        // 1~25일 선택 가능한 어댑터 설정 (One UI 8.5 스타일)
        val daysList = (1..25).map { "${it}일" }.toList()
        val adapter = ArrayAdapter(requireContext(), R.layout.spinner_item_oneui, daysList)
        adapter.setDropDownViewResource(R.layout.spinner_dropdown_oneui)
        binding.spinnerTotalDays.adapter = adapter
        
        // 선택 시 자동 저장
        binding.spinnerTotalDays.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                if (!isInitialLoad) {
                    val totalDays = position + 1 // 0-indexed to actual days
                    saveAnnualLeave(totalDays)
                }
            }
            
            override fun onNothingSelected(parent: AdapterView<*>?) {
                // Do nothing
            }
        }
    }

    private fun loadAnnualLeave() {
        lifecycleScope.launch {
            isInitialLoad = true
            val repo = ShiftRepository(requireContext())
            
            val annualLeave = repo.getAnnualLeave()
            annualLeave?.let {
                // 저장된 값이 있으면 해당 위치 선택 (0-indexed)
                binding.spinnerTotalDays.setSelection(it.totalDays.toInt() - 1)
                binding.tvRemainingDays.text = formatRemainingDays(it.remainingDays)
            } ?: run {
                // Default: 15 days (index 14)
                binding.spinnerTotalDays.setSelection(14)
                binding.tvRemainingDays.text = "15"
            }
            
            // 초기 로드 완료 후 플래그 변경 (약간의 딜레이로 초기 선택 이벤트 방지)
            delay(300)
            isInitialLoad = false
        }
    }

    private fun saveAnnualLeave(totalDays: Int) {
        lifecycleScope.launch {
            val repo = ShiftRepository(requireContext())
            
            repo.recalculateAndSaveAnnualLeave(totalDays.toFloat())
            
            val updated = repo.getAnnualLeave()
            updated?.let {
                binding.tvRemainingDays.text = formatRemainingDays(it.remainingDays)
                Toast.makeText(requireContext(), "총 연차 ${totalDays}일로 저장되었습니다 (남은 연차: ${formatRemainingDays(it.remainingDays)}일)", Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 남은 연차 표시 형식 개선
     * - 정수면 정수로 표시 (예: 22)
     * - 소숫점 있으면 소숫점 표시 (예: 21.5)
     */
    private fun formatRemainingDays(days: Float): String {
        return if (days == days.toInt().toFloat()) {
            // 정수인 경우
            days.toInt().toString()
        } else {
            // 소숫점이 있는 경우 (0.5 등)
            String.format("%.1f", days)
        }
    }

    private fun loadSaturdayOvertime() {
        lifecycleScope.launch {
            val repo = ShiftRepository(requireContext())
            val overtimeHours = repo.getSaturdayOvertimeHours()
            binding.tvSaturdayOvertime.text = "$overtimeHours"
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
