"""
과거 일자 수동 추가 다이얼로그.

캘린더 우클릭 → "기록 추가"에서 호출. 출/퇴근 시각 + 점심/저녁 + 메모 입력.
"""
from __future__ import annotations
from PyQt5.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel,
                             QPushButton, QTimeEdit, QCheckBox, QLineEdit,
                             QMessageBox)
from PyQt5.QtCore import QTime, Qt

from core.i18n import tr
from ui.styles import apply_dark_titlebar


class PastRecordDialog(QDialog):
    """과거 일자 근무 기록 입력."""

    def __init__(self, parent=None, date_str: str = ''):
        super().__init__(parent)
        self.date_str = date_str
        self.setWindowTitle(tr('past_record.dialog_title', date=date_str))
        self.setModal(True)
        self.setFixedSize(380, 348)

        layout = QVBoxLayout()
        layout.setSpacing(8)
        layout.setContentsMargins(20, 16, 20, 16)

        info = QLabel(tr('past_record.info', date=date_str))
        info.setStyleSheet("font-weight: bold; padding-bottom: 6px;")
        layout.addWidget(info)

        # 출근
        ci_row = QHBoxLayout()
        ci_row.addWidget(QLabel(tr('past_record.label_clock_in')))
        self.clock_in_edit = QTimeEdit()
        self.clock_in_edit.setDisplayFormat("HH:mm")
        self.clock_in_edit.setTime(QTime(9, 0))
        ci_row.addWidget(self.clock_in_edit)
        ci_row.addStretch()
        layout.addLayout(ci_row)

        # 퇴근
        co_row = QHBoxLayout()
        co_row.addWidget(QLabel(tr('past_record.label_clock_out')))
        self.clock_out_check = QCheckBox(tr('past_record.check_clock_out'))
        self.clock_out_check.setChecked(True)
        self.clock_out_edit = QTimeEdit()
        self.clock_out_edit.setDisplayFormat("HH:mm")
        self.clock_out_edit.setTime(QTime(18, 0))
        self.clock_out_check.toggled.connect(self.clock_out_edit.setEnabled)
        co_row.addWidget(self.clock_out_check)
        co_row.addWidget(self.clock_out_edit)
        co_row.addStretch()
        layout.addLayout(co_row)

        # 익일 퇴근 안내 (퇴근 < 출근이면 표시)
        self.overnight_note = QLabel('')
        self.overnight_note.setObjectName("note_text")
        self.overnight_note.setVisible(False)
        layout.addWidget(self.overnight_note)
        self.clock_in_edit.timeChanged.connect(self._refresh_overnight_note)
        self.clock_out_edit.timeChanged.connect(self._refresh_overnight_note)
        self.clock_out_check.toggled.connect(self._refresh_overnight_note)

        # 점심/저녁
        meal_row = QHBoxLayout()
        self.lunch_check = QCheckBox(tr('past_record.check_lunch'))
        self.lunch_check.setChecked(True)
        self.dinner_check = QCheckBox(tr('past_record.check_dinner'))
        meal_row.addWidget(self.lunch_check)
        meal_row.addWidget(self.dinner_check)
        meal_row.addStretch()
        layout.addLayout(meal_row)

        # 메모
        layout.addWidget(QLabel(tr('past_record.label_memo')))
        self.memo_edit = QLineEdit()
        self.memo_edit.setPlaceholderText(tr('past_record.memo_placeholder'))
        layout.addWidget(self.memo_edit)

        layout.addStretch()

        # 버튼
        btn_row = QHBoxLayout()
        btn_row.addStretch()
        ok_btn = QPushButton(tr('btn.save'))
        ok_btn.setObjectName("btn_primary")
        ok_btn.clicked.connect(self._validate_and_accept)
        cancel_btn = QPushButton(tr('btn.cancel'))
        cancel_btn.clicked.connect(self.reject)
        btn_row.addWidget(ok_btn)
        btn_row.addWidget(cancel_btn)
        layout.addLayout(btn_row)

        self.setLayout(layout)
        apply_dark_titlebar(self)

    def _refresh_overnight_note(self):
        """퇴근이 출근보다 이르면 익일 퇴근으로 해석됨을 표시."""
        if not self.clock_out_check.isChecked():
            self.overnight_note.setVisible(False)
            return
        ci = self.clock_in_edit.time()
        co = self.clock_out_edit.time()
        if co >= ci:
            self.overnight_note.setVisible(False)
            return
        total_min = ci.secsTo(co) // 60 + 24 * 60  # 익일까지
        self.overnight_note.setText(tr('edit.overnight_note',
                                        hours=total_min // 60, minutes=total_min % 60))
        self.overnight_note.setVisible(True)

    def _validate_and_accept(self):
        # 퇴근 < 출근은 익일 퇴근(야근)으로 허용. 같은 시각만 반려.
        if self.clock_out_check.isChecked():
            if self.clock_out_edit.time() == self.clock_in_edit.time():
                QMessageBox.warning(self, tr('past_record.input_error_title'),
                                     tr('past_record.input_error_body'))
                return
        self.accept()

    def get_data(self) -> dict:
        ci = self.clock_in_edit.time().toPyTime()
        data = {
            'clock_in': f"{ci.hour:02d}:{ci.minute:02d}:00",
            'lunch': self.lunch_check.isChecked(),
            'dinner': self.dinner_check.isChecked(),
            'memo': self.memo_edit.text().strip(),
        }
        if self.clock_out_check.isChecked():
            co = self.clock_out_edit.time().toPyTime()
            data['clock_out'] = f"{co.hour:02d}:{co.minute:02d}:00"
        return data
