import React, { useMemo } from 'react';
import styled from 'styled-components';
import { useNavigate } from 'react-router-dom';
import { HiCollection, HiTicket } from 'react-icons/hi';
import { useLocale } from '@/app/providers/LocaleProvider';
import { Card, Badge, StatusBadge } from '@/shared/components/ui';
import { PanelEmpty } from '@/shared/components/ui/PageState';
import { ROUTES } from '@/shared/constants/routes';
import type {
  DashboardRecentProject,
  DashboardRecentTicket,
} from '@/features/dashboard/types/dashboard.types';
import { translateMetricLabel } from '@/features/dashboard/utils/translateMetricLabel';

const HeaderRow = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: ${({ theme }) => theme.spacing[3]};
  flex-wrap: wrap;
`;

const HeaderTitle = styled.span`
  font-family: ${({ theme }) => theme.typography.fontFamily.headline};
  font-size: ${({ theme }) => theme.typography.fontSize.base};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
`;

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

const TimelineItem = styled.li`
  display: grid;
  grid-template-columns: 20px minmax(0, 1fr);
  gap: ${({ theme }) => theme.spacing[4]};
  padding: ${({ theme }) => theme.spacing[5]} 0;
  border-bottom: 1px solid ${({ theme }) => theme.colors.borderSoft};
  position: relative;

  &:last-child {
    border-bottom: none;
    padding-bottom: 0;
  }

  &:first-child {
    padding-top: ${({ theme }) => theme.spacing[2]};
  }
`;

const Rail = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: ${({ theme }) => theme.spacing[1]};
`;

const Dot = styled.span<{ $variant: 'ticket' | 'project' }>`
  width: 10px;
  height: 10px;
  border-radius: ${({ theme }) => theme.borderRadius.full};
  background: ${({ theme, $variant }) =>
    $variant === 'ticket' ? theme.colors.primary : theme.colors.warning};
  box-shadow: 0 0 0 3px
    ${({ theme, $variant }) =>
      $variant === 'ticket' ? theme.colors.primaryLight : theme.colors.warningLight};
  flex-shrink: 0;
`;

const Line = styled.span`
  flex: 1;
  width: 2px;
  margin-top: ${({ theme }) => theme.spacing[2]};
  background: ${({ theme }) => theme.colors.borderSoft};
  border-radius: ${({ theme }) => theme.borderRadius.full};
  min-height: 24px;
`;

const Content = styled.div`
  display: flex;
  flex-direction: column;
  gap: ${({ theme }) => theme.spacing[2]};
  min-width: 0;
  text-align: start;
`;

const TopRow = styled.div`
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: ${({ theme }) => theme.spacing[3]};
  flex-wrap: wrap;
`;

const ItemLink = styled.button`
  background: none;
  border: none;
  padding: 0;
  color: ${({ theme }) => theme.colors.primary};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  cursor: pointer;
  text-align: start;

  &:hover {
    text-decoration: underline;
  }
`;

const Subject = styled.p`
  margin: 0;
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  color: ${({ theme }) => theme.colors.text.primary};
  line-height: ${({ theme }) => theme.typography.lineHeight.relaxed};
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
`;

const MetaRow = styled.div`
  display: flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[2]};
  flex-wrap: wrap;
`;

const TypeBadge = styled.span<{ $variant: 'ticket' | 'project' }>`
  display: inline-flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[1]};
  font-size: ${({ theme }) => theme.typography.fontSize.xs};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  padding: 2px ${({ theme }) => theme.spacing[2]};
  border-radius: ${({ theme }) => theme.borderRadius.sm};
  color: ${({ theme, $variant }) =>
    $variant === 'ticket' ? theme.colors.primary : theme.colors.warning};
  background: ${({ theme, $variant }) =>
    $variant === 'ticket' ? theme.colors.primaryLight : theme.colors.warningLight};
  border: 1px solid
    ${({ theme, $variant }) =>
      $variant === 'ticket'
        ? theme.colors.status.open.border
        : theme.colors.status.warning.border};

  svg {
    width: 12px;
    height: 12px;
  }
`;

const Timestamp = styled.time`
  font-size: ${({ theme }) => theme.typography.fontSize.xs};
  color: ${({ theme }) => theme.colors.text.tertiary};
  white-space: nowrap;
`;

type ActivityFeedItem =
  | { kind: 'ticket'; sortAt: string; ticket: DashboardRecentTicket }
  | { kind: 'project'; sortAt: string; project: DashboardRecentProject };

interface RecentActivityFeedProps {
  tickets: DashboardRecentTicket[];
  projects: DashboardRecentProject[];
  emptyLabel: string;
}

function formatDate(value: string, locale: string): string {
  try {
    return new Intl.DateTimeFormat(locale === 'ar' ? 'ar' : 'en', {
      dateStyle: 'medium',
      timeStyle: 'short',
    }).format(new Date(value));
  } catch {
    return value;
  }
}

function ticketStatusTone(
  status: string,
): 'open' | 'pending' | 'inProgress' | 'resolved' | 'closed' | 'neutral' {
  const s = status.toLowerCase();
  if (s.includes('open')) return 'open';
  if (s.includes('pending')) return 'pending';
  if (s.includes('progress')) return 'inProgress';
  if (s.includes('resolved')) return 'resolved';
  if (s.includes('closed')) return 'closed';
  return 'neutral';
}

function projectStatusTone(status: string): 'active' | 'warning' | 'success' | 'neutral' {
  const s = status.toLowerCase();
  if (s === 'active' || s === 'planned') return 'active';
  if (s === 'on_hold') return 'warning';
  if (s === 'completed') return 'success';
  return 'neutral';
}

export const RecentActivityFeed: React.FC<RecentActivityFeedProps> = ({
  tickets,
  projects,
  emptyLabel,
}) => {
  const navigate = useNavigate();
  const { t, locale } = useLocale();

  const items = useMemo<ActivityFeedItem[]>(() => {
    const merged: ActivityFeedItem[] = [
      ...tickets.map((ticket) => ({
        kind: 'ticket' as const,
        sortAt: ticket.updated_at,
        ticket,
      })),
      ...projects.map((project) => ({
        kind: 'project' as const,
        sortAt: project.updated_at,
        project,
      })),
    ];

    return merged
      .sort((a, b) => new Date(b.sortAt).getTime() - new Date(a.sortAt).getTime())
      .slice(0, 10);
  }, [projects, tickets]);

  return (
    <Card
      variant="elevated"
      padding="lg"
      header={
        <HeaderRow>
          <HeaderTitle>{t('dashboard:widgets.recentActivity')}</HeaderTitle>
          <Badge variant="primary" size="sm">
            {items.length}
          </Badge>
        </HeaderRow>
      }
    >
      {items.length === 0 ? (
        <PanelEmpty icon="📋" title={emptyLabel} />
      ) : (
        <Timeline>
          {items.map((item, index) => (
            <TimelineItem key={`${item.kind}-${item.kind === 'ticket' ? item.ticket.id : item.project.id}`}>
              <Rail aria-hidden>
                <Dot $variant={item.kind} />
                {index < items.length - 1 && <Line />}
              </Rail>
              <Content>
                {item.kind === 'ticket' ? (
                  <>
                    <TopRow>
                      <ItemLink
                        type="button"
                        onClick={() => navigate(ROUTES.TICKET_DETAIL(item.ticket.id))}
                      >
                        {item.ticket.ticket_number}
                      </ItemLink>
                      <Timestamp dateTime={item.ticket.updated_at}>
                        {formatDate(item.ticket.updated_at, locale)}
                      </Timestamp>
                    </TopRow>
                    <Subject title={item.ticket.subject}>{item.ticket.subject}</Subject>
                    <MetaRow>
                      <TypeBadge $variant="ticket">
                        <HiTicket aria-hidden />
                        {t('dashboard:activity.types.ticket')}
                      </TypeBadge>
                      <StatusBadge tone={ticketStatusTone(item.ticket.status)} size="sm">
                        {translateMetricLabel(item.ticket.status, t)}
                      </StatusBadge>
                      {item.ticket.priority && (
                        <Badge variant="gray" size="sm">
                          {translateMetricLabel(item.ticket.priority, t)}
                        </Badge>
                      )}
                    </MetaRow>
                  </>
                ) : (
                  <>
                    <TopRow>
                      <ItemLink
                        type="button"
                        onClick={() => navigate(ROUTES.PROJECT_DETAIL(item.project.id))}
                      >
                        {item.project.key}
                      </ItemLink>
                      <Timestamp dateTime={item.project.updated_at}>
                        {formatDate(item.project.updated_at, locale)}
                      </Timestamp>
                    </TopRow>
                    <Subject title={item.project.name}>{item.project.name}</Subject>
                    <MetaRow>
                      <TypeBadge $variant="project">
                        <HiCollection aria-hidden />
                        {t('dashboard:activity.types.project')}
                      </TypeBadge>
                      <StatusBadge tone={projectStatusTone(item.project.status)} size="sm">
                        {translateMetricLabel(item.project.status.replace(/_/g, ' '), t)}
                      </StatusBadge>
                    </MetaRow>
                  </>
                )}
              </Content>
            </TimelineItem>
          ))}
        </Timeline>
      )}
    </Card>
  );
};
