import { Search, Loader2, Settings } from 'lucide-react';

import { useMemo, useState } from 'react';

import { Link } from '@inertiajs/react';

import { Button } from '@/Components/ui/button';
import { Input } from '@/Components/ui/input';
import { ScrollArea } from '@/Components/ui/scroll-area';
import type { TermStatus } from '@/hooks/useContentScore';
import { formatNumber } from '@/lib/format';
import { cn } from '@/lib/utils';

import ContentScoreGauge from './ContentScoreGauge';
import QualityMetricCard from './QualityMetricCard';
import TermChecklistItem from './TermChecklistItem';

interface ContentScoreSidebarProps {
  overallScore: number | null;
  termCoverage: { score: number; covered: number; total: number; percentage: number } | null;
  wordCountScore: {
    score: number;
    draft_count: number;
    competitor_avg: number;
    competitor_median: number;
  } | null;
  structureScore: { score: number } | null;
  readabilityScore: { score: number } | null;
  wordCountRange?: { min: number; max: number } | null;
  terms: TermStatus[];
  isLoading: boolean;
  isAnalyzing: boolean;
  hasSerpKey: boolean;
  analysisStatus: 'idle' | 'pending' | 'processing' | 'completed' | 'failed';
  analysisError: string | null;
  scoreError: string | null;
  onAnalyze: (keyword: string) => void;
  onCancel?: () => void;
}

function getScoreStatus(score: number): 'good' | 'warning' | 'error' | 'neutral' {
  if (score >= 70) return 'good';
  if (score >= 40) return 'warning';
  return 'error';
}

function wordCountStatus(ratio: number): { label: string; colorClass: string } {
  if (ratio < 0.5) return { label: 'Well below average', colorClass: 'text-destructive' };
  if (ratio <= 0.8) return { label: 'Below average', colorClass: 'text-warning' };
  if (ratio <= 1.2) return { label: 'On target', colorClass: 'text-success' };
  return { label: 'Above average', colorClass: 'text-info' };
}

const STATUS_ORDER: Record<TermStatus['status'], number> = { missing: 0, underused: 1, covered: 2 };

export default function ContentScoreSidebar({
  overallScore,
  termCoverage,
  wordCountScore,
  wordCountRange,
  structureScore,
  readabilityScore,
  terms,
  isLoading,
  isAnalyzing,
  hasSerpKey,
  analysisStatus,
  analysisError,
  scoreError,
  onAnalyze,
  onCancel,
}: ContentScoreSidebarProps) {
  const [keyword, setKeyword] = useState('');

  const handleAnalyze = () => {
    const trimmed = keyword.trim();
    if (trimmed.length >= 2) {
      onAnalyze(trimmed);
    }
  };

  // Sort: missing first, then underused, then covered; within each group by importance_rank ascending
  const sortedTerms = useMemo(
    () =>
      [...terms].sort((a, b) => {
        const statusDiff = STATUS_ORDER[a.status] - STATUS_ORDER[b.status];
        if (statusDiff !== 0) return statusDiff;
        return a.importance_rank - b.importance_rank;
      }),
    [terms],
  );

  // No SERP key configured
  if (!hasSerpKey) {
    return (
      <div className="space-y-3">
        <h3 className="text-sm font-semibold">Content Score</h3>
        <p className="text-sm text-muted-foreground">
          Add your DataForSEO credentials to unlock content scoring against SERP competitors.
        </p>
        <Button variant="outline" size="sm" asChild>
          <Link href={route('settings.serp')}>
            <Settings className="h-4 w-4 mr-1.5" />
            Configure SERP API
          </Link>
        </Button>
      </div>
    );
  }

  // No analysis started
  if (analysisStatus === 'idle') {
    return (
      <div className="space-y-3">
        <h3 className="text-sm font-semibold">Content Score</h3>
        <p className="text-sm text-muted-foreground">
          Enter the keyword you want this page to rank for.
        </p>
        <div className="flex gap-2">
          <label htmlFor="keyword-input-idle" className="sr-only">
            Target keyword
          </label>
          <Input
            id="keyword-input-idle"
            placeholder="e.g. best project management tools"
            value={keyword}
            onChange={(e) => setKeyword(e.target.value)}
            onKeyDown={(e) => e.key === 'Enter' && handleAnalyze()}
            className="text-sm"
          />
          <Button
            size="sm"
            onClick={handleAnalyze}
            disabled={keyword.trim().length < 2}
            aria-label="Analyze keyword"
          >
            <Search className="h-4 w-4" />
          </Button>
        </div>
      </div>
    );
  }

  // Analysis in progress
  if (isAnalyzing) {
    return (
      <div className="space-y-3">
        <h3 className="text-sm font-semibold">Content Score</h3>
        <div className="flex items-center gap-2 text-sm text-muted-foreground">
          <Loader2 className="h-4 w-4 animate-spin shrink-0" />
          <span>
            {analysisStatus === 'pending' ? 'Starting analysis...' : 'Analyzing competitors...'}
          </span>
        </div>
        <div className="h-1.5 w-full rounded-full bg-muted overflow-hidden">
          <div className="h-full rounded-full bg-primary animate-progress-fill" />
        </div>
        <div className="flex items-center justify-between">
          <p className="text-xs text-muted-foreground">
            Fetching top 10 SERP results and extracting NLP terms...
          </p>
          {onCancel && (
            <Button variant="ghost" size="sm" onClick={onCancel} className="h-6 text-xs px-2">
              Cancel
            </Button>
          )}
        </div>
      </div>
    );
  }

  // Analysis failed
  if (analysisStatus === 'failed') {
    return (
      <div className="space-y-3">
        <h3 className="text-sm font-semibold">Content Score</h3>
        <p className="text-sm text-destructive">
          {analysisError || 'Analysis failed. Try again.'}
        </p>
        <div className="flex gap-2">
          <label htmlFor="keyword-input-retry" className="sr-only">
            Target keyword
          </label>
          <Input
            id="keyword-input-retry"
            placeholder="e.g. best project management tools"
            value={keyword}
            onChange={(e) => setKeyword(e.target.value)}
            onKeyDown={(e) => e.key === 'Enter' && handleAnalyze()}
            className="text-sm"
          />
          <Button size="sm" onClick={handleAnalyze} disabled={keyword.trim().length < 2}>
            Retry
          </Button>
        </div>
      </div>
    );
  }

  // Analysis completed — show scores
  const coveredCount = terms.filter((t) => t.status === 'covered').length;
  const underusedCount = terms.filter((t) => t.status === 'underused').length;
  const missingCount = terms.filter((t) => t.status === 'missing').length;

  // Compact word count status: always visible, not buried inside the competitor panel
  const wcStatus =
    wordCountScore && wordCountScore.competitor_avg > 0
      ? wordCountStatus(wordCountScore.draft_count / wordCountScore.competitor_avg)
      : null;

  // Top 3 missing high-importance terms sorted by importance_rank ascending
  const quickWins = terms
    .filter((t) => t.status === 'missing')
    .sort((a, b) => a.importance_rank - b.importance_rank)
    .slice(0, 3);

  return (
    <div className="space-y-4">
      {/* Header with gauge */}
      <div className="flex items-center gap-3">
        {overallScore !== null ? (
          <div className="animate-in fade-in-0 zoom-in-95 duration-300">
            <ContentScoreGauge score={overallScore} size={64} />
          </div>
        ) : (
          <div className="flex items-center justify-center w-16 h-16">
            {isLoading ? (
              <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
            ) : (
              <span className="text-2xl font-bold text-muted-foreground">--</span>
            )}
          </div>
        )}
        <div>
          <h3 className="text-sm font-semibold">Content Score</h3>
          <p className="text-xs text-muted-foreground">vs SERP competitors</p>
        </div>
      </div>

      {/* Compact word count status — always visible without opening the competitor panel */}
      {!isLoading && wcStatus && wordCountScore && (
        <p className="text-xs text-muted-foreground -mt-1 flex flex-wrap items-center gap-x-1">
          <span>
            {formatNumber(wordCountScore.draft_count)}
            {wordCountRange
              ? ` / ${formatNumber(wordCountRange.min)}–${formatNumber(wordCountRange.max)} words`
              : ` / ~${formatNumber(wordCountScore.competitor_avg)} words`}
          </span>
          <span>·</span>
          <span className={cn('font-medium', wcStatus.colorClass)}>{wcStatus.label}</span>
        </p>
      )}

      {scoreError && <p className="text-xs text-destructive">{scoreError}</p>}

      {/* Sub-scores */}
      <div className="grid grid-cols-2 gap-2">
        <QualityMetricCard
          label="Term Coverage"
          value={termCoverage?.percentage ?? null}
          format="percent"
          status={termCoverage ? getScoreStatus(termCoverage.score) : 'neutral'}
          suggestion={
            termCoverage ? `${termCoverage.covered}/${termCoverage.total} terms` : undefined
          }
        />
        <QualityMetricCard
          label="Word Count"
          value={wordCountScore?.draft_count ?? null}
          status={wordCountScore ? getScoreStatus(wordCountScore.score) : 'neutral'}
          suggestion={
            wordCountScore?.competitor_median
              ? `Target: ~${wordCountScore.competitor_median}`
              : undefined
          }
        />
        <QualityMetricCard
          label="Structure"
          value={structureScore?.score ?? null}
          status={structureScore ? getScoreStatus(structureScore.score) : 'neutral'}
        />
        <QualityMetricCard
          label="Readability"
          value={readabilityScore?.score ?? null}
          status={readabilityScore ? getScoreStatus(readabilityScore.score) : 'neutral'}
        />
      </div>

      {/* Term status summary — persists during re-scoring */}
      {(sortedTerms.length > 0 || isLoading) && terms.length > 0 && (
        <div className="flex gap-3 text-xs text-muted-foreground">
          <span className="text-success">{coveredCount} covered</span>
          <span className="text-warning">{underusedCount} underused</span>
          <span className="text-destructive">{missingCount} missing</span>
        </div>
      )}

      {/* Quick Wins — persists during re-scoring, fades to signal staleness */}
      {quickWins.length > 0 && (
        <div
          className={cn(
            'rounded-lg bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 p-3 space-y-2 transition-opacity duration-300',
            isLoading && 'opacity-50',
          )}
        >
          <h4 className="text-xs font-semibold text-amber-800 dark:text-amber-200">Quick Wins</h4>
          <ul className="space-y-1.5">
            {quickWins.map((term) => (
              <li key={term.term} className="text-xs text-amber-900 dark:text-amber-100">
                Add &ldquo;{term.term}&rdquo; to your intro or a subheading.
              </li>
            ))}
          </ul>
        </div>
      )}

      {/* Term checklist — sorted: missing → underused → covered, by importance */}
      {(sortedTerms.length > 0 || isLoading) && (
        <div>
          <h4 className="text-xs font-medium text-muted-foreground mb-1">Terms to Include</h4>
          {sortedTerms.length > 0 ? (
            <ScrollArea className="max-h-75">
              <div className="space-y-0.5">
                {sortedTerms.map((term) => (
                  <TermChecklistItem key={term.term} term={term} />
                ))}
              </div>
            </ScrollArea>
          ) : (
            <p className="text-xs text-muted-foreground py-2">Scoring content against terms…</p>
          )}
        </div>
      )}

      {/* Re-analyze option */}
      <div className="pt-2 border-t">
        <div className="flex gap-2">
          <label htmlFor="keyword-input-reanalyze" className="sr-only">
            New keyword
          </label>
          <Input
            id="keyword-input-reanalyze"
            placeholder="e.g. best project management tools"
            value={keyword}
            onChange={(e) => setKeyword(e.target.value)}
            onKeyDown={(e) => e.key === 'Enter' && handleAnalyze()}
            className="text-sm h-8"
          />
          <Button
            size="sm"
            variant="outline"
            onClick={handleAnalyze}
            disabled={keyword.trim().length < 2}
            className="h-8"
            aria-label="Re-analyze with new keyword"
          >
            <Search className="h-3.5 w-3.5" />
          </Button>
        </div>
      </div>
    </div>
  );
}
