import ReactMarkdown from 'react-markdown';
import { VerticalTimelineElement } from 'react-vertical-timeline-component';
import type { TimelineBody, TimelineItem, TitleSegment } from '../api/client';
import { colorFor, iconFor } from '../lib/icon';

interface Props {
  item: TimelineItem;
}

export function TimelineEntry({ item }: Props) {
  const Icon = iconFor(item.icon);
  const date = formatDate(item.occurred_at);

  return (
    <VerticalTimelineElement
      date={date}
      iconStyle={{ background: colorFor(item.icon), color: '#fff' }}
      icon={<Icon />}
    >
      <h4 className="vertical-timeline-element-title">
        {renderSegments(item.title)}
      </h4>
      {item.subtitle && (
        <h5 className="vertical-timeline-element-subtitle">
          {renderSegments(item.subtitle)}
        </h5>
      )}
      {item.body && <Body body={item.body} />}
    </VerticalTimelineElement>
  );
}

function Body({ body }: { body: TimelineBody }) {
  switch (body.kind) {
    case 'markdown':
      return <ReactMarkdown>{body.text}</ReactMarkdown>;
    case 'commits':
      return (
        <ul style={{ listStyle: 'none', paddingLeft: 0 }}>
          {body.commits.map((c) => (
            <li key={c.sha}>
              <a href={c.url} target="_blank" rel="noopener noreferrer">
                <code>{c.short_sha}</code>
              </a>{' '}
              {c.message}
            </li>
          ))}
        </ul>
      );
    case 'links':
      return (
        <ul>
          {body.items.map((seg, i) => (
            <li key={i}>{renderSegment(seg, i)}</li>
          ))}
        </ul>
      );
  }
}

function renderSegments(segments: TitleSegment[]) {
  return segments.map((seg, i) => renderSegment(seg, i));
}

function renderSegment(seg: TitleSegment, i: number) {
  if (seg.kind === 'link') {
    return (
      <a key={i} href={seg.url} target="_blank" rel="noopener noreferrer">
        {seg.text}
      </a>
    );
  }
  return <span key={i}>{seg.text}</span>;
}

function formatDate(iso: string): string {
  const d = new Date(iso);
  const date = d
    .toLocaleDateString('en-GB', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    })
    .toLowerCase();
  const time = d
    .toLocaleTimeString('en-GB', { timeZoneName: 'short' })
    .toLowerCase();
  return `${date} — ${time}`;
}
