import { Card } from '../ui/card';
import { TrendingDown } from 'lucide-react';

export interface FunnelStage {
  stage: string;
  count: number;
  color?: string;
}

export interface PipelineFunnelProps {
  stages: FunnelStage[];
  title?: string;
  onStageClick?: (stage: string) => void;
}

export function PipelineFunnel({
  stages,
  title = 'Pipeline Funnel',
  onStageClick,
}: PipelineFunnelProps) {
  if (!stages || stages.length === 0) {
    return (
      <Card className="p-6">
        <h2 className="text-xl font-bold text-gray-900 mb-6">{title}</h2>
        <div className="text-center py-8 text-gray-500">
          <TrendingDown className="w-12 h-12 mx-auto mb-3 opacity-50" />
          <p className="text-sm">No pipeline data available</p>
        </div>
      </Card>
    );
  }

  const maxCount = Math.max(...stages.map(s => s.count));

  return (
    <Card className="p-6">
      <h2 className="text-xl font-bold text-gray-900 mb-6">{title}</h2>

      <div className="space-y-4" role="list" aria-label="Pipeline stages">
        {stages.map((stage, index) => {
          const percentage = maxCount > 0 ? (stage.count / maxCount) * 100 : 0;
          const stagePercentage = stages[0]?.count > 0
            ? Math.round((stage.count / stages[0].count) * 100)
            : 0;

          const defaultColors = [
            'from-accent/70 to-accent',
            'from-primary/50 to-primary/70',
            'from-primary/70 to-primary/90',
            'from-primary/90 to-primary',
          ];

          const gradientColor = stage.color || defaultColors[index % defaultColors.length];

          const nextStage = stages[index + 1];
          const conversionRate = nextStage
            ? Math.round((nextStage.count / stage.count) * 100)
            : null;

          return (
            <div
              key={stage.stage}
              role="listitem"
              className="group"
              onClick={() => onStageClick?.(stage.stage)}
            >
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm font-medium text-gray-700">
                  {stage.stage}
                </span>
                <div className="flex items-center gap-3">
                  <span className="text-xs text-gray-500">
                    {stagePercentage}% of total
                  </span>
                  <span className="text-sm font-bold text-gray-900">
                    {stage.count.toLocaleString()}
                  </span>
                </div>
              </div>

              <div className="relative h-8 bg-gray-100 rounded-md overflow-hidden">
                <button
                  className={`
                    absolute inset-y-0 left-0 bg-gradient-to-r ${gradientColor}
                    transition-all duration-300 group-hover:opacity-90
                    ${onStageClick ? 'cursor-pointer' : 'cursor-default'}
                    focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2
                  `}
                  style={{ width: `${percentage}%` }}
                  aria-label={`${stage.stage}: ${stage.count} prospects, ${stagePercentage}% of total`}
                  disabled={!onStageClick}
                >
                  <span className="sr-only">
                    {stage.stage}: {stage.count} prospects
                  </span>
                </button>

                {conversionRate !== null && (
                  <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none">
                    <span className="text-xs font-medium text-white bg-gray-900 bg-opacity-75 px-2 py-1 rounded">
                      {conversionRate}% convert to next stage
                    </span>
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>

      {stages.length >= 2 && (
        <div className="mt-6 pt-6 border-t border-gray-200">
          <div className="flex items-center justify-between text-sm">
            <span className="text-gray-600">Overall Conversion</span>
            <span className="font-bold text-gray-900">
              {Math.round((stages[stages.length - 1].count / stages[0].count) * 100)}%
              <span className="text-xs text-gray-500 ml-1">
                ({stages[0].stage} → {stages[stages.length - 1].stage})
              </span>
            </span>
          </div>
        </div>
      )}
    </Card>
  );
}
