import React from 'react';
import styled from 'styled-components';
import { useLocale } from '@/app/providers/LocaleProvider';
import { Spinner, StatusBadge } from '@/shared/components/ui';
import type { TicketSlaTracking } from '@/features/tickets/types/sla.types';
import type { SlaMetricBlock } from '@/features/tickets/types/sla.types';
import {
  formatMinutesRemaining,
  formatSlaDueDate,
  slaStatusTone,
} from '@/features/tickets/utils/slaDisplay';

const Wrap = styled.div`
  display: flex;
  flex-direction: column;
  gap: ${({ theme }) => theme.spacing[4]};
`;

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

const MetricBlock = styled.div`
  padding: ${({ theme }) => theme.spacing[4]};
  border-radius: ${({ theme }) => theme.borderRadius.lg};
  background-color: ${({ theme }) => theme.colors.surfaceInset};
  border: 1px solid ${({ theme }) => theme.colors.borderSoft};
`;

const MetricLabel = styled.div`
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: flex-start;
  gap: ${({ theme }) => theme.layout.sidebarRowGap};
  margin-bottom: ${({ theme }) => theme.spacing[3]};
  font-size: ${({ theme }) => theme.typography.fontSize.xs};
  font-weight: ${({ theme }) => theme.typography.fontWeight.medium};
  color: ${({ theme }) => theme.colors.text.tertiary};
  text-align: start;
  min-width: 0;
`;

const MetricValue = styled.span`
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  color: ${({ theme }) => theme.colors.text.primary};
  font-variant-numeric: tabular-nums;
`;

const ProgressTrack = styled.div`
  height: 5px;
  border-radius: ${({ theme }) => theme.borderRadius.full};
  background-color: ${({ theme }) => theme.colors.borderSoft};
  overflow: hidden;
`;

const ProgressFill = styled.div<{ $pct: number; $tone: 'active' | 'warning' | 'breached' }>`
  height: 100%;
  width: ${({ $pct }) => Math.min(100, Math.max(0, $pct))}%;
  border-radius: inherit;
  background-color: ${({ theme, $tone }) => theme.colors.status[$tone].text};
  opacity: 0.85;
  transition: width ${({ theme }) => theme.transitions.normal};
`;

const PausedBanner = styled.div`
  padding: ${({ theme }) => `${theme.spacing[2]} ${theme.spacing[3]}`};
  border-radius: ${({ theme }) => theme.borderRadius.md};
  background-color: ${({ theme }) => theme.colors.status.paused.bg};
  border: 1px solid ${({ theme }) => theme.colors.status.paused.border};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  color: ${({ theme }) => theme.colors.status.paused.text};
  text-align: start;
`;

const Message = styled.div`
  margin: 0;
  display: flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[2]};
  color: ${({ theme }) => theme.colors.text.secondary};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  text-align: start;
`;

function metricProgressTone(metric: SlaMetricBlock): 'active' | 'warning' | 'breached' {
  if (metric.is_breached) return 'breached';
  if (metric.is_warning) return 'warning';
  return 'active';
}

function SlaMetricRow({
  label,
  metric,
  locale,
}: {
  label: string;
  metric: SlaMetricBlock;
  locale: string;
}) {
  const pct = metric.percentage_elapsed ?? 0;
  const tone = metricProgressTone(metric);

  return (
    <MetricBlock>
      <MetricLabel>
        <span>{label}</span>
        <MetricValue>{formatMinutesRemaining(metric.time_remaining_minutes)}</MetricValue>
      </MetricLabel>
      <ProgressTrack aria-hidden>
        <ProgressFill $pct={pct} $tone={tone} />
      </ProgressTrack>
      <MetricLabel style={{ marginTop: 8, marginBottom: 0 }}>
        <span>{formatSlaDueDate(metric.due_at, locale)}</span>
      </MetricLabel>
    </MetricBlock>
  );
}

interface SlaSummaryProps {
  sla?: TicketSlaTracking | null;
  isLoading?: boolean;
  isError?: boolean;
}

export const SlaSummary: React.FC<SlaSummaryProps> = ({ sla, isLoading, isError }) => {
  const { t, locale } = useLocale();

  if (isLoading) {
    return (
      <Message role="status">
        <Spinner size="sm" /> {t('tickets:slaStates.loading')}
      </Message>
    );
  }

  if (isError) {
    return <Message role="alert">{t('tickets:slaStates.error')}</Message>;
  }

  if (!sla) {
    return <Message>{t('tickets:slaStates.none')}</Message>;
  }

  return (
    <Wrap>
      <StatusRow>
        <StatusBadge tone={slaStatusTone(sla.sla_status)} size="sm" dot>
          {sla.sla_status_label}
        </StatusBadge>
      </StatusRow>
      <SlaMetricRow
        label={t('tickets:sla.responseDue')}
        metric={sla.response}
        locale={locale}
      />
      <SlaMetricRow
        label={t('tickets:sla.resolutionDue')}
        metric={sla.resolution}
        locale={locale}
      />
      {sla.is_paused && (
        <PausedBanner role="status">{t('tickets:sla.yes')} — {t('tickets:sla.paused')}</PausedBanner>
      )}
    </Wrap>
  );
};
