import { useEffect } from 'react';
import { useMutation } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { evaluatePrompt, type PromptCoachResult } from '../../api';

interface PromptCoachPanelProps {
  /** Current draft body from the dialog's textarea. */
  body: string;
  /** Selected piece ('auto' = unset). */
  piece?: string;
  /** Inject the rewrite suggestion back into the textarea. */
  onApplyRewrite: (text: string) => void;
}

function scoreColor(score: number, max: number): string {
  const ratio = max > 0 ? score / max : 0;
  if (ratio >= 0.75) return 'text-emerald-600 dark:text-emerald-400';
  if (ratio >= 0.4) return 'text-amber-600 dark:text-amber-400';
  return 'text-rose-600 dark:text-rose-400';
}

export function PromptCoachPanel({ body, piece, onApplyRewrite }: PromptCoachPanelProps) {
  const { t } = useTranslation('create');
  const mutation = useMutation<PromptCoachResult, Error, void>({
    mutationFn: () => evaluatePrompt({ instruction: body.trim(), piece }),
  });
  // Discard a stale evaluation once the draft (body or piece) changes, so the
  // panel never shows a score/rewrite that no longer matches the textarea —
  // and "Apply to request" can't overwrite the draft with an outdated rewrite.
  const { reset } = mutation;
  useEffect(() => {
    reset();
  }, [body, piece, reset]);
  const result = mutation.data;
  const disabled = !body.trim() || mutation.isPending;

  return (
    <div>
      <div className="flex items-center gap-2">
        <button
          type="button"
          disabled={disabled}
          onClick={() => mutation.mutate()}
          className="px-3 py-1.5 border border-accent/40 text-accent rounded-xl text-xs font-bold hover:bg-accent/5 disabled:opacity-40 disabled:cursor-not-allowed inline-flex items-center gap-1.5"
        >
          {mutation.isPending && (
            <span className="inline-block w-3 h-3 border-2 border-accent/30 border-t-accent rounded-full animate-spin" />
          )}
          {mutation.isPending ? t('coach.evaluating') : t('coach.evaluate')}
        </button>
        <span className="text-2xs text-slate-400">{t('coach.hint')}</span>
      </div>

      {mutation.isError && (
        <div className="mt-2 text-xs text-rose-600">{t('coach.failed')}</div>
      )}

      {result && (
        <div className="mt-3 space-y-3 border border-slate-200 dark:border-slate-700 rounded-xl p-4 bg-slate-50/60 dark:bg-slate-800/40">
          {/* Overall score */}
          <div className="flex items-baseline gap-2">
            <span className="text-xs font-bold text-slate-500">{t('coach.overall')}</span>
            <span className={`text-2xl font-extrabold ${scoreColor(result.overall, 100)}`}>{result.overall}</span>
            <span className="text-xs text-slate-400">/ 100</span>
          </div>

          {/* Axes */}
          {result.axes.length > 0 && (
            <div className="space-y-1.5">
              {result.axes.map((ax, i) => (
                <div key={i} className="text-xs">
                  <div className="flex items-center gap-2">
                    <span className="font-semibold text-slate-700 dark:text-slate-200">{ax.name}</span>
                    <span className={`font-bold ${scoreColor(ax.score, 10)}`}>{ax.score}/10</span>
                  </div>
                  {ax.comment && <div className="text-slate-500 dark:text-slate-400 mt-0.5">{ax.comment}</div>}
                </div>
              ))}
            </div>
          )}

          {/* Rewrite suggestion */}
          {result.rewrite && (
            <div>
              <div className="flex items-center justify-between gap-2 mb-1">
                <span className="text-xs font-bold text-slate-500">{t('coach.rewrite')}</span>
                <button
                  type="button"
                  onClick={() => onApplyRewrite(result.rewrite)}
                  className="px-2 py-0.5 rounded bg-accent text-accent-fg text-2xs font-bold hover:bg-accent-deep"
                >
                  {t('coach.applyRewrite')}
                </button>
              </div>
              <div className="text-xs text-slate-700 dark:text-slate-200 whitespace-pre-wrap bg-white dark:bg-slate-900/50 border border-slate-200 dark:border-slate-700 rounded-lg p-2.5 leading-relaxed">
                {result.rewrite}
              </div>
            </div>
          )}

          {/* Predicted piece */}
          {result.predicted_piece && (
            <div className="text-xs">
              <span className="font-bold text-slate-500">{t('coach.predictedPiece')}</span>{' '}
              <span className="font-semibold text-accent">{result.predicted_piece.name}</span>
              {result.predicted_piece.reason && (
                <span className="text-slate-500 dark:text-slate-400"> — {result.predicted_piece.reason}</span>
              )}
            </div>
          )}

          {/* MAESTRO tips */}
          {result.maestro_tips.length > 0 && (
            <div>
              <div className="text-xs font-bold text-slate-500 mb-1">{t('coach.maestroTips')}</div>
              <ul className="space-y-1">
                {result.maestro_tips.map((tip, i) => (
                  <li key={i} className="text-xs text-slate-600 dark:text-slate-300">
                    <span className="font-semibold">{tip.feature}</span>
                    {tip.suggestion && <span className="text-slate-500 dark:text-slate-400"> — {tip.suggestion}</span>}
                  </li>
                ))}
              </ul>
            </div>
          )}

          {/* Personalized notes */}
          {result.personalized.length > 0 && (
            <div>
              <div className="text-xs font-bold text-slate-500 mb-1">{t('coach.personalized')}</div>
              <ul className="list-disc list-inside space-y-0.5">
                {result.personalized.map((note, i) => (
                  <li key={i} className="text-xs text-slate-600 dark:text-slate-300">{note}</li>
                ))}
              </ul>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
