import React, { useState } from 'react';
import { AlertCircle, CheckCircle, Zap, TrendingUp, BookOpen, Lightbulb } from 'lucide-react';

interface PostQuality {
  score: number;
  suggestions: Suggestion[];
  stats: Stats;
}

interface Suggestion {
  type: 'grammar' | 'formatting' | 'engagement' | 'readability' | 'length' | 'content';
  severity: 'low' | 'medium' | 'high';
  message: string;
  fix?: string;
}

interface Stats {
  wordCount: number;
  charCount: number;
  readingTime: number;
  sentenceCount: number;
  avgWordLength: number;
}

export function PostImprover() {
  const [postContent, setPostContent] = useState('');
  const [quality, setQuality] = useState<PostQuality | null>(null);
  const [improvedPost, setImprovedPost] = useState('');

  const analyzePost = (text: string): PostQuality => {
    const suggestions: Suggestion[] = [];
    let score = 100; // Start with perfect score

    // 1. GRAMMAR & SPELLING CHECKS
    const commonMistakes = [
      { pattern: /\byour\b(?=\s+going)/gi, fix: 'you\'re', msg: 'Should be "you\'re" (you are)' },
      { pattern: /\bits\b(?=\s+[\w]+\s+(and|or|but))/gi, fix: 'it\'s', msg: 'Should be "it\'s" (it is)' },
      { pattern: /\byour\s+going/gi, fix: 'you\'re going', msg: 'Your vs You\'re confusion' },
      { pattern: /\btheir\s+are/gi, fix: 'they\'re are', msg: 'Their vs They\'re confusion' },
      { pattern: /\b([A-Z])\s{2,}([A-Z])/g, fix: '$1 $2', msg: 'Multiple spaces between words' },
    ];

    commonMistakes.forEach(mistake => {
      if (mistake.pattern.test(text)) {
        suggestions.push({
          type: 'grammar',
          severity: 'medium',
          message: mistake.msg,
          fix: mistake.fix
        });
        score -= 5;
      }
    });

    // 2. FORMATTING CHECKS
    const hasProperPunctuation = /[.!?]$/.test(text.trim());
    if (!hasProperPunctuation) {
      suggestions.push({
        type: 'formatting',
        severity: 'low',
        message: 'Post should end with proper punctuation',
        fix: 'Add . ! or ?'
      });
      score -= 3;
    }

    const paragraphs = text.split('\n\n').filter(p => p.trim());
    if (paragraphs.length > 1) {
      suggestions.push({
        type: 'formatting',
        severity: 'low',
        message: 'Good use of paragraphs',
      });
    }

    // Capitalize first letter
    if (text.length > 0 && text[0] !== text[0].toUpperCase()) {
      suggestions.push({
        type: 'formatting',
        severity: 'low',
        message: 'Post should start with capital letter',
      });
      score -= 2;
    }

    // 3. LENGTH ANALYSIS
    const wordCount = text.trim().split(/\s+/).length;
    const charCount = text.length;

    if (wordCount < 10) {
      suggestions.push({
        type: 'length',
        severity: 'high',
        message: 'Post is too short (less than 10 words)',
        fix: 'Add more detail and context'
      });
      score -= 15;
    } else if (wordCount < 20) {
      suggestions.push({
        type: 'length',
        severity: 'medium',
        message: 'Post is quite short. Consider adding more details',
      });
      score -= 8;
    } else if (wordCount > 500) {
      suggestions.push({
        type: 'length',
        severity: 'low',
        message: 'Post is quite long. Consider breaking it into paragraphs',
      });
      score -= 2;
    } else {
      suggestions.push({
        type: 'length',
        severity: 'low',
        message: `Good post length (${wordCount} words)`,
      });
    }

    // 4. READABILITY ANALYSIS
    const sentenceCount = text.split(/[.!?]+/).filter(s => s.trim()).length;
    const avgWordLength = charCount / Math.max(wordCount, 1);
    const avgSentenceLength = wordCount / Math.max(sentenceCount, 1);

    if (avgSentenceLength > 25) {
      suggestions.push({
        type: 'readability',
        severity: 'medium',
        message: 'Sentences are too long. Break them up for better readability',
      });
      score -= 8;
    }

    if (avgWordLength > 5.5) {
      suggestions.push({
        type: 'readability',
        severity: 'low',
        message: 'Use simpler words for better readability',
      });
      score -= 3;
    }

    // 5. ENGAGEMENT SCORE
    const hasQuestionMarks = /\?/.test(text);
    const hasExclamation = /!/.test(text);
    const hasEmojis = /[\u{1F300}-\u{1F9FF}]/gu.test(text);

    let engagementScore = 0;
    if (hasQuestionMarks) {
      suggestions.push({
        type: 'engagement',
        severity: 'low',
        message: 'Good! Questions encourage responses',
      });
      engagementScore += 10;
    }
    if (hasExclamation) {
      engagementScore += 5;
    }
    if (hasEmojis) {
      suggestions.push({
        type: 'engagement',
        severity: 'low',
        message: 'Good use of emojis for engagement',
      });
      engagementScore += 5;
    }

    if (engagementScore === 0) {
      suggestions.push({
        type: 'engagement',
        severity: 'medium',
        message: 'Add questions or exclamations to boost engagement',
      });
      score -= 5;
    }

    // 6. CONTENT SUGGESTIONS
    if (text.includes('http') || text.includes('http://') || text.includes('https://')) {
      suggestions.push({
        type: 'content',
        severity: 'low',
        message: 'Good! You included links',
      });
    }

    const wordFreq: { [key: string]: number } = {};
    text.toLowerCase().split(/\s+/).forEach(word => {
      wordFreq[word] = (wordFreq[word] || 0) + 1;
    });

    const repetitiveWords = Object.entries(wordFreq)
      .filter(([_, count]) => count > 4 && _.length > 3)
      .map(([word]) => word);

    if (repetitiveWords.length > 0) {
      suggestions.push({
        type: 'content',
        severity: 'low',
        message: `Try to vary your vocabulary - "${repetitiveWords[0]}" is repeated often`,
      });
      score -= 2;
    }

    // Ensure score doesn't go below 0
    score = Math.max(0, Math.min(100, score));

    return {
      score,
      suggestions: suggestions.sort((a, b) => {
        const severityOrder = { high: 0, medium: 1, low: 2 };
        return severityOrder[a.severity] - severityOrder[b.severity];
      }),
      stats: {
        wordCount,
        charCount,
        readingTime: Math.ceil(wordCount / 200),
        sentenceCount,
        avgWordLength: Math.round(avgWordLength * 10) / 10,
      }
    };
  };

  const handleAnalyze = () => {
    if (postContent.trim()) {
      const analyzed = analyzePost(postContent);
      setQuality(analyzed);
    }
  };

  const improvePost = () => {
    let improved = postContent;

    // Apply basic improvements
    improved = improved.replace(/your(?=\s+going)/gi, "you're");
    improved = improved.replace(/their(?=\s+are)/gi, "they're");
    improved = improved.replace(/its(?=\s+[\w]+\s+and|\s+[\w]+\s+or)/gi, "it's");
    improved = improved.replace(/\s{2,}/g, ' '); // Remove extra spaces
    
    // Capitalize first letter
    if (improved) {
      improved = improved.charAt(0).toUpperCase() + improved.slice(1);
    }

    // Ensure ending punctuation
    if (improved && !/[.!?]$/.test(improved.trim())) {
      improved = improved.trim() + '.';
    }

    setImprovedPost(improved);
  };

  const getSeverityColor = (severity: string) => {
    switch (severity) {
      case 'high': return 'text-red-500';
      case 'medium': return 'text-yellow-500';
      case 'low': return 'text-blue-500';
      default: return 'text-gray-500';
    }
  };

  const getSeverityBg = (severity: string) => {
    switch (severity) {
      case 'high': return 'bg-red-500/10 border-red-500/30';
      case 'medium': return 'bg-yellow-500/10 border-yellow-500/30';
      case 'low': return 'bg-blue-500/10 border-blue-500/30';
      default: return 'bg-gray-500/10 border-gray-500/30';
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-slate-900 to-slate-800 p-6">
      <div className="max-w-4xl mx-auto">
        <div className="mb-8">
          <h1 className="text-4xl font-bold text-white mb-2">Post Quality Improver</h1>
          <p className="text-slate-400">Analyze and enhance your posts by up to 50%</p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Input Section */}
          <div>
            <h2 className="text-xl font-semibold text-white mb-4">Your Post</h2>
            <textarea
              value={postContent}
              onChange={(e) => setPostContent(e.target.value)}
              placeholder="Paste your post content here..."
              className="w-full h-64 p-4 bg-slate-700 text-white rounded-lg border border-slate-600 focus:border-blue-500 outline-none resize-none font-mono text-sm"
            />
            <button
              onClick={handleAnalyze}
              className="mt-4 w-full px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg transition flex items-center justify-center gap-2"
            >
              <Zap className="w-5 h-5" /> Analyze Quality
            </button>
          </div>

          {/* Quality Results */}
          <div>
            {quality ? (
              <div>
                <h2 className="text-xl font-semibold text-white mb-4">Quality Score</h2>
                
                {/* Score Circle */}
                <div className="bg-slate-700 rounded-lg p-6 text-center mb-4 border border-slate-600">
                  <div className="text-6xl font-bold text-blue-400 mb-2">{quality.score}%</div>
                  <div className="text-slate-300 mb-4">Overall Quality</div>
                  <div className="w-full bg-slate-600 rounded-full h-3">
                    <div 
                      className="bg-gradient-to-r from-blue-500 to-blue-400 h-3 rounded-full transition-all"
                      style={{ width: `${quality.score}%` }}
                    />
                  </div>
                </div>

                {/* Stats */}
                <div className="grid grid-cols-2 gap-2 text-sm mb-4">
                  <div className="bg-slate-700 p-3 rounded border border-slate-600">
                    <div className="text-slate-400">Words</div>
                    <div className="text-white font-bold">{quality.stats.wordCount}</div>
                  </div>
                  <div className="bg-slate-700 p-3 rounded border border-slate-600">
                    <div className="text-slate-400">Reading Time</div>
                    <div className="text-white font-bold">{quality.stats.readingTime}m</div>
                  </div>
                  <div className="bg-slate-700 p-3 rounded border border-slate-600">
                    <div className="text-slate-400">Sentences</div>
                    <div className="text-white font-bold">{quality.stats.sentenceCount}</div>
                  </div>
                  <div className="bg-slate-700 p-3 rounded border border-slate-600">
                    <div className="text-slate-400">Avg Word Length</div>
                    <div className="text-white font-bold">{quality.stats.avgWordLength}</div>
                  </div>
                </div>

                <button
                  onClick={improvePost}
                  className="w-full px-4 py-2 bg-green-600 hover:bg-green-700 text-white font-semibold rounded transition flex items-center justify-center gap-2 text-sm"
                >
                  <Lightbulb className="w-4 h-4" /> Auto-Improve Post
                </button>
              </div>
            ) : (
              <div className="bg-slate-700 rounded-lg p-6 text-center border border-slate-600 h-64 flex items-center justify-center">
                <div className="text-slate-400">Paste content and click "Analyze Quality" to get started</div>
              </div>
            )}
          </div>
        </div>

        {/* Suggestions */}
        {quality && quality.suggestions.length > 0 && (
          <div className="mt-8">
            <h2 className="text-xl font-semibold text-white mb-4">Improvement Suggestions</h2>
            <div className="space-y-3">
              {quality.suggestions.map((suggestion, idx) => (
                <div 
                  key={idx} 
                  className={`p-4 rounded-lg border ${getSeverityBg(suggestion.severity)} backdrop-blur`}
                >
                  <div className="flex items-start gap-3">
                    {suggestion.severity === 'high' ? (
                      <AlertCircle className="w-5 h-5 text-red-500 flex-shrink-0 mt-1" />
                    ) : suggestion.severity === 'medium' ? (
                      <TrendingUp className="w-5 h-5 text-yellow-500 flex-shrink-0 mt-1" />
                    ) : (
                      <CheckCircle className="w-5 h-5 text-blue-500 flex-shrink-0 mt-1" />
                    )}
                    <div>
                      <div className="text-white font-semibold capitalize">{suggestion.type}</div>
                      <div className="text-slate-300 text-sm mt-1">{suggestion.message}</div>
                      {suggestion.fix && (
                        <div className="text-slate-400 text-xs mt-2 italic">💡 Suggestion: {suggestion.fix}</div>
                      )}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Improved Post Preview */}
        {improvedPost && (
          <div className="mt-8">
            <h2 className="text-xl font-semibold text-white mb-4">Improved Post</h2>
            <div className="bg-slate-700 rounded-lg p-6 border border-green-500/30">
              <p className="text-slate-100 mb-4">{improvedPost}</p>
              <button
                onClick={() => navigator.clipboard.writeText(improvedPost)}
                className="px-4 py-2 bg-green-600 hover:bg-green-700 text-white text-sm font-semibold rounded transition"
              >
                📋 Copy Improved Post
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

export default PostImprover;
