import React from "react";
import moment, { Moment } from "moment";
import Table, { CellStatus } from "./BaseTable";
import { useTranslation } from "../../i18n";
import {
  RangeDateType,
  CalendarTableType,
  DateChangeContext,
} from "../DateProps";
import { getNow, isAfter, isBefore, isSame } from "../../datepicker/util";

export interface YearTableProps {
  /**
   * 当前展示时间
   */
  current: Moment;

  /**
   * 允许选择的时间范围限制
   */
  range?: RangeDateType;

  cellStatus?: (date: Moment) => CellStatus;

  onSelect?: (value: Moment, context: DateChangeContext) => void;

  onTypeChange?: (type: CalendarTableType) => void;

  onCurrentChange?: (current: Moment) => void;
}

export function YearTable({
  current,
  onCurrentChange = () => null,
  range,
  onSelect = () => null,
  cellStatus = () => CellStatus.Common,
}: YearTableProps) {
  const t = useTranslation();

  const year = current.year();
  const now = getNow(current);
  const start = year - (year % 20);
  const end = start + 20 - 1;

  // 5 * 4
  function genTable(): number[][] {
    return "abcde".split("").map((_, i) =>
      Array(4)
        .fill(0)
        .map((_, j) => i * 4 + j + start)
    );
  }

  function renderYear() {
    return `${start}-${end}`;
  }

  const [rangeMin, rangeMax] = range || [null, null];

  function isValid(date) {
    if (moment.isMoment(rangeMin) && isAfter(rangeMin, date, "year")) {
      return false;
    }
    if (moment.isMoment(rangeMax) && isBefore(rangeMax, date, "year")) {
      return false;
    }
    return true;
  }

  return (
    <Table
      type="year"
      caption={renderYear()}
      jumperOptions={{
        onNext: () => onCurrentChange(moment(current).add(20, "year")),
        onPrev: () => onCurrentChange(moment(current).subtract(20, "year")),
        onCurrent: () => onCurrentChange(now),
        isCurrent: now.year() >= start && now.year() <= end,
        nextDisabled: moment.isMoment(rangeMax) && rangeMax.year() <= end,
        prevDisabled: moment.isMoment(rangeMin) && rangeMin.year() >= start,
        nextTitle: t.nextTwentyYears,
        prevTitle: t.prevTwentyYears,
        curTitle: t.curTwentyYears,
      }}
    >
      {genTable().map((row, index) => (
        <Table.Row key={index}>
          {row.map(year => {
            const y = moment(current).set({
              year,
              month: 0,
              date: 1,
              hour: 0,
              minute: 0,
              second: 0,
              millisecond: 0,
            });
            return (
              <Table.Cell
                key={year}
                name={y.format("YYYY")}
                value={y}
                onSelect={onSelect}
                isNow={isSame(y, now, "year")}
                status={cellStatus(y)}
                disabled={!isValid(y)}
              />
            );
          })}
        </Table.Row>
      ))}
    </Table>
  );
}

YearTable.displayName = "YearTable";
