import React from 'react';
import { Alert, Button, Descriptions, Modal, Tabs, Typography } from 'antd';
import { EditOutlined } from '@ant-design/icons';
import type { SlaHolidayList, SlaRule, SlaSettings } from '../interface';
import HolidayList from './HolidayList';
import HolidayCalendar from './HolidayCalendar';
import WorkingHoursForm from './WorkingHoursForm';
import { LEAD_REQUEST_RUN_TIME, SLA_RULES, closedDayNames, describeHours, hasWorkingHours, joinNames, scheduleOf } from './scheduleText';

const { Title } = Typography;

export type SettingsMode = 'view' | 'edit';

interface SlaSettingsModalProps {
  rule: SlaRule | null // which SLA's settings are open; null = closed
  mode: SettingsMode
  settings: SlaSettings | null
  settingsFailed: boolean
  holidays: SlaHolidayList | null
  holidaysLoading: boolean
  holidaysFailed: boolean
  onModeChange: (mode: SettingsMode) => void
  onClose: () => void
  onSettingsChanged: () => Promise<void>
  onHolidaysChanged: () => Promise<void>
}

// One window for one SLA's settings, opened from its row on the Feature Control screen: to look at them (working hours,
// weekly closed days, holidays) or to change them. The 30-minute SLA and the overdue SLA each have their own.
const SlaSettingsModal: React.FC<SlaSettingsModalProps> = ({
  rule, mode, settings, settingsFailed, holidays, holidaysLoading, holidaysFailed, onModeChange, onClose, onSettingsChanged, onHolidaysChanged,
}) => {
  const editing = mode === 'edit';

  const retry = (reload: () => Promise<void>): React.ReactNode => <Button size="small" onClick={() => reload()}>Try again</Button>;

  const body = (activeRule: SlaRule): React.ReactNode => {
    const ruleHolidays = (holidays?.holidays ?? []).filter((holiday) => holiday.rule === activeRule);

    if (editing) {
      return (
        <Tabs
          items={[
            {
              key: 'hours',
              label: hasWorkingHours(activeRule) ? 'Working hours' : 'Closed days',
              children: settingsFailed && settings === null
                ? <Alert type="error" showIcon message="The working hours could not be loaded." action={retry(onSettingsChanged)} />
                : <WorkingHoursForm rule={activeRule} settings={settings} onSaved={onSettingsChanged} />,
            },
            {
              key: 'holidays',
              label: 'Holidays',
              children: holidaysFailed && holidays === null
                ? <Alert type="error" showIcon message="The holidays could not be loaded." action={retry(onHolidaysChanged)} />
                : <HolidayCalendar rule={activeRule} data={holidays} onChanged={onHolidaysChanged} />,
            },
          ]}
        />
      );
    }

    const schedule = settings ? scheduleOf(settings, activeRule) : null;
    const closed = schedule ? closedDayNames(schedule.offDays) : [];
    return (
      <>
        {settingsFailed && settings === null
          ? <Alert type="error" showIcon message="The working hours could not be loaded." action={retry(onSettingsChanged)} />
          : (
            <Descriptions bordered size="small" column={1} labelStyle={{ width: 230 }}>
              {hasWorkingHours(activeRule)
                ? <Descriptions.Item label="Working hours">{schedule ? describeHours(schedule) : '—'}</Descriptions.Item>
                : <Descriptions.Item label="Runs">Every day at {LEAD_REQUEST_RUN_TIME}, and when a request is approved</Descriptions.Item>}
              <Descriptions.Item label="Closed all day, every week">{schedule ? (closed.length > 0 ? joinNames(closed) : 'None') : '—'}</Descriptions.Item>
            </Descriptions>
          )}

        <Title level={5} style={{ margin: '20px 0 12px' }}>Holidays</Title>
        {holidaysFailed && holidays === null
          ? <Alert type="error" showIcon message="The holidays could not be loaded." action={retry(onHolidaysChanged)} />
          : <HolidayList holidays={ruleHolidays} loading={holidaysLoading} />}
      </>
    );
  };

  const footer = editing
    ? [
      <Button key="back" onClick={() => onModeChange('view')}>Back to view</Button>,
      <Button key="close" onClick={onClose}>Close</Button>,
    ]
    : [
      <Button key="close" onClick={onClose}>Close</Button>,
      <Button key="edit" type="primary" icon={<EditOutlined />} onClick={() => onModeChange('edit')}>Edit settings</Button>,
    ];

  return (
    <Modal
      open={rule !== null}
      title={rule ? `${editing ? 'Edit ' : ''}${SLA_RULES[rule].label} Settings` : ''}
      width={editing ? 720 : 640}
      footer={footer}
      onCancel={onClose}
      destroyOnClose
    >
      {rule && body(rule)}
    </Modal>
  );
};

export default SlaSettingsModal;
