import React from 'react';
import styled from 'styled-components';
import { Card } from '@/shared/components/ui';
import type { ChartDataset } from '@/features/dashboard/types/dashboard.types';

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

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

const BarHeader = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[2]};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
`;

const BarLabel = styled.span`
  color: ${({ theme }) => theme.colors.text.primary};
  text-align: start;
`;

const BarCount = styled.span`
  color: ${({ theme }) => theme.colors.text.secondary};
  font-variant-numeric: tabular-nums;
`;

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

const BarFill = styled.div<{ $width: number }>`
  height: 100%;
  width: ${({ $width }) => $width}%;
  background-color: ${({ theme }) => theme.colors.primary};
  border-radius: ${({ theme }) => theme.borderRadius.full};
  transition: width ${({ theme }) => theme.transitions.normal};
`;

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

interface ChartBreakdownProps {
  title: string;
  dataset: ChartDataset;
  emptyLabel: string;
}

export const ChartBreakdown: React.FC<ChartBreakdownProps> = ({
  title,
  dataset,
  emptyLabel,
}) => {
  const max = Math.max(...dataset.data, 0);

  return (
    <Card variant="outlined" padding="lg" header={title}>
      {dataset.labels.length === 0 ? (
        <EmptyMessage>{emptyLabel}</EmptyMessage>
      ) : (
        dataset.labels.map((label, index) => {
          const count = dataset.data[index] ?? 0;
          const width = max > 0 ? (count / max) * 100 : 0;

          return (
            <BarRow key={`${label}-${index}`}>
              <BarHeader>
                <BarLabel>{label}</BarLabel>
                <BarCount>{count}</BarCount>
              </BarHeader>
              <BarTrack>
                <BarFill $width={width} />
              </BarTrack>
            </BarRow>
          );
        })
      )}
    </Card>
  );
};
