import { ScrollArea } from '@/Components/ui/scroll-area';

import QualityMetricCard from './QualityMetricCard';

export interface EeatPillarMetrics {
  score: number;
  signal_count: number;
  detected: string[];
  suggestions: string[];
}

export interface GeoPillarMetrics {
  score: number;
  signal_count: number;
  detected: string[];
  suggestions: string[];
}

export interface QualityMetrics {
  flesch_kincaid_grade: number | null;
  avg_sentence_length: number | null;
  paragraph_count: number;
  passive_voice_percentage: number | null;
  word_count: number;
  h1_count: number;
  h2_count: number;
  h3_count: number;
  h4_count: number;
  h5_count: number;
  h6_count: number;
  image_count: number;
  internal_link_count: number;
  external_link_count: number;
  eeat_overall_score?: number | null;
  eeat_experience?: EeatPillarMetrics | null;
  eeat_expertise?: EeatPillarMetrics | null;
  eeat_authoritativeness?: EeatPillarMetrics | null;
  eeat_trustworthiness?: EeatPillarMetrics | null;
  geo_overall_score?: number | null;
  geo_direct_answers?: GeoPillarMetrics | null;
  geo_faq_structure?: GeoPillarMetrics | null;
  geo_structured_data?: GeoPillarMetrics | null;
  geo_concept_clarity?: GeoPillarMetrics | null;
  geo_citation_readiness?: GeoPillarMetrics | null;
  geo_schema_opportunities?: GeoPillarMetrics | null;
}

interface QualityScoreSidebarProps {
  metrics: QualityMetrics | null;
  isLoading?: boolean;
  className?: string;
}

function getReadabilityStatus(grade: number | null): 'good' | 'warning' | 'error' | 'neutral' {
  if (grade === null) return 'neutral';
  if (grade <= 8) return 'good'; // Elementary/middle school level
  if (grade <= 12) return 'warning'; // High school level
  return 'error'; // College level+
}

function getReadabilitySuggestion(grade: number | null): string | undefined {
  if (grade === null) return undefined;
  if (grade <= 8) return 'Content is easy to read for most audiences';
  if (grade <= 12)
    return 'Content is at high school reading level. Consider simplifying for broader audience.';
  return 'Content is at college reading level. Consider breaking up complex sentences and using simpler words.';
}

function getSentenceLengthStatus(length: number | null): 'good' | 'warning' | 'error' | 'neutral' {
  if (length === null) return 'neutral';
  if (length <= 20) return 'good';
  if (length <= 25) return 'warning';
  return 'error';
}

function getSentenceLengthSuggestion(length: number | null): string | undefined {
  if (length === null) return undefined;
  if (length <= 20) return 'Sentences are concise and easy to follow';
  if (length <= 25) return 'Consider breaking up some longer sentences for better readability';
  return 'Sentences are too long. Break them up for improved clarity.';
}

function getPassiveVoiceStatus(
  percentage: number | null,
): 'good' | 'warning' | 'error' | 'neutral' {
  if (percentage === null) return 'neutral';
  if (percentage <= 10) return 'good';
  if (percentage <= 20) return 'warning';
  return 'error';
}

function getPassiveVoiceSuggestion(percentage: number | null): string | undefined {
  if (percentage === null) return undefined;
  if (percentage <= 10) return 'Good use of active voice makes content more engaging';
  if (percentage <= 20) return 'Consider converting some passive constructions to active voice';
  return 'Too much passive voice. Use active voice to make content more direct and engaging.';
}

function getWordCountStatus(count: number): 'good' | 'warning' | 'error' | 'neutral' {
  if (count < 300) return 'error'; // Too short for SEO
  if (count < 600) return 'warning'; // Short but acceptable
  if (count >= 1500) return 'good'; // Comprehensive content
  return 'neutral'; // Moderate length
}

function getWordCountSuggestion(count: number): string | undefined {
  if (count < 300) return 'Content is too short. Aim for at least 600 words for better SEO.';
  if (count < 600) return 'Content is short. Consider expanding to 800+ words for better depth.';
  if (count >= 1500) return 'Comprehensive content length that provides value to readers';
  return 'Moderate content length. Consider expanding for more comprehensive coverage.';
}

function getHeadingStatus(
  h1Count: number,
  totalHeadings: number,
): 'good' | 'warning' | 'error' | 'neutral' {
  // Should have exactly 1 H1
  if (h1Count === 0) return 'error';
  if (h1Count > 1) return 'error';

  // Should have at least 2 subheadings (H2+)
  if (totalHeadings < 2) return 'warning';

  return 'good';
}

function getHeadingSuggestion(h1Count: number, totalHeadings: number): string | undefined {
  if (h1Count === 0) return 'Add an H1 heading as the main title of your content';
  if (h1Count > 1) return 'Use only one H1 heading. Use H2-H6 for subheadings.';
  if (totalHeadings < 2) return 'Add more subheadings (H2-H3) to improve content structure';
  return 'Good heading structure helps readers scan your content';
}

function getLinkStatus(
  internalCount: number,
  externalCount: number,
  wordCount: number,
): 'good' | 'warning' | 'error' | 'neutral' {
  const totalLinks = internalCount + externalCount;

  // Rough guideline: 2-4 links per 500 words
  const expectedMinLinks = Math.floor((wordCount / 500) * 2);

  if (totalLinks === 0) return 'error';
  if (totalLinks < expectedMinLinks) return 'warning';
  if (internalCount >= externalCount) return 'good'; // More internal than external is good

  return 'neutral';
}

function getLinkSuggestion(
  internalCount: number,
  externalCount: number,
  _wordCount: number,
): string | undefined {
  const totalLinks = internalCount + externalCount;

  if (totalLinks === 0) return 'Add internal and external links to provide context and authority';
  if (internalCount === 0 && externalCount > 0)
    return 'Add internal links to help readers discover related content on your site';
  if (internalCount < externalCount)
    return 'Consider adding more internal links to keep readers on your site';
  return 'Good balance of internal and external links';
}

export default function QualityScoreSidebar({
  metrics,
  isLoading = false,
  className,
}: QualityScoreSidebarProps) {
  if (isLoading) {
    return (
      <aside className={className}>
        <div className="mb-4">
          <h2 className="text-lg font-semibold">Quality Metrics</h2>
          <p className="text-sm text-muted-foreground">Analyzing...</p>
        </div>
        <div className="space-y-3">
          {Array.from({ length: 5 }).map((_, i) => (
            <div key={i} className="h-14 rounded-lg bg-muted animate-pulse" />
          ))}
        </div>
      </aside>
    );
  }

  if (!metrics) {
    return (
      <aside className={className}>
        <div className="space-y-4">
          <h2 className="text-lg font-semibold">Quality Metrics</h2>
          <p className="text-sm text-muted-foreground">Start typing to see quality metrics</p>
        </div>
      </aside>
    );
  }

  const totalHeadings =
    metrics.h2_count + metrics.h3_count + metrics.h4_count + metrics.h5_count + metrics.h6_count;

  return (
    <aside className={className}>
      <div className="mb-4">
        <h2 className="text-lg font-semibold">Quality Metrics</h2>
        <p className="text-sm text-muted-foreground">Live content analysis</p>
      </div>

      <ScrollArea className="h-[calc(100vh-8rem)] md:h-[calc(100vh-10rem)] lg:h-[calc(100vh-12rem)]">
        <div className="space-y-4 pr-4">
          {/* Readability Section */}
          <div>
            <h3 className="mb-3 text-sm font-medium text-muted-foreground">Readability</h3>
            <div className="space-y-3">
              <QualityMetricCard
                label="Reading Level"
                value={metrics.flesch_kincaid_grade}
                format="grade"
                status={getReadabilityStatus(metrics.flesch_kincaid_grade)}
                description="Flesch-Kincaid grade level"
                suggestion={getReadabilitySuggestion(metrics.flesch_kincaid_grade)}
              />
              <QualityMetricCard
                label="Avg. Sentence Length"
                value={metrics.avg_sentence_length}
                format="decimal"
                status={getSentenceLengthStatus(metrics.avg_sentence_length)}
                description="Words per sentence"
                suggestion={getSentenceLengthSuggestion(metrics.avg_sentence_length)}
              />
              <QualityMetricCard
                label="Passive Voice"
                value={metrics.passive_voice_percentage}
                format="percent"
                status={getPassiveVoiceStatus(metrics.passive_voice_percentage)}
                description="Percentage of passive sentences"
                suggestion={getPassiveVoiceSuggestion(metrics.passive_voice_percentage)}
              />
            </div>
          </div>

          {/* Content Structure Section */}
          <div>
            <h3 className="mb-3 text-sm font-medium text-muted-foreground">Content Structure</h3>
            <div className="space-y-3">
              <QualityMetricCard
                label="Word Count"
                value={metrics.word_count}
                format="number"
                status={getWordCountStatus(metrics.word_count)}
                description="Total words in content"
                suggestion={getWordCountSuggestion(metrics.word_count)}
              />
              <QualityMetricCard
                label="Paragraphs"
                value={metrics.paragraph_count}
                format="number"
                status="neutral"
                description="Number of paragraphs"
              />
              <QualityMetricCard
                label="Heading Structure"
                value={metrics.h1_count}
                format="number"
                status={getHeadingStatus(metrics.h1_count, totalHeadings)}
                description={`H1: ${metrics.h1_count}, H2: ${metrics.h2_count}, H3: ${metrics.h3_count}`}
                suggestion={getHeadingSuggestion(metrics.h1_count, totalHeadings)}
              />
            </div>
          </div>

          {/* Links & Media Section */}
          <div>
            <h3 className="mb-3 text-sm font-medium text-muted-foreground">Links & Media</h3>
            <div className="space-y-3">
              <QualityMetricCard
                label="Internal Links"
                value={metrics.internal_link_count}
                format="number"
                status={metrics.internal_link_count > 0 ? 'good' : 'warning'}
                description="Links to your own content"
                suggestion={
                  metrics.internal_link_count === 0
                    ? 'Add internal links to related content'
                    : undefined
                }
              />
              <QualityMetricCard
                label="External Links"
                value={metrics.external_link_count}
                format="number"
                status={metrics.external_link_count > 0 ? 'neutral' : 'warning'}
                description="Links to external sources"
                suggestion={
                  metrics.external_link_count === 0 ? 'Consider citing external sources' : undefined
                }
              />
              <QualityMetricCard
                label="Total Links"
                value={metrics.internal_link_count + metrics.external_link_count}
                format="number"
                status={getLinkStatus(
                  metrics.internal_link_count,
                  metrics.external_link_count,
                  metrics.word_count,
                )}
                description={`${metrics.internal_link_count} internal, ${metrics.external_link_count} external`}
                suggestion={getLinkSuggestion(
                  metrics.internal_link_count,
                  metrics.external_link_count,
                  metrics.word_count,
                )}
              />
              <QualityMetricCard
                label="Images"
                value={metrics.image_count}
                format="number"
                status="neutral"
                description="Number of images in content"
              />
            </div>
          </div>
        </div>
      </ScrollArea>
    </aside>
  );
}
