import React, { useEffect, useState } from 'react';
import { Alert, Button, Checkbox, TimePicker, Typography, notification } from 'antd';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import { updateSlaSettings } from '../service';
import type { SlaRule, SlaSettings } from '../interface';
import { LEAD_REQUEST_RUN_TIME, SLA_RULES, WEEKDAY_NAMES, hasWorkingHours, otherRule, scheduleOf, schedulePayload } from './scheduleText';

const { Text } = Typography;

const TIME_FORMAT = 'HH:mm';
// Shown Monday first; the values are the backend's weekday numbers.
const WEEKDAY_OPTIONS = [1, 2, 3, 4, 5, 6, 0].map((day) => ({ label: WEEKDAY_NAMES[day], value: day }));

interface WorkingHoursFormProps {
  rule: SlaRule
  settings: SlaSettings | null
  onSaved: () => Promise<void>
}

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

// 'HH:MM' as a time today. Text typed into the picker is read as a time today as well, and the two must be on the
// same day or the picker takes the start for a later time than the end.
const toTime = (value: string): Dayjs => {
  const [hour, minute] = value.split(':').map(Number);
  return dayjs().hour(hour).minute(minute).second(0).millisecond(0);
};

// One SLA's working hours and the weekdays it is closed all day. Saving changes only this SLA, never the other one.
const WorkingHoursForm: React.FC<WorkingHoursFormProps> = ({ rule, settings, onSaved }) => {
  const [start, setStart] = useState<Dayjs | null>(null);
  const [end, setEnd] = useState<Dayjs | null>(null);
  const [closedDays, setClosedDays] = useState<number[]>([]);
  const [saving, setSaving] = useState(false);

  const saved = settings ? scheduleOf(settings, rule) : null;

  // Start from what is saved, and again whenever it changes (after a save).
  useEffect(() => {
    if (settings) {
      const current = scheduleOf(settings, rule);
      setStart(toTime(current.start));
      setEnd(toTime(current.end));
      setClosedDays(current.offDays);
    }
  }, [settings, rule]);

  const withHours = hasWorkingHours(rule);
  const other = otherRule(rule);

  const problem = ((): string | null => {
    if (withHours && (!start || !end)) return 'Choose an opening and a closing time.';
    if (withHours && start && end && !start.isBefore(end)) return 'The closing time must be after the opening time.';
    if (closedDays.length >= 7) return 'At least one day of the week must be a working day.';
    return null;
  })();

  const changed = saved !== null && start !== null && end !== null && (
    start.format(TIME_FORMAT) !== saved.start ||
    end.format(TIME_FORMAT) !== saved.end ||
    [...closedDays].sort().join() !== [...saved.offDays].sort().join()
  );

  const save = async(): Promise<void> => {
    if (problem || !start || !end) return;
    setSaving(true);
    try {
      const response = await updateSlaSettings(schedulePayload(rule, {
        start: start.format(TIME_FORMAT),
        end: end.format(TIME_FORMAT),
        offDays: closedDays,
      }));
      notification.success({ message: 'Success', description: response?.data?.message ?? `${SLA_RULES[rule].label} working hours saved.` });
      await onSaved();
    } catch (error) {
      notification.error({ message: 'Error', description: (error as ApiError)?.response?.data?.message });
    } finally {
      setSaving(false);
    }
  };

  return (
    <div>
      {withHours ? (
        <Text type="secondary">
          The {SLA_RULES[rule].short} only runs inside these hours, and not at all on a closed day.
          {other && ` The ${SLA_RULES[other].short} keeps its own hours.`}
        </Text>
      ) : (
        <Text type="secondary">
          The {SLA_RULES[rule].short} moves the next batch of every approved lead request once a day at {LEAD_REQUEST_RUN_TIME}
          {' '}(the first batch is moved when the request is approved). It does not run on a closed day or a holiday.
        </Text>
      )}

      {withHours && (
        <>
          <div style={{ margin: '16px 0 6px', fontWeight: 500 }}>Working hours</div>
          <TimePicker.RangePicker
            value={start && end ? [start, end] : null}
            format={TIME_FORMAT}
            allowClear={false}
            order={false} // keep what was typed, so a start after the end shows the message below instead of being swapped
            placeholder={['Opens', 'Closes']}
            onChange={(range) => {
              setStart(range?.[0] ? toTime(range[0].format(TIME_FORMAT)) : null);
              setEnd(range?.[1] ? toTime(range[1].format(TIME_FORMAT)) : null);
            }}
          />
        </>
      )}

      <div style={{ margin: '16px 0 6px', fontWeight: 500 }}>Closed all day, every week</div>
      <Checkbox.Group
        options={WEEKDAY_OPTIONS}
        value={closedDays}
        onChange={(values) => setClosedDays(values as number[])}
      />

      {problem && saved !== null && <Alert style={{ marginTop: 16 }} type="error" showIcon message={problem} />}

      <Text type="secondary" style={{ display: 'block', margin: '16px 0', fontSize: 12 }}>
        {withHours
          ? 'Leads already waiting keep the due time they were given, and are checked only inside the new hours; the new hours apply to leads assigned from now on. Single days off are marked under Holidays.'
          : 'Single days off are marked under Holidays.'}
      </Text>

      <Button type="primary" loading={saving} disabled={saved === null || problem !== null || !changed} onClick={save}>
        {withHours ? 'Save working hours' : 'Save closed days'}
      </Button>
    </div>
  );
};

export default WorkingHoursForm;
