/**
 * 근태관리 (AttendanceManagement) 타입 정의
 */

// ============================================
// 근태 상태 타입
// ============================================

export type AttendanceStatus =
  | 'notYetIn'
  | 'onTime'
  | 'late'
  | 'absent'
  | 'vacation'
  | 'businessTrip'
  | 'fieldWork'
  | 'overtime'
  | 'remote';

// 근태 상태 라벨
export const ATTENDANCE_STATUS_LABELS: Record<AttendanceStatus, string> = {
  notYetIn: '미출근',
  onTime: '정시 출근',
  late: '지각',
  absent: '결근',
  vacation: '휴가',
  businessTrip: '출장',
  fieldWork: '외근',
  overtime: '연장근무',
  remote: '재택근무',
};

// 근태 상태 색상
export const ATTENDANCE_STATUS_COLORS: Record<AttendanceStatus, string> = {
  notYetIn: 'bg-gray-100 text-gray-700',
  onTime: 'bg-green-100 text-green-700',
  late: 'bg-yellow-100 text-yellow-700',
  absent: 'bg-red-100 text-red-700',
  vacation: 'bg-blue-100 text-blue-700',
  businessTrip: 'bg-purple-100 text-purple-700',
  fieldWork: 'bg-orange-100 text-orange-700',
  overtime: 'bg-indigo-100 text-indigo-700',
  remote: 'bg-cyan-100 text-cyan-700',
};

// ============================================
// 필터/정렬 옵션
// ============================================

export type FilterOption = 'all' | AttendanceStatus;

export const FILTER_OPTIONS: { value: FilterOption; label: string }[] = [
  { value: 'all', label: '전체' },
  { value: 'notYetIn', label: '미출근' },
  { value: 'onTime', label: '정시 출근' },
  { value: 'late', label: '지각' },
  { value: 'absent', label: '결근' },
  { value: 'vacation', label: '휴가' },
  { value: 'businessTrip', label: '출장' },
  { value: 'fieldWork', label: '외근' },
  { value: 'overtime', label: '연장근무' },
  { value: 'remote', label: '재택근무' },
];

export type SortOption = 'rank' | 'deptAsc' | 'deptDesc' | 'nameAsc' | 'nameDesc' | 'dateDesc' | 'dateAsc';

export const SORT_OPTIONS: { value: SortOption; label: string }[] = [
  { value: 'dateDesc', label: '날짜 최신순' },
  { value: 'dateAsc', label: '날짜 오래된순' },
  { value: 'rank', label: '직급순' },
  { value: 'deptAsc', label: '부서 오름차순' },
  { value: 'deptDesc', label: '부서 내림차순' },
  { value: 'nameAsc', label: '이름 오름차순' },
  { value: 'nameDesc', label: '이름 내림차순' },
];

// ============================================
// 사유 유형 (문서 유형)
// ============================================

export type ReasonType = 'businessTripRequest' | 'vacationRequest' | 'fieldWorkRequest' | 'overtimeRequest';

export const REASON_TYPE_LABELS: Record<ReasonType, string> = {
  businessTripRequest: '출장신청서',
  vacationRequest: '휴가신청서',
  fieldWorkRequest: '외근신청서',
  overtimeRequest: '연장근무신청서',
};

// ============================================
// API 응답 타입 (백엔드)
// ============================================

export interface AttendanceApiData {
  id: number;
  tenant_id: number;
  user_id: number;
  base_date: string;
  status: AttendanceStatus;
  // Model $appends로 인해 최상위 레벨에 추가되는 필드
  check_in?: string | null;
  check_out?: string | null;
  break_minutes?: number | null;
  json_details: {
    check_in?: string;
    check_out?: string;
    break_time?: string;
    work_minutes?: number;
    overtime_minutes?: number;
    late_minutes?: number;
    early_leave_minutes?: number;
    vacation_type?: string;
    gps_data?: Record<string, unknown>;
    external_work?: Record<string, unknown>;
    reason?: {
      type: ReasonType;
      label: string;
      documentId?: string;
    };
  } | null;
  remarks?: string;
  created_by?: number;
  updated_by?: number;
  created_at: string;
  updated_at: string;
  user?: {
    id: number;
    name: string;
    email?: string;
    // API는 tenant_profiles 배열로 반환 (with 쿼리에서 tenantProfiles 로드)
    tenant_profiles?: Array<{
      id: number;
      tenant_id: number;
      user_id: number;
      department_id?: number;
      position_key?: string;
      department?: { id: number; name: string };
    }>;
    // 기존 호환성을 위한 단수형도 유지
    tenant_profile?: {
      department?: { id: number; name: string };
      position?: { id: number; name: string };
      rank?: string;
    };
  };
}

// ============================================
// 프론트엔드 타입
// ============================================

// 사원 옵션 (드롭다운용)
export interface EmployeeOption {
  id: string;
  name: string;
  department: string;
  position: string;
  rank: string;
}

// 근태 기록 인터페이스
export interface AttendanceRecord {
  id: string;
  employeeId: string;
  employeeName: string;
  department: string;
  position: string;
  rank: string;
  baseDate: string;
  checkIn: string | null;
  checkOut: string | null;
  breakTime: string | null;
  overtimeHours: string | null;
  workMinutes: number | null;
  reason: {
    type: ReasonType;
    label: string;
    documentId?: string;
  } | null;
  status: AttendanceStatus;
  remarks: string | null;
  createdAt: string;
  updatedAt: string;
}

// 근태 등록/수정 폼 데이터
export interface AttendanceFormData {
  employeeId: string;
  baseDate: string;
  status?: AttendanceStatus;
  checkInHour: string;
  checkInMinute: string;
  checkOutHour: string;
  checkOutMinute: string;
  nightOvertimeHours: string;
  nightOvertimeMinutes: string;
  weekendOvertimeHours: string;
  weekendOvertimeMinutes: string;
  remarks?: string;
}

// 사유 등록 폼 데이터
export interface ReasonFormData {
  employeeId: string;
  baseDate: string;
  reasonType: ReasonType | '';
}

// ============================================
// 통계 타입
// ============================================

export interface AttendanceStats {
  year: number;
  month: number;
  totalDays: number;
  byStatus: {
    onTime: number;
    late: number;
    absent: number;
    vacation: number;
    businessTrip: number;
    fieldWork: number;
    overtime: number;
    remote: number;
  };
  totalWorkMinutes: number;
  totalOvertimeMinutes: number;
}

// ============================================
// 다이얼로그 Props
// ============================================

export interface AttendanceInfoDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  mode: 'create' | 'edit';
  attendance?: AttendanceRecord | null;
  employees: EmployeeOption[];
  onSave: (data: AttendanceFormData) => void;
}

export interface ReasonInfoDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  employees: EmployeeOption[];
  onSubmit: (data: ReasonFormData) => void;
}

// ============================================
// 시간 옵션 헬퍼
// ============================================

export const HOUR_OPTIONS = Array.from({ length: 24 }, (_, i) => ({
  value: String(i),
  label: `${i}시`,
}));

export const MINUTE_OPTIONS = [
  { value: '0', label: '0분' },
  { value: '15', label: '15분' },
  { value: '30', label: '30분' },
  { value: '45', label: '45분' },
];

// 연장 시간 옵션 (0-12시간)
export const OVERTIME_HOUR_OPTIONS = Array.from({ length: 13 }, (_, i) => ({
  value: String(i),
  label: `${i}시간`,
}));

// 상태 옵션 (등록/수정용)
export const STATUS_OPTIONS: { value: AttendanceStatus; label: string }[] = [
  { value: 'onTime', label: '정시 출근' },
  { value: 'late', label: '지각' },
  { value: 'absent', label: '결근' },
  { value: 'vacation', label: '휴가' },
  { value: 'businessTrip', label: '출장' },
  { value: 'fieldWork', label: '외근' },
  { value: 'overtime', label: '연장근무' },
  { value: 'remote', label: '재택근무' },
];
