import React from 'react';

import EmptyState from '../agent-analytics/EmptyState';
import type { VisibilityProblem } from '../../service/visibility/visibility.interface';

import { severityToTone, toneToBadgeClass } from './helpers';

interface ProblemsListProps {
  problems: VisibilityProblem[];
}

/**
 * Render the "Problems detected this week" section. Every user-visible
 * string (title, severity, reason) is taken verbatim from the backend -
 * we only pick the tone from the canonical ``severity`` key.
 */
const ProblemsList = ({ problems }: ProblemsListProps): JSX.Element => {
  if (problems.length === 0) {
    return <EmptyState message="No problems detected this week - great job!" />;
  }

  return (
    <div className="flex flex-col gap-3">
      {problems.map(problem => {
        const tone = severityToTone(problem.severity);
        const reasonText = problem.reason_localized || problem.reason;
        const titleText = problem.type_label || problem.type;

        return (
          <div
            key={problem.id}
            className="bg-white rounded-xl border border-gray-200 p-4 flex flex-col gap-2"
          >
            <div className="flex items-center justify-between gap-2 flex-wrap">
              <h3 className="text-base font-semibold text-gray-900">
                {titleText}
              </h3>
              {problem.severity_label && (
                <span
                  className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${toneToBadgeClass(tone)}`}
                >
                  {problem.severity_label}
                </span>
              )}
            </div>
            <p className="text-sm text-gray-700">{reasonText}</p>
            {problem.fix &&
              Array.isArray(problem.fix.steps) &&
              problem.fix.steps.length > 0 && (
                <div className="flex flex-col gap-1">
                  <p className="text-xs font-semibold text-gray-900">
                    Fix plan
                  </p>
                  <ul className="list-disc pl-5 text-xs text-gray-700">
                    {problem.fix.steps.map((step, index) => (
                      <li key={index}>{step}</li>
                    ))}
                  </ul>
                </div>
              )}
          </div>
        );
      })}
    </div>
  );
};

export default ProblemsList;
