import React from 'react';
import styled from 'styled-components';
import { useNavigate } from 'react-router-dom';
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 { 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`
  width: 10px;
  height: 10px;
  border-radius: ${({ theme }) => theme.borderRadius.full};
  background: ${({ theme }) => theme.colors.primary};
  box-shadow: 0 0 0 3px ${({ theme }) => theme.colors.primaryLight};
  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 TicketLink = 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 Timestamp = styled.time`
  font-size: ${({ theme }) => theme.typography.fontSize.xs};
  color: ${({ theme }) => theme.colors.text.tertiary};
  white-space: nowrap;
`;

interface RecentTicketsListProps {
  title: string;
  tickets: DashboardRecentTicket[];
  emptyLabel: string;
  columns: {
    ticket: string;
    subject: string;
    status: string;
    priority: string;
    updated: 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 statusTone(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';
}

export const RecentTicketsList: React.FC<RecentTicketsListProps> = ({
  title,
  tickets,
  emptyLabel,
}) => {
  const navigate = useNavigate();
  const { t, locale } = useLocale();

  return (
    <Card
      variant="elevated"
      padding="lg"
      header={
        <HeaderRow>
          <HeaderTitle>{title}</HeaderTitle>
          <Badge variant="primary" size="sm">
            {tickets.length}
          </Badge>
        </HeaderRow>
      }
    >
      {tickets.length === 0 ? (
        <PanelEmpty icon="🎫" title={emptyLabel} />
      ) : (
        <Timeline>
          {tickets.map((ticket, index) => (
            <TimelineItem key={ticket.id}>
              <Rail aria-hidden>
                <Dot />
                {index < tickets.length - 1 && <Line />}
              </Rail>
              <Content>
                <TopRow>
                  <TicketLink
                    type="button"
                    onClick={() => navigate(ROUTES.TICKET_DETAIL(ticket.id))}
                  >
                    {ticket.ticket_number}
                  </TicketLink>
                  <Timestamp dateTime={ticket.updated_at}>
                    {formatDate(ticket.updated_at, locale)}
                  </Timestamp>
                </TopRow>
                <Subject title={ticket.subject}>{ticket.subject}</Subject>
                <MetaRow>
                  <StatusBadge tone={statusTone(ticket.status)} size="sm">
                    {translateMetricLabel(ticket.status, t)}
                  </StatusBadge>
                  {ticket.priority && (
                    <Badge variant="gray" size="sm">
                      {translateMetricLabel(ticket.priority, t)}
                    </Badge>
                  )}
                </MetaRow>
              </Content>
            </TimelineItem>
          ))}
        </Timeline>
      )}
    </Card>
  );
};
