"use client";
import { useState } from "react";
import {
  FiCheckCircle,
  FiAlertTriangle,
  FiInfo,
  FiDownload,
  FiExternalLink,
} from "react-icons/fi";

const SEOChecker = () => {
  const [url, setUrl] = useState("");
  const [seoData, setSeoData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [activeTab, setActiveTab] = useState("summary");

  const checkSEO = async () => {
    if (!url) {
      setError("Please enter a URL");
      return;
    }

    setLoading(true);
    setError(null);
    setSeoData(null);

    try {
      const response = await fetch("/api/seo-check", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ url }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Failed to analyze URL");
      }

      const data = await response.json();
      setSeoData(data);
      setActiveTab("summary");
    } catch (err) {
      setError(err.message || "Failed to check SEO");
      console.error("SEO check error:", err);
    } finally {
      setLoading(false);
    }
  };

  const calculateScores = (data) => {
    if (!data) return { score: 0, deductions: [], categoryScores: {} };

    let score = 100;
    const deductions = [];

    // Title (15 points)
    if (!data.title.exists) {
      score -= 15;
      deductions.push({
        item: "Title Tag",
        points: -15,
        message: "Missing completely",
      });
    } else {
      if (data.title.text.length < 30) {
        score -= 7;
        deductions.push({
          item: "Title Length",
          points: -7,
          message: "Too short (under 30 chars)",
        });
      } else if (data.title.text.length > 60) {
        score -= 5;
        deductions.push({
          item: "Title Length",
          points: -5,
          message: "Too long (over 60 chars)",
        });
      }
    }

    // Meta Description (10 points)
    if (!data.meta.description.exists) {
      score -= 10;
      deductions.push({
        item: "Meta Description",
        points: -10,
        message: "Missing completely",
      });
    } else {
      if (data.meta.description.text.length < 50) {
        score -= 5;
        deductions.push({
          item: "Meta Description",
          points: -5,
          message: "Too short (under 50 chars)",
        });
      } else if (data.meta.description.text.length > 160) {
        score -= 3;
        deductions.push({
          item: "Meta Description",
          points: -3,
          message: "Too long (over 160 chars)",
        });
      }
    }

    // Headings (15 points)
    if (data.headings.h1.count === 0) {
      score -= 10;
      deductions.push({
        item: "H1 Heading",
        points: -10,
        message: "Missing H1 tag",
      });
    } else if (data.headings.h1.count > 1) {
      score -= 7;
      deductions.push({
        item: "H1 Heading",
        points: -7,
        message: "Multiple H1 tags",
      });
    }

    if (data.headings.h2.count < 2) {
      score -= 3;
      deductions.push({
        item: "H2 Headings",
        points: -3,
        message: "Not enough H2 tags",
      });
    }

    // Images (10 points)
    if (data.images?.withoutAlt > 0) {
      const deduction = Math.min(10, data.images.withoutAlt * 2);
      score -= deduction;
      deductions.push({
        item: "Image Alt Tags",
        points: -deduction,
        message: `${data.images.withoutAlt} images missing alt text`,
      });
    }

    // Links (10 points)
    if (data.links?.internal < 5) {
      score -= 5;
      deductions.push({
        item: "Internal Links",
        points: -5,
        message: "Few internal links",
      });
    }

    if (data.links?.external === 0) {
      score -= 2;
      deductions.push({
        item: "External Links",
        points: -2,
        message: "No external links",
      });
    }

    // Mobile (10 points)
    if (!data.meta?.viewport?.mobileFriendly) {
      score -= 10;
      deductions.push({
        item: "Mobile Friendly",
        points: -10,
        message: "No responsive viewport",
      });
    }

    // Performance (10 points)
    if (data.pageLoadTime > 3) {
      const deduction = Math.min(10, Math.floor(data.pageLoadTime - 2) * 2);
      score -= deduction;
      deductions.push({
        item: "Page Speed",
        points: -deduction,
        message: `Slow load time (${data.pageLoadTime}s)`,
      });
    }

    // Technical SEO (20 points)
    if (!data.technical?.canonical?.exists) {
      score -= 5;
      deductions.push({
        item: "Canonical URL",
        points: -5,
        message: "Missing canonical tag",
      });
    }

    if (!data.security?.https) {
      score -= 5;
      deductions.push({
        item: "HTTPS",
        points: -5,
        message: "Not using HTTPS",
      });
    }

    if (data.technical?.schemaMarkup?.count === 0) {
      score -= 5;
      deductions.push({
        item: "Schema Markup",
        points: -5,
        message: "Missing structured data",
      });
    }

    if (!data.meta?.robots?.content) {
      score -= 5;
      deductions.push({
        item: "Robots Meta",
        points: -5,
        message: "Missing robots meta tag",
      });
    }

    // Calculate category scores
    const categoryScores = {
      onPage: calculateOnPageScore(data),
      technical: calculateTechnicalScore(data),
      content: calculateContentScore(data),
      mobile: calculateMobileScore(data),
    };

    return {
      score: Math.max(0, Math.round(score)),
      deductions,
      categoryScores,
    };
  };

  const calculateOnPageScore = (data) => {
    let score = 30;
    if (!data.title.exists) score -= 15;
    if (!data.meta.description.exists) score -= 10;
    if (data.headings.h1.count !== 1) score -= 5;
    return Math.max(0, score);
  };

  const calculateTechnicalScore = (data) => {
    let score = 30;
    if (!data.technical.canonical.exists) score -= 5;
    if (!data.security.https) score -= 5;
    if (data.technical.schemaMarkup.count === 0) score -= 5;
    if (!data.meta.robots.content) score -= 5;
    return Math.max(0, score);
  };

  const calculateContentScore = (data) => {
    let score = 20;
    if (data.content.wordCount < 300) score -= 5;
    if (data.content.readability < 60) score -= 5;
    if (data.images.withoutAlt > 0) score -= 5;
    return Math.max(0, score);
  };

  const calculateMobileScore = (data) => {
    let score = 20;
    if (!data.meta.viewport.mobileFriendly) score -= 10;
    if (data.pageLoadTime > 3) score -= 5;
    return Math.max(0, score);
  };

  const renderReportSection = () => {
    if (!seoData) return null;

    const { score, deductions, categoryScores } = calculateScores(seoData);

    switch (activeTab) {
      case "summary":
        return (
          <div className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              <ScoreCard
                title="Overall Score"
                score={score}
                max={100}
                description="Composite SEO health score"
              />
              <ScoreCard
                title="On-Page SEO"
                score={categoryScores.onPage}
                max={30}
                description="Title, meta, headings"
              />
              <ScoreCard
                title="Technical SEO"
                score={categoryScores.technical}
                max={30}
                description="Canonical, schema, security"
              />
              <ScoreCard
                title="Content Quality"
                score={categoryScores.content}
                max={20}
                description="Word count, readability"
              />
            </div>

            <div className="bg-white p-6 rounded-lg shadow">
              <h3 className="text-lg font-semibold mb-4">
                Key Recommendations
              </h3>
              <ul className="space-y-3">
                {deductions
                  .sort((a, b) => a.points - b.points)
                  .map((item, i) => (
                    <li key={i} className="flex items-start">
                      {item.points < -7 ? (
                        <FiAlertTriangle className="text-red-500 mt-1 mr-2 flex-shrink-0" />
                      ) : (
                        <FiInfo className="text-yellow-500 mt-1 mr-2 flex-shrink-0" />
                      )}
                      <div className="flex-1">
                        <div className="flex justify-between">
                          <span className="font-medium">{item.item}</span>
                          <span
                            className={`font-mono ${
                              item.points < 0
                                ? "text-red-500"
                                : "text-green-500"
                            }`}
                          >
                            {item.points}
                          </span>
                        </div>
                        <p className="text-gray-600 text-sm">{item.message}</p>
                        <div className="flex justify-between mt-1">
                          <span className="text-xs text-gray-500">
                            Priority:{" "}
                            {item.points < -7
                              ? "High"
                              : item.points < -4
                              ? "Medium"
                              : "Low"}
                          </span>
                          {item.item === "HTTPS" && !seoData.security.https && (
                            <a
                              href={`https://${seoData.url.replace(
                                /^https?:\/\//,
                                ""
                              )}`}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="text-xs text-blue-500 flex items-center"
                            >
                              Try HTTPS <FiExternalLink className="ml-1" />
                            </a>
                          )}
                        </div>
                      </div>
                    </li>
                  ))}
              </ul>
            </div>
          </div>
        );

      case "details":
        return (
          <div className="space-y-6">
            <Section title="On-Page SEO">
              <CheckItem
                label="Title Tag"
                status={seoData.title.exists ? "good" : "bad"}
                goodText={`"${seoData.title.text}" (${seoData.title.text.length} chars)`}
                badText="Missing"
                recommendation="Include 1 title tag (50-60 chars)"
              />
              <CheckItem
                label="Meta Description"
                status={seoData.meta.description.exists ? "good" : "bad"}
                goodText={`"${seoData.meta.description.text}" (${seoData.meta.description.text.length} chars)`}
                badText="Missing"
                recommendation="Write a compelling description (120-160 chars)"
              />
              <CheckItem
                label="Heading Structure"
                status={
                  seoData.headings.h1.count === 1 &&
                  seoData.headings.h2.count >= 2
                    ? "good"
                    : "bad"
                }
                goodText={`1 H1 and ${seoData.headings.h2.count} H2 headings`}
                badText={
                  seoData.headings.h1.count === 0
                    ? "No H1 heading"
                    : seoData.headings.h1.count > 1
                    ? "Multiple H1 headings"
                    : "Not enough H2 headings"
                }
                recommendation="Use one H1 and multiple H2s for proper structure"
              />
            </Section>

            <Section title="Technical SEO">
              <CheckItem
                label="Canonical URL"
                status={seoData.technical.canonical.exists ? "good" : "bad"}
                goodText={`Points to: ${seoData.technical.canonical.url}`}
                badText="Missing"
                recommendation="Add canonical URL tag to avoid duplicate content"
              />
              <CheckItem
                label="Schema Markup"
                status={
                  seoData.technical.schemaMarkup.count > 0 ? "good" : "bad"
                }
                goodText={`${seoData.technical.schemaMarkup.count} schema items found`}
                badText="Missing"
                recommendation="Implement structured data for rich snippets"
              />
              <CheckItem
                label="HTTPS"
                status={seoData.security.https ? "good" : "bad"}
                goodText="Secure connection"
                badText="Not secure"
                recommendation="Install SSL certificate"
              />
            </Section>

            <Section title="Content Quality">
              <CheckItem
                label="Word Count"
                status={seoData.content.wordCount >= 300 ? "good" : "bad"}
                goodText={`${seoData.content.wordCount} words (good length)`}
                badText={`${seoData.content.wordCount} words (too short)`}
                recommendation="Aim for at least 300 words of quality content"
              />
              <CheckItem
                label="Readability"
                status={seoData.content.readability >= 60 ? "good" : "bad"}
                goodText={`Score: ${seoData.content.readability}/100 (good)`}
                badText={`Score: ${seoData.content.readability}/100 (needs improvement)`}
                recommendation="Simplify complex sentences and reduce jargon"
              />
              <CheckItem
                label="Image Alt Text"
                status={seoData.images.withoutAlt === 0 ? "good" : "bad"}
                goodText="All images have alt text"
                badText={`${seoData.images.withoutAlt} images missing alt text`}
                recommendation="Add descriptive alt text to all images"
              />
            </Section>
          </div>
        );

      case "full-report":
        return (
          <div className="space-y-8 bg-white p-6 rounded-lg shadow">
            <div className="prose max-w-none">
              <h2 className="text-2xl font-bold">Comprehensive SEO Report</h2>
              <p className="text-gray-600">
                Generated for {seoData.url} on{" "}
                {new Date(seoData.analyzedAt).toLocaleString()}
              </p>

              <div className="my-6 p-4 bg-gray-50 rounded-lg">
                <h3 className="text-xl font-semibold mb-2">
                  Executive Summary
                </h3>
                <p>
                  Overall SEO Score: <strong>{score}/100</strong> -{" "}
                  {score >= 80
                    ? "Excellent"
                    : score >= 60
                    ? "Good"
                    : score >= 40
                    ? "Needs Improvement"
                    : "Poor"}
                </p>
                <p className="mt-2">
                  {score >= 80
                    ? "Your site has strong SEO fundamentals."
                    : score >= 60
                    ? "Your site has decent SEO but could use some improvements."
                    : score >= 40
                    ? "Your site needs significant SEO improvements."
                    : "Your site requires urgent SEO attention."}
                </p>
              </div>

              <h3 className="text-xl font-semibold mt-8 mb-4">
                Detailed Findings
              </h3>

              <h4 className="font-semibold mt-6">On-Page SEO</h4>
              <ul className="list-disc pl-5 space-y-2">
                <li>
                  <strong>Title Tag:</strong>{" "}
                  {seoData.title.exists
                    ? `"${seoData.title.text}" (${seoData.title.text.length} characters, ${seoData.title.status})`
                    : "Missing"}
                </li>
                <li>
                  <strong>Meta Description:</strong>{" "}
                  {seoData.meta.description.exists
                    ? `"${seoData.meta.description.text}" (${seoData.meta.description.text.length} characters, ${seoData.meta.description.status})`
                    : "Missing"}
                </li>
                <li>
                  <strong>Headings:</strong> H1={seoData.headings.h1.count},{" "}
                  H2={seoData.headings.h2.count}, H3={seoData.headings.h3.count} 
                </li>
              </ul>

              <h4 className="font-semibold mt-6">Technical SEO</h4>
              <ul className="list-disc pl-5 space-y-2">
                <li>
                  <strong>Canonical URL:</strong>{" "}
                  {seoData.technical.canonical.exists
                    ? seoData.technical.canonical.url
                    : "Missing"}
                </li>
                <li>
                  <strong>Schema Markup:</strong>{" "}
                  {seoData.technical.schemaMarkup.count > 0
                    ? `${seoData.technical.schemaMarkup.count} schema items found`
                    : "None detected"}
                </li>
                <li>
                  <strong>HTTPS:</strong>{" "}
                  {seoData.security.https ? "Enabled" : "Not enabled"}
                </li>
              </ul>

              <h4 className="font-semibold mt-6">Contents</h4>
              <ul className="list-disc pl-5 space-y-2">
                <li>
                  <strong>Word Count:</strong> {seoData.content.wordCount} words
                </li>
                <li>
                  <strong>Images:</strong> {seoData.images.total} total,{" "}
                  {seoData.images.withoutAlt} missing alt text
                </li>
              </ul>
            </div>

            <div className="flex justify-end">
              <button
                onClick={() => window.print()}
                className="bg-blue-600 text-white px-4 py-2 rounded-md flex items-center"
              >
                <FiDownload className="mr-2" />
                Download PDF Report
              </button>
            </div>
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <div className="max-w-6xl mx-auto p-6 bg-white rounded-lg shadow-lg">
      <div className="mb-8">
        <div className="flex flex-col sm:flex-row gap-4">
          <input
            type="text"
            value={url}
            onChange={(e) => setUrl(e.target.value)}
            placeholder="Enter URL (e.g., https://example.com)"
            className="flex-1 p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            onKeyDown={(e) => e.key === "Enter" && checkSEO()}
          />
          <button
            onClick={checkSEO}
            disabled={loading || !url}
            className="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 disabled:bg-blue-300 focus:outline-none focus:ring-2 focus:ring-blue-500 flex items-center justify-center min-w-[150px]"
          >
            {loading ? (
              <>
                <svg
                  className="animate-spin -ml-1 mr-2 h-4 w-4 text-white"
                  xmlns="http://www.w3.org/2000/svg"
                  fill="none"
                  viewBox="0 0 24 24"
                >
                  <circle
                    className="opacity-25"
                    cx="12"
                    cy="12"
                    r="10"
                    stroke="currentColor"
                    strokeWidth="4"
                  ></circle>
                  <path
                    className="opacity-75"
                    fill="currentColor"
                    d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                  ></path>
                </svg>
                Analyzing...
              </>
            ) : (
              "Run Full Analysis"
            )}
          </button>
        </div>
        {error && (
          <p className="mt-2 text-sm text-red-600 flex items-center">
            <FiAlertTriangle className="mr-1" /> {error}
          </p>
        )}
      </div>

      {loading && (
        <div className="text-center py-12">
          <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500 mx-auto"></div>
          <p className="mt-4 text-gray-600">
            Running comprehensive SEO analysis...
          </p>
          <p className="text-sm text-gray-500">This may take 10-15 seconds</p>
        </div>
      )}

      {seoData && (
        <>
          <div className="border-b border-gray-200 mb-6">
            <nav className="flex space-x-4 overflow-x-auto pb-2">
              {["summary", "details", "full-report"].map((tab) => (
                <button
                  key={tab}
                  onClick={() => setActiveTab(tab)}
                  className={`px-4 py-2 text-sm font-medium whitespace-nowrap ${
                    activeTab === tab
                      ? "border-b-2 border-blue-500 text-blue-600"
                      : "text-gray-500 hover:text-gray-700"
                  }`}
                >
                  {tab
                    .split("-")
                    .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
                    .join(" ")}
                </button>
              ))}
            </nav>
          </div>

          {renderReportSection()}
        </>
      )}
    </div>
  );
};

// Helper Components
const ScoreCard = ({ title, score, max, description }) => {
  const percentage = (score / max) * 100;
  const getColor = () => {
    if (percentage >= 80) return "bg-green-500";
    if (percentage >= 50) return "bg-yellow-500";
    return "bg-red-500";
  };

  return (
    <div className="bg-white p-4 rounded-lg shadow border border-gray-100">
      <h3 className="font-medium text-gray-700">{title}</h3>
      <div className="flex items-end mt-2">
        <span className="text-3xl font-bold mr-2">{score}</span>
        <span className="text-gray-500">/ {max}</span>
      </div>
      <div className="w-full bg-gray-200 rounded-full h-2 mt-2">
        <div
          className={`h-2 rounded-full ${getColor()}`}
          style={{ width: `${percentage}%` }}
        ></div>
      </div>
      <p className="text-xs text-gray-500 mt-2">{description}</p>
    </div>
  );
};

const Section = ({ title, children }) => (
  <div className="bg-white p-6 rounded-lg shadow">
    <h3 className="text-lg font-semibold mb-4">{title}</h3>
    <div className="space-y-4">{children}</div>
  </div>
);

const CheckItem = ({ label, status, goodText, badText, recommendation }) => (
  <div className="flex items-start">
    <div className="mr-3 mt-1">
      {status === "good" ? (
        <FiCheckCircle className="text-green-500" />
      ) : (
        <FiAlertTriangle className="text-red-500" />
      )}
    </div>
    <div>
      <p className="font-medium">{label}</p>
      <p className="text-gray-600 text-sm">
        {status === "good" ? goodText : badText}
      </p>
      {status !== "good" && recommendation && (
        <p className="text-blue-600 text-sm mt-1">
          Recommendation: {recommendation}
        </p>
      )}
    </div>
  </div>
);

export default SEOChecker;
