import React, { useMemo, useState } from 'react';
import { Empty, Segmented, Table, Tag } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { SlaHoliday } from '../interface';
import { formatHolidayDate } from './holidayDate';

type Scope = 'upcoming' | 'past';

interface HolidayListProps {
  holidays: SlaHoliday[]
  loading: boolean
}

// Read-only list of the SLA holidays: the ones still to come (today included) or the ones already gone by.
const HolidayList: React.FC<HolidayListProps> = ({ holidays, loading }) => {
  const [scope, setScope] = useState<Scope>('upcoming');

  const { upcoming, past } = useMemo(() => ({
    upcoming: holidays.filter((holiday) => holiday.status !== 'past'), // oldest first, as the server sends them
    past: holidays.filter((holiday) => holiday.status === 'past').reverse(), // most recent first
  }), [holidays]);

  const columns: ColumnsType<SlaHoliday> = [
    {
      title: 'Date',
      key: 'date',
      width: 190,
      render: (_, record) => (
        <>
          {formatHolidayDate(record.date)}
          {record.status === 'today' && <Tag color="red" style={{ marginLeft: 8 }}>Today</Tag>}
        </>
      ),
    },
    {
      title: 'Reason',
      dataIndex: 'reason',
      key: 'reason',
      render: (reason: string | null) => reason ?? '—',
    },
    {
      title: 'Added by',
      dataIndex: 'added_by',
      key: 'added_by',
      width: 150,
      render: (addedBy: string | null) => addedBy ?? '—',
    },
  ];

  return (
    <>
      <Segmented
        value={scope}
        onChange={(value) => setScope(value as Scope)}
        options={[
          { label: `Upcoming (${upcoming.length})`, value: 'upcoming' },
          { label: `Past (${past.length})`, value: 'past' },
        ]}
        style={{ marginBottom: 12 }}
      />
      <Table
        size="small"
        bordered
        rowKey="id"
        loading={loading}
        columns={columns}
        dataSource={scope === 'upcoming' ? upcoming : past}
        pagination={{ pageSize: 7, hideOnSinglePage: true, showSizeChanger: false }}
        locale={{
          emptyText: (
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description={scope === 'upcoming' ? 'No upcoming holidays. Both SLAs run on every working day.' : 'No past holidays.'}
            />
          ),
        }}
      />
    </>
  );
};

export default HolidayList;
