/**
 * Readability Panel Component
 *
 * Displays Flesch-Kincaid readability score in the editor sidebar.
 *
 * @package
 */

import { __ } from '@wordpress/i18n';
import { useSelect } from '@wordpress/data';
import { useEffect, useState, useCallback, useMemo } from '@wordpress/element';
import { Spinner, Notice } from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';
import { debounce } from 'lodash';

const cancelDebounced = (fn) => {
  if (fn && typeof fn.cancel === 'function') {
    fn.cancel();
  }
};

const ReadabilityPanel = ({ postId }) => {
  const [score, setScore] = useState(null);
  const [level, setLevel] = useState(null);
  const [grade, setGrade] = useState(null);
  const [stats, setStats] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  const postContent = useSelect((select) => {
    const { getEditedPostContent } = select('core/editor');
    return getEditedPostContent();
  }, []);

  const fetchReadabilityScore = useCallback(async (currentPostId) => {
    if (!currentPostId) return;

    setIsLoading(true);
    setError(null);

    try {
      const response = await apiFetch({
        path: `/prorank-seo/v1/readability-score/${currentPostId}`,
        method: 'GET',
      });

      if (response.success && response.data) {
        setScore(response.data.score);
        setLevel(response.data.level);
        setGrade(response.data.grade);
        setStats(response.data.stats);
      } else {
        throw new Error(response.message || __('Error fetching readability score', 'prorank-seo'));
      }
    } catch (err) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  }, []);

  const debouncedFetch = useMemo(
    () =>
      debounce((currentPostId) => {
        fetchReadabilityScore(currentPostId);
      }, 800),
    [fetchReadabilityScore]
  );

  useEffect(() => {
    if (postId && postContent) {
      debouncedFetch(postId);
    }

    return () => {
      cancelDebounced(debouncedFetch);
    };
  }, [postId, postContent, debouncedFetch]);

  const getScoreColor = (scoreValue) => {
    if (scoreValue >= 60) return 'success';
    if (scoreValue >= 30) return 'warning';
    return 'error';
  };

  const getHelpText = (scoreValue) => {
    if (scoreValue >= 60) {
      return __('Your content is easy to read. Great job!', 'prorank-seo');
    }
    if (scoreValue >= 30) {
      return __(
        'Your content readability could be improved. Consider using shorter sentences and simpler words.',
        'prorank-seo'
      );
    }
    return __(
      'Your content is difficult to read. Try breaking up long sentences and using simpler vocabulary.',
      'prorank-seo'
    );
  };

  return (
    <div
      className="prorank-readability-panel"
      role="region"
      aria-label={__('Readability Analysis', 'prorank-seo')}
    >
      {isLoading && (
        <div className="prorank-readability-loading">
          <Spinner />
          <span className="screen-reader-text">
            {__('Calculating readability score…', 'prorank-seo')}
          </span>
        </div>
      )}

      {error && !isLoading && (
        <Notice status="error" isDismissible={false} className="prorank-readability-error">
          {error}
        </Notice>
      )}

      {!isLoading && !error && score !== null && (
        <div className="prorank-readability-results">
          <div className="prorank-readability-score-container">
            <div
              className={`prorank-readability-score-badge prorank-readability-score-badge--${getScoreColor(score)}`}
              aria-live="polite"
              aria-atomic="true"
            >
              {Math.round(score)}
            </div>
            <div className="prorank-readability-score-info">
              <p className="prorank-readability-score-title">
                {__('Readability', 'prorank-seo')}
              </p>
              <p className="prorank-readability-level-text">{level}</p>
              <p className="prorank-readability-grade-text">{grade}</p>
            </div>
          </div>

          {stats && (
            <div className="prorank-readability-stats-row">
              <span className="prorank-readability-stat">
                <span className="prorank-readability-stat-label">⏱</span>
                <span className="prorank-readability-stat-value">
                  {stats.estimated_reading_time} min read
                </span>
              </span>
            </div>
          )}

          <div className={`prorank-readability-help ${score >= 60 ? 'prorank-readability-help--success' : ''}`}>
            <div className="prorank-readability-help-content">
              <p className="prorank-readability-help-text">{getHelpText(score)}</p>
            </div>
          </div>
        </div>
      )}

      {!isLoading && !error && score === null && postContent && (
        <Notice status="info" isDismissible={false} className="prorank-readability-no-content">
          {__('Add more content to see readability analysis.', 'prorank-seo')}
        </Notice>
      )}

      {!postContent && (
        <div className="prorank-readability-empty">
          <p>{__('Start writing to see your readability score.', 'prorank-seo')}</p>
        </div>
      )}
    </div>
  );
};

export default ReadabilityPanel;
