// aislop-ignore-file: duplicate-block -- 周/月视图表格结构相似且展示维度不同，已共享 ScheduleGrid 组件
import React from 'react';
import { Badge, Empty, Spin, Tooltip } from 'antd';
import type { Dayjs } from 'dayjs';
import { isMaskedSchedule } from './schedule-visibility';

export const WEEKDAYS = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
export const WEEKDAY_NUMBERS = [1, 2, 3, 4, 5, 6, 7];

export interface ClassScheduleItem {
  id: number | null;
  classId: number | null;
  classroomId: number;
  weekDay: number;
  startTime: string;
  endTime: string;
  attendanceAdvanceMinutes: number;
  startDate: string;
  endDate: string;
  subject: string;
  teacherId: number | null;
  scheduleType: string;
  status: string;
  notes: string | null;
  createdAt: string;
  updatedAt: string;
  canViewDetails?: boolean;
}

export interface ClassroomItem {
  id: number;
  name: string;
  building: string;
  floor: number;
  roomType: string;
}

export interface ClassItem {
  id: number;
  name: string;
  code: string;
}

export interface ClassTeacherOption {
  id: number;
  userId: number;
  username?: string;
  name?: string;
  roleType: string;
  subject?: string | null;
}

export const ScheduleGrid: React.FC<{
  loading: boolean;
  viewMode: 'week' | 'month';
  classrooms: ClassroomItem[];
  filteredClassrooms: ClassroomItem[];
  displayMatrix: Record<number, Record<number, ClassScheduleItem[]>>;
  weeks: Dayjs[][];
  monthStart: Dayjs;
  monthScheduleMap: Record<string, ClassScheduleItem[]>;
  onCellClick: (classroomId: number, weekDay: number) => void;
  onDateClick: (date: Dayjs) => void;
}> = ({
  loading,
  viewMode,
  classrooms,
  filteredClassrooms,
  displayMatrix,
  weeks,
  monthStart,
  monthScheduleMap,
  onCellClick,
  onDateClick,
}) => {
  return (
    <Spin spinning={loading}>
      {classrooms.length === 0 ? (
        <Empty description="暂无教室数据" />
      ) : viewMode === 'week' ? (
        <div style={{ overflowX: 'auto' }}>
          <table
            style={{
              width: '100%',
              borderCollapse: 'collapse',
              fontSize: 13,
              tableLayout: 'fixed',
            }}
          >
            <thead>
              <tr style={{ background: '#fafafa' }}>
                <th
                  style={{
                    position: 'sticky',
                    left: 0,
                    background: '#fafafa',
                    zIndex: 2,
                    padding: '10px 12px',
                    border: '1px solid #f0f0f0',
                    width: 150,
                    textAlign: 'left',
                  }}
                >
                  教室
                </th>
                {WEEKDAYS.map((day) => (
                  <th
                    key={day}
                    style={{
                      padding: '10px 8px',
                      border: '1px solid #f0f0f0',
                      textAlign: 'center',
                      background: '#fafafa',
                      fontWeight: 500,
                    }}
                  >
                    {day}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filteredClassrooms.map((classroom) => (
                <tr key={classroom.id}>
                  <td
                    style={{
                      position: 'sticky',
                      left: 0,
                      background: '#fff',
                      zIndex: 1,
                      padding: '8px 12px',
                      border: '1px solid #f0f0f0',
                      fontWeight: 500,
                    }}
                  >
                    <div>{classroom.name}</div>
                    {classroom.building && (
                      <div style={{ fontSize: 11, color: '#8c8c8c', marginTop: 2 }}>
                        {classroom.building}
                        {classroom.floor ? ` ${classroom.floor}F` : ''}
                      </div>
                    )}
                  </td>
                  {WEEKDAY_NUMBERS.map((wd) => {
                    const schedules = displayMatrix[classroom.id]?.[wd] || [];
                    const hasContent = schedules.length > 0;
                    return (
                      <td
                        key={wd}
                        tabIndex={0}
                        role="button"
                        aria-label={`选择教室 ${classroom.name} ${WEEKDAYS[wd - 1]} 排课`}
                        onClick={() => onCellClick(classroom.id, wd)}
                        onKeyDown={(e) => {
                          if (e.key === 'Enter' || e.key === ' ') {
                            e.preventDefault();
                            onCellClick(classroom.id, wd);
                          }
                        }}
                        style={{
                          padding: 4,
                          border: '1px solid #f0f0f0',
                          verticalAlign: 'top',
                          cursor: 'pointer',
                          minHeight: 56,
                          transition: 'background 0.15s',
                        }}
                        onMouseEnter={(e) => {
                          (e.currentTarget as HTMLElement).style.background = '#f6f8fa';
                        }}
                        onMouseLeave={(e) => {
                          (e.currentTarget as HTMLElement).style.background = '';
                        }}
                      >
                        {hasContent ? (
                          <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                            {schedules.map((s) => (
                              <Tooltip
                                key={`${s.id ?? 'busy'}-${s.classroomId}-${s.weekDay}-${s.startTime}-${s.endTime}`}
                                title={
                                  isMaskedSchedule(s)
                                    ? `已占用 · ${s.startTime}-${s.endTime}`
                                    : `${s.subject} · ${s.startTime}-${s.endTime} · ${s.startDate}~${s.endDate}`
                                }
                              >
                                <div
                                  style={{
                                    background: isMaskedSchedule(s) ? '#f5f5f5' : '#e6f4ff',
                                    border: isMaskedSchedule(s)
                                      ? '1px solid #d9d9d9'
                                      : '1px solid #91caff',
                                    borderRadius: 4,
                                    padding: '2px 6px',
                                    fontSize: 12,
                                    lineHeight: '18px',
                                  }}
                                >
                                  <div
                                    style={{
                                      fontWeight: 600,
                                      color: isMaskedSchedule(s) ? '#595959' : '#1677ff',
                                    }}
                                  >
                                    {s.subject}
                                  </div>
                                  <div style={{ color: '#595959' }}>
                                    {s.startTime}-{s.endTime}
                                  </div>
                                </div>
                              </Tooltip>
                            ))}
                          </div>
                        ) : (
                          <div
                            style={{
                              color: '#d9d9d9',
                              fontSize: 20,
                              textAlign: 'center',
                              lineHeight: '44px',
                            }}
                          >
                            —
                          </div>
                        )}
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <div style={{ overflowX: 'auto' }}>
          <table
            style={{
              width: '100%',
              borderCollapse: 'collapse',
              fontSize: 13,
              tableLayout: 'fixed',
            }}
          >
            <thead>
              <tr style={{ background: '#fafafa' }}>
                {WEEKDAYS.map((d) => (
                  <th
                    key={d}
                    style={{
                      padding: '10px 8px',
                      border: '1px solid #f0f0f0',
                      textAlign: 'center',
                      fontWeight: 500,
                    }}
                  >
                    {d}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {weeks.map((week, wi) => (
                <tr key={wi}>
                  {week.map((day, di) => {
                    const isCurrentMonth = day.month() === monthStart.month();
                    const dateKey = day.format('YYYY-MM-DD');
                    const daySchedules = monthScheduleMap[dateKey] || [];
                    const count = daySchedules.length;
                    return (
                      <td
                        key={di}
                        tabIndex={0}
                        role="button"
                        aria-label={`${day.format('YYYY-MM-DD')} 排课详情`}
                        onClick={() => onDateClick(day)}
                        onKeyDown={(e) => {
                          if (e.key === 'Enter' || e.key === ' ') {
                            e.preventDefault();
                            onDateClick(day);
                          }
                        }}
                        style={{
                          padding: '6px 8px',
                          border: '1px solid #f0f0f0',
                          verticalAlign: 'top',
                          cursor: 'pointer',
                          height: 90,
                          background: isCurrentMonth ? '#fff' : '#fafafa',
                          transition: 'background 0.15s',
                        }}
                        onMouseEnter={(e) => {
                          (e.currentTarget as HTMLElement).style.background = isCurrentMonth
                            ? '#f0f5ff'
                            : '#f0f0f0';
                        }}
                        onMouseLeave={(e) => {
                          (e.currentTarget as HTMLElement).style.background = isCurrentMonth
                            ? ''
                            : '#fafafa';
                        }}
                      >
                        <div
                          style={{
                            fontWeight: isCurrentMonth ? 600 : 400,
                            color: isCurrentMonth ? '#262626' : '#bfbfbf',
                            fontSize: 14,
                            marginBottom: 4,
                          }}
                        >
                          {day.date()}
                        </div>
                        {count > 0 && (
                          <Badge
                            count={count}
                            size="small"
                            overflowCount={99}
                            style={{ backgroundColor: '#1677ff' }}
                          />
                        )}
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </Spin>
  );
};
