import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router';
import PageMeta from '../../components/common/PageMeta';
import PageHeader from '../../components/common/PageHeader';
import { optimizerApi } from '../../api/optimizer.api';
import { fetchContent, Content as ContentType } from '../../services/api';
import { useToast } from '../../components/ui/toast/ToastContainer';
import { OptimizationScores } from '../../components/optimizer/OptimizationScores';
import { ArrowLeftIcon, BoltIcon } from '../../icons';

export default function AnalysisPreview() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const toast = useToast();

  const [content, setContent] = useState<ContentType | null>(null);
  const [scores, setScores] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [analyzing, setAnalyzing] = useState(false);

  useEffect(() => {
    if (id) {
      loadContent();
      analyzeContent();
    }
  }, [id]);

  const loadContent = async () => {
    try {
      setLoading(true);
      // Note: fetchContent by ID would need to be implemented or use a different endpoint
      // For now, we'll fetch and filter
      const data = await fetchContent({ page_size: 1000 });
      const found = data.results?.find((c: ContentType) => c.id === parseInt(id || '0'));
      if (found) {
        setContent(found);
      }
    } catch (error: any) {
      console.error('Error loading content:', error);
      toast.error(`Failed to load content: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  const analyzeContent = async () => {
    if (!id) return;
    
    try {
      setAnalyzing(true);
      const result = await optimizerApi.analyze(parseInt(id));
      setScores(result.scores);
    } catch (error: any) {
      console.error('Error analyzing content:', error);
      toast.error(`Failed to analyze content: ${error.message}`);
    } finally {
      setAnalyzing(false);
    }
  };

  return (
    <>
      <PageMeta title="Content Analysis" description="Preview content optimization scores" />
      
      <div className="space-y-6">
        <div className="flex items-center justify-between mb-6">
          <PageHeader
            title="Content Analysis"
            lastUpdated={new Date()}
            badge={{
              icon: <BoltIcon />,
              color: 'orange',
            }}
          />
          <button
            onClick={() => navigate(-1)}
            className="inline-flex items-center gap-2 px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
          >
            <ArrowLeftIcon className="w-4 h-4" />
            Back
          </button>
        </div>
        <p className="text-gray-600 dark:text-gray-400 mb-6">
          Preview optimization scores without optimizing
        </p>

        {loading || analyzing ? (
          <div className="text-center py-12">
            <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mb-3"></div>
            <p className="text-gray-600 dark:text-gray-400">
              {loading ? 'Loading content...' : 'Analyzing content...'}
            </p>
          </div>
        ) : !content ? (
          <div className="text-center py-12">
            <BoltIcon className="w-12 h-12 text-gray-400 dark:text-gray-500 mx-auto mb-3 opacity-50" />
            <p className="text-gray-600 dark:text-gray-400 mb-2">Content not found</p>
            <p className="text-sm text-gray-400 dark:text-gray-500">Unable to load content for analysis</p>
          </div>
        ) : !scores ? (
          <div className="text-center py-12">
            <BoltIcon className="w-12 h-12 text-gray-400 dark:text-gray-500 mx-auto mb-3 opacity-50" />
            <p className="text-gray-600 dark:text-gray-400 mb-2">Analysis unavailable</p>
            <p className="text-sm text-gray-400 dark:text-gray-500">Unable to analyze this content</p>
          </div>
        ) : content && scores ? (
          <div className="space-y-6">
            {/* Content Info */}
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
              <h2 className="text-xl font-semibold text-gray-900 dark:text-white mb-2">
                {content.title || 'Untitled'}
              </h2>
              <p className="text-sm text-gray-600 dark:text-gray-400">
                Source: {content.source} | 
                Status: {content.status}
              </p>
            </div>

            {/* Scores */}
            <OptimizationScores scores={scores} />

            {/* Stage 3: Cluster Dimension Scorecards */}
            {(scores.has_cluster_mapping || scores.has_taxonomy_mapping || scores.has_attributes) && (
              <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">Metadata Coverage</h3>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div className={`p-4 rounded-lg border-2 ${
                    scores.has_cluster_mapping
                      ? 'border-green-500 bg-green-50 dark:bg-green-900/20'
                      : 'border-red-500 bg-red-50 dark:bg-red-900/20'
                  }`}>
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-sm font-medium text-gray-700 dark:text-gray-300">Cluster Mapping</span>
                      {scores.has_cluster_mapping ? (
                        <span className="text-green-600 dark:text-green-400">✓</span>
                      ) : (
                        <span className="text-red-600 dark:text-red-400">✗</span>
                      )}
                    </div>
                    <div className="text-xs text-gray-600 dark:text-gray-400">
                      {scores.has_cluster_mapping
                        ? 'Content is mapped to cluster'
                        : 'Missing cluster mapping'}
                    </div>
                  </div>

                  <div className={`p-4 rounded-lg border-2 ${
                    scores.has_taxonomy_mapping
                      ? 'border-green-500 bg-green-50 dark:bg-green-900/20'
                      : 'border-yellow-500 bg-yellow-50 dark:bg-yellow-900/20'
                  }`}>
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-sm font-medium text-gray-700 dark:text-gray-300">Taxonomy Mapping</span>
                      {scores.has_taxonomy_mapping ? (
                        <span className="text-green-600 dark:text-green-400">✓</span>
                      ) : (
                        <span className="text-yellow-600 dark:text-yellow-400">⚠</span>
                      )}
                    </div>
                    <div className="text-xs text-gray-600 dark:text-gray-400">
                      {scores.has_taxonomy_mapping
                        ? 'Content is mapped to taxonomy'
                        : 'Taxonomy mapping recommended'}
                    </div>
                  </div>

                  <div className={`p-4 rounded-lg border-2 ${
                    scores.has_attributes
                      ? 'border-green-500 bg-green-50 dark:bg-green-900/20'
                      : 'border-yellow-500 bg-yellow-50 dark:bg-yellow-900/20'
                  }`}>
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-sm font-medium text-gray-700 dark:text-gray-300">Attributes</span>
                      {scores.has_attributes ? (
                        <span className="text-green-600 dark:text-green-400">✓</span>
                      ) : (
                        <span className="text-yellow-600 dark:text-yellow-400">⚠</span>
                      )}
                    </div>
                    <div className="text-xs text-gray-600 dark:text-gray-400">
                      {scores.has_attributes
                        ? 'Content has attributes'
                        : 'Attributes recommended for products/services'}
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* Score Details */}
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">Score Details</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <span className="text-sm text-gray-600 dark:text-gray-400">Word Count:</span>
                  <span className="ml-2 font-medium text-gray-900 dark:text-white">{scores.word_count || 0}</span>
                </div>
                <div>
                  <span className="text-sm text-gray-600 dark:text-gray-400">Has Meta Title:</span>
                  <span className="ml-2 font-medium text-gray-900 dark:text-white">
                    {scores.has_meta_title ? 'Yes' : 'No'}
                  </span>
                </div>
                <div>
                  <span className="text-sm text-gray-600 dark:text-gray-400">Has Meta Description:</span>
                  <span className="ml-2 font-medium text-gray-900 dark:text-white">
                    {scores.has_meta_description ? 'Yes' : 'No'}
                  </span>
                </div>
                <div>
                  <span className="text-sm text-gray-600 dark:text-gray-400">Has Primary Keyword:</span>
                  <span className="ml-2 font-medium text-gray-900 dark:text-white">
                    {scores.has_primary_keyword ? 'Yes' : 'No'}
                  </span>
                </div>
                <div>
                  <span className="text-sm text-gray-600 dark:text-gray-400">Internal Links:</span>
                  <span className="ml-2 font-medium text-gray-900 dark:text-white">
                    {scores.internal_links_count || 0}
                  </span>
                </div>
                {/* Stage 3: Metadata completeness score */}
                {scores.metadata_completeness_score !== undefined && (
                  <div>
                    <span className="text-sm text-gray-600 dark:text-gray-400">Metadata Completeness:</span>
                    <span className="ml-2 font-medium text-gray-900 dark:text-white">
                      {scores.metadata_completeness_score.toFixed(1)}%
                    </span>
                  </div>
                )}
              </div>
            </div>

            {/* Stage 3: Next Action Cards */}
            {(!scores.has_cluster_mapping || !scores.has_taxonomy_mapping || !scores.has_attributes || (scores.metadata_completeness_score !== undefined && scores.metadata_completeness_score < 80)) && (
              <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">Recommended Actions</h3>
                <div className="space-y-3">
                  {!scores.has_cluster_mapping && (
                    <div className="p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
                      <div className="flex items-start gap-2">
                        <span className="text-blue-600 dark:text-blue-400 font-bold">1.</span>
                        <div className="flex-1">
                          <div className="font-medium text-blue-900 dark:text-blue-300">Map Content to Cluster</div>
                          <div className="text-sm text-blue-700 dark:text-blue-400 mt-1">
                            Assign this content to a keyword cluster to improve internal linking and SEO structure.
                          </div>
                        </div>
                      </div>
                    </div>
                  )}
                  {!scores.has_taxonomy_mapping && (
                    <div className="p-3 bg-purple-50 dark:bg-purple-900/20 border border-purple-200 dark:border-purple-800 rounded-lg">
                      <div className="flex items-start gap-2">
                        <span className="text-purple-600 dark:text-purple-400 font-bold">2.</span>
                        <div className="flex-1">
                          <div className="font-medium text-purple-900 dark:text-purple-300">Add Taxonomy Mapping</div>
                          <div className="text-sm text-purple-700 dark:text-purple-400 mt-1">
                            Categorize this content with a taxonomy for better organization and navigation.
                          </div>
                        </div>
                      </div>
                    </div>
                  )}
                  {!scores.has_attributes && (content?.content_type === 'product' || content?.content_type === 'service') && (
                    <div className="p-3 bg-orange-50 dark:bg-orange-900/20 border border-orange-200 dark:border-orange-800 rounded-lg">
                      <div className="flex items-start gap-2">
                        <span className="text-orange-600 dark:text-orange-400 font-bold">3.</span>
                        <div className="flex-1">
                          <div className="font-medium text-orange-900 dark:text-orange-300">Add Product/Service Attributes</div>
                          <div className="text-sm text-orange-700 dark:text-orange-400 mt-1">
                            Add attributes like specifications, features, or modifiers to enhance content completeness.
                          </div>
                        </div>
                      </div>
                    </div>
                  )}
                  {scores.metadata_completeness_score !== undefined && scores.metadata_completeness_score < 80 && (
                    <div className="p-3 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg">
                      <div className="flex items-start gap-2">
                        <span className="text-amber-600 dark:text-amber-400 font-bold">4.</span>
                        <div className="flex-1">
                          <div className="font-medium text-amber-900 dark:text-amber-300">Improve Metadata Completeness</div>
                          <div className="text-sm text-amber-700 dark:text-amber-400 mt-1">
                            Current score: {scores.metadata_completeness_score.toFixed(1)}%. Complete missing metadata fields to reach 80%+.
                          </div>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>
        ) : (
          <div className="text-center py-12">
            <p className="text-gray-600 dark:text-gray-400">Content not found</p>
          </div>
        )}
      </div>
    </>
  );
}

