import { useState } from 'react';
import { formatPercent } from '../../lib/format';
import type { SentimentResponse } from '../../lib/types';

interface SentimentPanelProps {
  data: SentimentResponse;
}

const classificationColors: Record<string, string> = {
  bullish: 'text-emerald-400',
  bearish: 'text-red-400',
  neutral: 'text-gray-300',
};

const recommendationStyle: Record<string, string> = {
  buy: 'bg-emerald-500/15 text-emerald-300 border-emerald-500/30',
  hold: 'bg-amber-500/15 text-amber-300 border-amber-500/30',
  avoid: 'bg-red-500/15 text-red-300 border-red-500/30',
};

export function SentimentPanel({ data }: SentimentPanelProps) {
  const [expanded, setExpanded] = useState<boolean>(false);
  const latest = data.scores[0];

  return (
    <div className="glass p-5">
      <h3 className="mb-3 text-xs font-medium uppercase tracking-widest text-gray-500">Sentiment</h3>
      {latest ? (
        <>
          {latest.recommendation && (
            <div className="mb-3 flex items-center justify-between rounded-lg border bg-white/[0.02] px-3 py-2">
              <span className="text-xs uppercase tracking-wider text-gray-500">LLM view</span>
              <span className={`rounded-md border px-2.5 py-1 text-sm font-semibold uppercase tracking-wide ${recommendationStyle[latest.recommendation] ?? 'text-gray-300'}`}>
                {latest.recommendation}
              </span>
            </div>
          )}
          <div className="space-y-2.5 text-sm">
            <div className="flex justify-between">
              <span className="text-gray-400">Classification</span>
              <span className={classificationColors[latest.classification] ?? 'text-gray-300'}>
                {latest.classification}
              </span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-400">Confidence</span>
              <span className="text-gray-200">{formatPercent(latest.confidence)}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-400">Dimension Score</span>
              <span className="text-gray-200">{data.dimension_score !== null ? Math.round(data.dimension_score) : '—'}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-gray-400">Sources</span>
              <span className="text-gray-200">{data.count}</span>
            </div>
          </div>

          <button
            type="button"
            onClick={() => setExpanded((prev) => !prev)}
            className="mt-3 flex w-full items-center justify-center gap-1.5 rounded-md border border-white/[0.08] py-1.5 text-xs text-gray-400 hover:bg-white/[0.04] hover:text-gray-200 transition-colors"
            aria-expanded={expanded}
          >
            {expanded ? 'Hide' : 'Full analysis & sources'}
            <svg
              className={`h-3.5 w-3.5 transition-transform ${expanded ? 'rotate-180' : ''}`}
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={2}
            >
              <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
            </svg>
          </button>

          {expanded && (
            <div className="mt-3 space-y-3 border-t border-white/10 pt-3">
              <div>
                <span className="text-xs font-medium uppercase tracking-widest text-gray-500">Reasoning</span>
                <p className="mt-1 text-sm text-gray-300">
                  {latest.reasoning || 'No reasoning available'}
                </p>
              </div>

              {latest.citations.length > 0 && (
                <div>
                  <span className="text-xs font-medium uppercase tracking-widest text-gray-500">Citations</span>
                  <ul className="mt-1 space-y-1">
                    {latest.citations.map((citation, idx) => (
                      <li key={idx}>
                        <a
                          href={citation.url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="text-sm text-blue-400 hover:text-blue-300 underline break-all"
                        >
                          {citation.title || citation.url}
                        </a>
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </div>
          )}
        </>
      ) : (
        <p className="text-sm text-gray-500">No sentiment data available</p>
      )}
    </div>
  );
}
