import React, { useMemo } from 'react';
import styled from 'styled-components';
import { HiSwitchHorizontal } from 'react-icons/hi';
import { useLocale } from '@/app/providers/LocaleProvider';
import { Card } from '@/shared/components/ui';
import type { TicketStatusHistoryEntry } from '@/features/tickets/types/ticket.types';
import { formatDateTime, localizedName } from '@/features/tickets/utils/ticketDisplay';

const Timeline = styled.ul`
  list-style: none;
  margin: 0;
  padding: 0;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    inset-inline-start: 15px;
    top: 8px;
    bottom: 8px;
    width: 2px;
    background-color: ${({ theme }) => theme.colors.border};
  }
`;

const Item = styled.li`
  position: relative;
  padding-inline-start: ${({ theme }) => theme.spacing[10]};
  padding-bottom: ${({ theme }) => theme.spacing[5]};

  &:last-child {
    padding-bottom: 0;
  }
`;

const Dot = styled.span`
  position: absolute;
  inset-inline-start: 8px;
  top: 4px;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background-color: ${({ theme }) => theme.colors.primary};
  border: 2px solid ${({ theme }) => theme.colors.primary};
  z-index: 1;
`;

const EventTitle = styled.div`
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  font-weight: ${({ theme }) => theme.typography.fontWeight.medium};
  color: ${({ theme }) => theme.colors.text.primary};
  text-align: start;
  line-height: ${({ theme }) => theme.typography.lineHeight.normal};
`;

const EventMeta = styled.div`
  margin-top: ${({ theme }) => theme.spacing[1]};
  font-size: ${({ theme }) => theme.typography.fontSize.xs};
  color: ${({ theme }) => theme.colors.text.tertiary};
  text-align: start;
`;

const DateGroup = styled.div`
  margin-bottom: ${({ theme }) => theme.spacing[4]};

  &:last-child {
    margin-bottom: 0;
  }
`;

const DateLabel = styled.div`
  font-size: 0.6875rem;
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  letter-spacing: ${({ theme }) => theme.typography.letterSpacing.widest};
  text-transform: uppercase;
  color: ${({ theme }) => theme.colors.text.tertiary};
  margin-bottom: ${({ theme }) => theme.spacing[3]};
  text-align: start;
`;

const EmptyMessage = styled.p`
  margin: 0;
  color: ${({ theme }) => theme.colors.text.secondary};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  text-align: start;
`;

function dateGroupKey(iso: string, locale: string): string {
  try {
    return new Intl.DateTimeFormat(locale === 'ar' ? 'ar' : 'en', {
      dateStyle: 'medium',
    }).format(new Date(iso));
  } catch {
    return iso.slice(0, 10);
  }
}

interface StatusHistoryTimelineProps {
  history: TicketStatusHistoryEntry[];
}

export const StatusHistoryTimeline: React.FC<StatusHistoryTimelineProps> = ({ history }) => {
  const { t, locale } = useLocale();

  const grouped = useMemo(() => {
    const map = new Map<string, TicketStatusHistoryEntry[]>();
    for (const entry of history) {
      const key = dateGroupKey(entry.created_at, locale);
      const list = map.get(key) ?? [];
      list.push(entry);
      map.set(key, list);
    }
    return Array.from(map.entries());
  }, [history, locale]);

  return (
    <Card
      variant="elevated"
      padding="lg"
      header={
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
          <HiSwitchHorizontal aria-hidden style={{ width: 18, height: 18 }} />
          {t('tickets:history')}
        </span>
      }
    >
      {history.length === 0 ? (
        <EmptyMessage>{t('tickets:states.noHistory')}</EmptyMessage>
      ) : (
        grouped.map(([dateLabel, entries]) => (
          <DateGroup key={dateLabel}>
            <DateLabel>{dateLabel}</DateLabel>
            <Timeline>
              {entries.map((entry) => (
                <Item key={entry.id}>
                  <Dot aria-hidden />
                  <EventTitle>
                    <strong>{entry.changed_by.name}</strong>
                    {' — '}
                    {entry.from_status
                      ? `${localizedName(entry.from_status, locale)} → ${localizedName(entry.to_status, locale)}`
                      : localizedName(entry.to_status, locale)}
                  </EventTitle>
                  <EventMeta>{formatDateTime(entry.created_at, locale)}</EventMeta>
                </Item>
              ))}
            </Timeline>
          </DateGroup>
        ))
      )}
    </Card>
  );
};
