import React, { useMemo, useState } from 'react';
import { Button, Calendar, Checkbox, Input, Modal, Tag, Typography, notification, theme } from 'antd';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import { addSlaHolidays, removeSlaHoliday } from '../service';
import type { SlaHoliday, SlaHolidayList, SlaRule } from '../interface';
import { formatHolidayDate } from './holidayDate';
import { SLA_RULES, otherRule } from './scheduleText';

const { Text } = Typography;

const DATE_KEY = 'YYYY-MM-DD';
const MAX_DAYS_AHEAD = 366; // the server refuses a holiday further out than this
const MAX_REASON_LENGTH = 255;

interface HolidayCalendarProps {
  rule: SlaRule // whose holidays these are
  data: SlaHolidayList | null // the holidays of both SLAs; only this rule's are shown
  onChanged: () => Promise<void>
}

interface ApiError {
  response?: { data?: { message?: string } }
}

const errorMessage = (error: unknown): string | undefined => (error as ApiError)?.response?.data?.message;

// Calendar for marking one SLA's holidays: click a free day to select it, then Save; click a red day to remove that
// holiday. A day can be marked for the other SLA in the same go (ticked by default).
const HolidayCalendar: React.FC<HolidayCalendarProps> = ({ rule, data, onChanged }) => {
  const { token } = theme.useToken();
  const [selected, setSelected] = useState<string[]>([]);
  const [reason, setReason] = useState('');
  const [alsoOther, setAlsoOther] = useState(true);
  const [saving, setSaving] = useState(false);
  const [viewDate, setViewDate] = useState<Dayjs>(dayjs());
  const other = otherRule(rule); // null for the lead request transfer, which is marked on its own
  const rules: SlaRule[] = alsoOther && other ? [rule, other] : [rule]; // the rules the selected days are marked for

  // The server's "today" is the IST day; the browser may be anywhere.
  const today = data?.today ?? dayjs().format(DATE_KEY);
  const lastDay = dayjs(today).add(MAX_DAYS_AHEAD, 'day').format(DATE_KEY);
  const holidayByDate = useMemo(
    () => new Map((data?.holidays ?? []).filter((holiday) => holiday.rule === rule).map((holiday) => [holiday.date, holiday])),
    [data, rule]
  );

  const isSelectable = (date: Dayjs): boolean => {
    const key = date.format(DATE_KEY);
    return key >= today && key <= lastDay;
  };

  const confirmRemove = (holiday: SlaHoliday): void => {
    Modal.confirm({
      title: 'Remove this holiday?',
      content: `${formatHolidayDate(holiday.date)}${holiday.reason ? ` (${holiday.reason})` : ''} will be a normal working day again for the ${SLA_RULES[rule].short}.${other ? ` The ${SLA_RULES[other].short} keeps its own holidays.` : ''}`,
      okText: 'Remove',
      okButtonProps: { danger: true },
      cancelText: 'Keep',
      async onOk() {
        try {
          const response = await removeSlaHoliday(holiday.id);
          notification.success({ message: 'Success', description: response?.data?.message });
          await onChanged();
        } catch (error) {
          notification.error({ message: 'Error', description: errorMessage(error) });
        }
      },
    });
  };

  const onSelect = (date: Dayjs, { source }: { source: string }): void => {
    if (source !== 'date') return; // the month and year drop-downs in the header also report a selection
    const key = date.format(DATE_KEY);
    const holiday = holidayByDate.get(key);
    if (holiday) {
      if (holiday.status !== 'past') confirmRemove(holiday);
      return;
    }
    setSelected((current) => (current.includes(key) ? current.filter((day) => day !== key) : [...current, key].sort()));
  };

  const save = async(): Promise<void> => {
    setSaving(true);
    try {
      const response = await addSlaHolidays({
        dates: selected,
        reason: reason.trim() || undefined,
        rules,
      });
      const moved: number = response?.data?.data?.leads_rescheduled ?? 0;
      notification.success({
        message: 'Success',
        description: `${response?.data?.message ?? 'Holidays saved.'}${moved > 0 ? ` ${moved} waiting lead(s) were given a fresh 30-minute window after the holiday.` : ''}`,
      });
      setSelected([]);
      setReason('');
      await onChanged();
    } catch (error) {
      notification.error({ message: 'Error', description: errorMessage(error) });
    } finally {
      setSaving(false);
    }
  };

  // Marking a holiday stops the reassignment on those days, so it is confirmed before it is saved.
  const confirmSave = (): void => {
    const many = selected.length > 1;
    Modal.confirm({
      title: many ? `Mark ${selected.length} days as holidays?` : 'Mark this day as a holiday?',
      content: (
        <div>
          <div style={{ fontWeight: 500 }}>{selected.map((day) => formatHolidayDate(day)).join(', ')}</div>
          <div style={{ marginTop: 8 }}>
            The {rules.map((entry) => SLA_RULES[entry].short).join(' and the ')} will not run on {many ? 'these days' : 'this day'}.
            {rules.includes('sla') && ' Waiting leads whose 30-minute timer falls on a newly marked day get a fresh window from the next working day.'}
          </div>
        </div>
      ),
      okText: many ? 'Mark holidays' : 'Mark holiday',
      cancelText: 'Cancel',
      async onOk() {
        await save();
      },
    });
  };

  // The whole day cell is drawn here, so a holiday, a selected day and today are told apart at a glance.
  const fullCellRender = (date: Dayjs, info: { type: string, originNode: React.ReactNode }): React.ReactNode => {
    if (info.type !== 'date') return info.originNode;
    const key = date.format(DATE_KEY);
    const holiday = holidayByDate.get(key);
    const style: React.CSSProperties = {
      display: 'inline-block',
      minWidth: 28,
      height: 28,
      lineHeight: '26px',
      borderRadius: '50%',
      borderWidth: 1,
      borderStyle: 'solid',
      borderColor: 'transparent',
      textAlign: 'center',
    };
    if (holiday) {
      Object.assign(style, holiday.status === 'past'
        ? { background: token.colorErrorBg, color: token.colorError }
        : { background: token.colorError, color: token.colorWhite });
    } else if (selected.includes(key)) {
      Object.assign(style, { background: token.colorPrimary, color: token.colorWhite });
    } else if (key === today) {
      Object.assign(style, { borderColor: token.colorPrimary });
    }
    return <div style={style}>{date.date()}</div>;
  };

  const legend = (color: string, label: string): React.ReactNode => (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginRight: 14 }}>
      <span style={{ width: 10, height: 10, borderRadius: '50%', background: color, display: 'inline-block' }} />
      <Text type="secondary" style={{ fontSize: 12 }}>{label}</Text>
    </span>
  );

  return (
    <div style={{ display: 'flex', gap: 24, flexWrap: 'wrap' }}>
      <div style={{ flex: '0 0 300px' }}>
        <div style={{ border: `1px solid ${token.colorBorderSecondary}`, borderRadius: token.borderRadiusLG, padding: 8 }}>
          <Calendar
            fullscreen={false}
            value={viewDate}
            onChange={setViewDate}
            disabledDate={(date) => !isSelectable(date)}
            fullCellRender={fullCellRender}
            onSelect={onSelect}
          />
        </div>
        <div style={{ marginTop: 10 }}>
          {legend(token.colorError, 'Holiday')}
          {legend(token.colorPrimary, 'Selected')}
        </div>
      </div>

      <div style={{ flex: '1 1 240px', minWidth: 240 }}>
        <Text type="secondary">
          Click the days the {SLA_RULES[rule].short} should not run, then save. Click a red day to remove that holiday
          from the {SLA_RULES[rule].short}.
        </Text>

        <div style={{ margin: '16px 0 6px', fontWeight: 500 }}>Selected days</div>
        <div style={{ minHeight: 32 }}>
          {selected.length === 0
            ? <Text type="secondary">No days selected yet.</Text>
            : selected.map((day) => (
              <Tag
                key={day}
                closable
                onClose={() => setSelected((current) => current.filter((entry) => entry !== day))}
                style={{ marginBottom: 4 }}
              >
                {formatHolidayDate(day)}
              </Tag>
            ))}
        </div>
        <div style={{ margin: '16px 0 6px', fontWeight: 500 }}>Reason (optional)</div>
        <Input
          value={reason}
          onChange={(event) => setReason(event.target.value)}
          maxLength={MAX_REASON_LENGTH}
          placeholder="e.g. Diwali"
          disabled={selected.length === 0}
        />
        {other && (
          <>
            <Checkbox
              checked={alsoOther}
              onChange={(event) => setAlsoOther(event.target.checked)}
              style={{ display: 'flex', margin: '12px 0 4px' }}
            >
              Also mark these days for the {SLA_RULES[other].short}
            </Checkbox>
            <Text type="secondary" style={{ display: 'block', margin: '0 0 16px', fontSize: 12 }}>
              Leads whose 30-minute timer falls on a new 30-minute holiday get a fresh window from the next working day.
            </Text>
          </>
        )}
        {!other && <div style={{ height: 16 }} />}

        <Button type="primary" loading={saving} disabled={selected.length === 0} onClick={confirmSave}>
          {selected.length > 1 ? `Save ${selected.length} holidays` : 'Save holiday'}
        </Button>
      </div>
    </div>
  );
};

export default HolidayCalendar;
