"use client";

import { useEffect, useState, useCallback } from "react";
import { motion } from "framer-motion";
import {
  ShieldCheck, RefreshCw, Loader2, AlertTriangle, CheckCircle2,
  Car, FileText, GitCompare, Clock, Zap,
} from "lucide-react";
import { fetchSeoHealthReport, runSeoHealthCheck } from "@/lib/api";
import type { SeoHealthReport } from "@/lib/types";
import { cn } from "@/lib/utils";

function MetricCard({
  label,
  value,
  total,
  good = false,
}: {
  label: string;
  value: number;
  total?: number;
  good?: boolean;
}) {
  const isOk = good || value === 0;
  return (
    <div className="flex items-center justify-between gap-2 py-2.5 border-b border-gray-50 last:border-0 min-w-0">
      <span className="text-sm text-gray-600 min-w-0 break-words">{label}</span>
      <div className="flex items-center gap-2 flex-shrink-0">
        {total !== undefined && (
          <span className="text-xs text-gray-400">/ {total}</span>
        )}
        <span className={cn(
          "text-sm font-bold px-2.5 py-0.5 rounded-full",
          isOk ? "bg-green-50 text-green-700" : "bg-red-50 text-red-600"
        )}>
          {value}
        </span>
      </div>
    </div>
  );
}

function SectionCard({
  icon: Icon,
  title,
  color,
  children,
}: {
  icon: React.ElementType;
  title: string;
  color: string;
  children: React.ReactNode;
}) {
  return (
    <div className="bg-white rounded-[24px] border border-gray-200/60 p-5 shadow-[0_4px_20px_rgba(0,0,0,0.05)]">
      <div className="flex items-center gap-3 mb-4 min-w-0">
        <div className={cn("w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0", color)}>
          <Icon className="w-4.5 h-4.5 text-white" />
        </div>
        <h3 className="font-bold text-gray-900 min-w-0 break-words">{title}</h3>
      </div>
      {children}
    </div>
  );
}

export default function AdminSeoHealthPage() {
  const [report, setReport] = useState<SeoHealthReport | null>(null);
  const [loading, setLoading] = useState(true);
  const [running, setRunning] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [noReport, setNoReport] = useState(false);

  const loadReport = useCallback(async () => {
    setLoading(true);
    setError(null);
    setNoReport(false);
    try {
      const r = await fetchSeoHealthReport();
      setReport(r);
    } catch (e: unknown) {
      const msg = e instanceof Error ? e.message : String(e);
      if (msg.includes("No SEO health report")) {
        setNoReport(true);
      } else {
        setError(msg);
      }
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { loadReport(); }, [loadReport]);

  async function handleRunCheck() {
    setRunning(true);
    setError(null);
    try {
      const r = await runSeoHealthCheck();
      setReport(r);
      setNoReport(false);
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : "SEO check failed");
    } finally {
      setRunning(false);
    }
  }

  const totalIssues = report
    ? (report.cars.missingMetadata + report.cars.missingImages + report.cars.missingPros +
       report.cars.missingFaqs + report.cars.thinContent +
       report.blogs.thinContent + report.blogs.missingMeta +
       report.comparisons.missingMeta)
    : 0;

  return (
    <div className="p-4 sm:p-6 lg:p-8 max-w-5xl mx-auto">
      {/* Header */}
      <div className="mb-6 flex items-center justify-between flex-wrap gap-3">
        <div className="min-w-0">
          <h1 className="text-xl sm:text-2xl font-black text-gray-900 break-words">SEO Health Monitor</h1>
          <p className="text-sm text-gray-500 mt-0.5 break-words">
            {report
              ? `Last checked: ${new Date(report.checkedAt).toLocaleString("en-IN")}`
              : "Automated daily audit of all content"}
          </p>
        </div>
        <div className="flex flex-wrap gap-2">
          <button
            onClick={loadReport}
            disabled={loading}
            className="p-2.5 min-h-[44px] min-w-[44px] inline-flex items-center justify-center rounded-xl border border-gray-200 hover:bg-gray-50 text-gray-500 transition-colors"
            title="Refresh"
          >
            <RefreshCw className={cn("w-4 h-4", loading && "animate-spin")} />
          </button>
          <button
            onClick={handleRunCheck}
            disabled={running}
            className="flex items-center gap-2 px-4 py-2.5 min-h-[44px] rounded-xl bg-gradient-to-r from-blue-600 to-indigo-600 text-white text-sm font-bold shadow-lg shadow-blue-100 hover:opacity-90 transition-opacity disabled:opacity-60"
          >
            {running ? <Loader2 className="w-4 h-4 animate-spin" /> : <Zap className="w-4 h-4" />}
            Run Check Now
          </button>
        </div>
      </div>

      {error && (
        <div className="mb-5 p-4 bg-red-50 border border-red-200 rounded-2xl text-sm text-red-700 flex items-start gap-3">
          <AlertTriangle className="w-4 h-4 flex-shrink-0 mt-0.5" />
          <span className="min-w-0 flex-1 break-words">{error}</span>
        </div>
      )}

      {loading ? (
        <div className="flex items-center justify-center py-20">
          <Loader2 className="w-6 h-6 animate-spin text-blue-500" />
        </div>
      ) : noReport ? (
        <div className="text-center py-20 px-4 bg-white rounded-[28px] border border-gray-100">
          <ShieldCheck className="w-12 h-12 mx-auto mb-4 text-gray-300" />
          <h3 className="text-lg font-bold text-gray-700 mb-2">No Report Yet</h3>
          <p className="text-sm text-gray-400 mb-6 max-w-sm mx-auto break-words">Run your first SEO health check to see the results.</p>
          <button
            onClick={handleRunCheck}
            disabled={running}
            className="inline-flex items-center gap-2 px-5 py-2.5 min-h-[44px] rounded-xl bg-blue-600 text-white text-sm font-bold hover:bg-blue-700 transition-colors disabled:opacity-60"
          >
            {running ? <Loader2 className="w-4 h-4 animate-spin" /> : <Zap className="w-4 h-4" />}
            Run First Check
          </button>
        </div>
      ) : report ? (
        <div className="space-y-5">
          {/* Summary banner */}
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            className={cn(
              "flex items-start sm:items-center gap-4 p-5 rounded-[24px] border",
              totalIssues === 0
                ? "bg-green-50 border-green-200"
                : totalIssues < 20
                ? "bg-amber-50 border-amber-200"
                : "bg-red-50 border-red-200"
            )}
          >
            {totalIssues === 0 ? (
              <CheckCircle2 className="w-8 h-8 text-green-600 flex-shrink-0" />
            ) : (
              <AlertTriangle className={cn("w-8 h-8 flex-shrink-0", totalIssues < 20 ? "text-amber-600" : "text-red-600")} />
            )}
            <div className="min-w-0 flex-1">
              <p className={cn("text-base sm:text-lg font-black break-words", totalIssues === 0 ? "text-green-800" : totalIssues < 20 ? "text-amber-800" : "text-red-800")}>
                {totalIssues === 0
                  ? "All content looks healthy!"
                  : `${totalIssues} SEO issue${totalIssues !== 1 ? "s" : ""} detected`}
              </p>
              <p className="text-sm mt-0.5 opacity-75 break-words">
                {report.cars.fixed > 0 && `${report.cars.fixed} issues auto-fixed · `}
                Checked {report.cars.checked} cars · {report.blogs.checked} blogs · {report.comparisons.checked} comparisons
              </p>
            </div>
          </motion.div>

          {/* Detail cards */}
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            <SectionCard icon={Car} title="Cars" color="bg-gradient-to-br from-blue-500 to-indigo-600">
              <MetricCard label="Checked"          value={report.cars.checked}          good />
              <MetricCard label="Missing metadata"  value={report.cars.missingMetadata}  />
              <MetricCard label="Missing images"    value={report.cars.missingImages}    />
              <MetricCard label="Missing pros/cons" value={report.cars.missingPros}      />
              <MetricCard label="Missing FAQs"      value={report.cars.missingFaqs}      />
              <MetricCard label="Thin content"      value={report.cars.thinContent}      />
              <MetricCard label="Auto-fixed"        value={report.cars.fixed}            good />
            </SectionCard>

            <SectionCard icon={FileText} title="Blogs" color="bg-gradient-to-br from-purple-500 to-violet-600">
              <MetricCard label="Checked"         value={report.blogs.checked}     good />
              <MetricCard label="Thin content"    value={report.blogs.thinContent} />
              <MetricCard label="Missing meta"    value={report.blogs.missingMeta} />
            </SectionCard>

            <SectionCard icon={GitCompare} title="Comparisons" color="bg-gradient-to-br from-orange-500 to-red-500">
              <MetricCard label="Checked"      value={report.comparisons.checked}     good />
              <MetricCard label="Missing meta" value={report.comparisons.missingMeta} />
            </SectionCard>
          </div>

          {/* Issues table */}
          {report.issues?.length > 0 && (
            <div className="bg-white rounded-[24px] border border-gray-200/60 overflow-hidden shadow-[0_4px_20px_rgba(0,0,0,0.05)]">
              <div className="flex items-center justify-between gap-2 px-4 sm:px-5 py-4 border-b border-gray-100 min-w-0">
                <h3 className="font-bold text-gray-900 min-w-0 truncate">Issue Details</h3>
                <span className="text-xs bg-red-50 text-red-600 font-bold px-2.5 py-1 rounded-full flex-shrink-0">
                  {report.issues.length} items
                </span>
              </div>
              <div className="divide-y divide-gray-50 max-h-96 overflow-y-auto">
                {report.issues.map((issue, i) => (
                  <div key={i} className="flex items-start gap-3 px-4 sm:px-5 py-3 min-w-0">
                    <span className={cn(
                      "text-xs font-bold px-2 py-0.5 rounded-full flex-shrink-0 mt-0.5",
                      issue.type === "car"        ? "bg-blue-50 text-blue-600"   :
                      issue.type === "blog"       ? "bg-purple-50 text-purple-600" :
                      "bg-orange-50 text-orange-600"
                    )}>
                      {issue.type}
                    </span>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-semibold text-gray-800 truncate">
                        {issue.name ?? issue.title ?? issue.id}
                      </p>
                      <div className="flex flex-wrap gap-1 mt-1">
                        {issue.issues.map((iss, j) => (
                          <span key={j} className="text-xs bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full max-w-full break-words">
                            {iss}
                          </span>
                        ))}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Scheduled info */}
          <div className="flex items-start gap-3 p-4 bg-blue-50 border border-blue-100 rounded-2xl text-sm text-blue-700">
            <Clock className="w-4 h-4 flex-shrink-0 mt-0.5" />
            <span className="min-w-0 flex-1 break-words">Automated checks run daily at 06:00 UTC via the background scheduler.</span>
          </div>
        </div>
      ) : null}
    </div>
  );
}
