"use client";

import type { MobileFirstAudit, MobileFinding, MobileDimension } from "@/lib/mobile-first/types";

interface Props {
  mobileFirstAudit: MobileFirstAudit | null | undefined;
}

const TIER_CONFIG: Record<
  MobileFirstAudit["scoreTier"],
  { label: string; scoreClass: string; badgeClass: string; barClass: string }
> = {
  excellent: {
    label: "Excellent",
    scoreClass: "text-emerald-400",
    badgeClass: "bg-emerald-500/20 text-emerald-400 border border-emerald-500/30",
    barClass: "bg-emerald-500",
  },
  good: {
    label: "Good",
    scoreClass: "text-blue-400",
    badgeClass: "bg-blue-500/20 text-blue-400 border border-blue-500/30",
    barClass: "bg-blue-500",
  },
  needs_improvement: {
    label: "Needs Improvement",
    scoreClass: "text-amber-400",
    badgeClass: "bg-amber-500/20 text-amber-400 border border-amber-500/30",
    barClass: "bg-amber-500",
  },
  poor: {
    label: "Poor",
    scoreClass: "text-red-400",
    badgeClass: "bg-red-500/20 text-red-400 border border-red-500/30",
    barClass: "bg-red-500",
  },
};

const SEVERITY_CONFIG: Record<
  MobileFinding["severity"],
  { label: string; class: string; dot: string }
> = {
  critical: { label: "Critical", class: "bg-red-500/20 text-red-400 border border-red-500/30", dot: "bg-red-500" },
  high: { label: "High", class: "bg-orange-500/20 text-orange-400 border border-orange-500/30", dot: "bg-orange-500" },
  moderate: { label: "Moderate", class: "bg-amber-500/20 text-amber-400 border border-amber-500/30", dot: "bg-amber-400" },
  low: { label: "Low", class: "bg-slate-600/60 text-slate-400 border border-slate-600/50", dot: "bg-slate-500" },
};

const DIMENSION_LABELS: Record<MobileDimension, string> = {
  viewport: "Viewport Config",
  touch_targets: "Touch Targets",
  mobile_schema: "Mobile Schema",
  amp: "AMP",
  above_fold_composition: "Above-Fold",
};

function ScoreBar({ score, barClass }: { score: number; barClass: string }) {
  return (
    <div className="flex items-center gap-3">
      <div className="flex-1 h-2 bg-slate-700/60 rounded-full overflow-hidden">
        <div
          className={`h-full rounded-full transition-all ${barClass}`}
          style={{ width: `${Math.min(100, score)}%` }}
        />
      </div>
      <span className="text-sm font-bold text-slate-300 w-12 text-right">{score}/100</span>
    </div>
  );
}

function FindingCard({ finding }: { finding: MobileFinding }) {
  const sev = SEVERITY_CONFIG[finding.severity];
  return (
    <div className="rounded-xl bg-slate-800/60 border border-slate-700/50 p-4 space-y-2">
      <div className="flex items-start justify-between gap-3">
        <div className="flex items-center gap-2 min-w-0">
          <div className={`w-2 h-2 rounded-full flex-shrink-0 mt-0.5 ${sev.dot}`} />
          <span className="text-sm font-semibold text-slate-200 leading-snug">{finding.title}</span>
        </div>
        <span className={`flex-shrink-0 text-xs font-medium px-2 py-0.5 rounded-full ${sev.class}`}>
          {sev.label}
        </span>
      </div>
      <p className="text-xs text-slate-400 leading-relaxed pl-4">{finding.detail}</p>
      {finding.recommendation && (
        <p className="text-xs text-slate-300 leading-relaxed pl-4 border-l-2 border-slate-600">
          {finding.recommendation}
        </p>
      )}
    </div>
  );
}

function PageTab({
  evaluation,
  isSelected,
  onClick,
}: {
  evaluation: MobileFirstAudit["perPageEvaluations"][number];
  isSelected: boolean;
  onClick: () => void;
}) {
  const tierKey: MobileFirstAudit["scoreTier"] =
    evaluation.mobileScore >= 85
      ? "excellent"
      : evaluation.mobileScore >= 65
        ? "good"
        : evaluation.mobileScore >= 45
          ? "needs_improvement"
          : "poor";
  const cfg = TIER_CONFIG[tierKey];
  return (
    <button
      onClick={onClick}
      className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
        isSelected
          ? "bg-slate-700 text-white"
          : "text-slate-400 hover:text-slate-200 hover:bg-slate-800/60"
      }`}
    >
      {evaluation.pageLabel}
      <span className={`ml-2 text-xs ${cfg.scoreClass}`}>{evaluation.mobileScore}</span>
    </button>
  );
}

export default function MobileFirstAuditSection({ mobileFirstAudit }: Props) {
  if (!mobileFirstAudit?.hasAudit || mobileFirstAudit.perPageEvaluations.length === 0) {
    return null;
  }

  const tierCfg = TIER_CONFIG[mobileFirstAudit.scoreTier];

  // Client-side tab state via uncontrolled approach using details/summary for simplicity
  const evals = mobileFirstAudit.perPageEvaluations;

  return (
    <section className="space-y-6">
      {/* Hero strip */}
      <div className="rounded-2xl bg-slate-800/50 border border-slate-700/50 p-6">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div>
            <div className="flex items-center gap-3 mb-2">
              <span className="text-2xl font-black text-white">{mobileFirstAudit.overallMobileScore}</span>
              <span className="text-slate-400 text-sm font-medium">/ 100</span>
              <span className={`text-xs font-semibold px-2.5 py-1 rounded-full ${tierCfg.badgeClass}`}>
                {tierCfg.label}
              </span>
            </div>
            <h3 className="text-lg font-bold text-white">Mobile Usability Evaluation</h3>
            <p className="text-sm text-slate-400 mt-1">
              {mobileFirstAudit.pagesEvaluated} page{mobileFirstAudit.pagesEvaluated !== 1 ? "s" : ""} evaluated
              {" "}&middot;{" "}
              {mobileFirstAudit.topPriorityFindings.filter((f) => f.severity === "critical" || f.severity === "high").length} high-priority issues
            </p>
          </div>
          <div className="w-full sm:w-48">
            <ScoreBar score={mobileFirstAudit.overallMobileScore} barClass={tierCfg.barClass} />
          </div>
        </div>
      </div>

      {/* Top priority findings */}
      {mobileFirstAudit.topPriorityFindings.length > 0 && (
        <div className="space-y-3">
          <h4 className="text-sm font-semibold text-slate-300 uppercase tracking-wide">
            Priority Findings
          </h4>
          <div className="grid gap-3 sm:grid-cols-2">
            {mobileFirstAudit.topPriorityFindings.map((finding) => (
              <FindingCard key={finding.id} finding={finding} />
            ))}
          </div>
        </div>
      )}

      {/* Dimension breakdown */}
      <div className="rounded-2xl bg-slate-800/50 border border-slate-700/50 p-5 space-y-4">
        <h4 className="text-sm font-semibold text-slate-300 uppercase tracking-wide">
          Dimension Breakdown
        </h4>
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
          {(Object.keys(DIMENSION_LABELS) as MobileDimension[]).map((dim) => {
            const breakdown = mobileFirstAudit.dimensionBreakdown[dim];
            return (
              <div key={dim} className="rounded-xl bg-slate-900/40 border border-slate-700/40 p-3 space-y-1">
                <p className="text-xs font-semibold text-slate-400">{DIMENSION_LABELS[dim]}</p>
                <p className="text-sm text-slate-200">{breakdown.findingCount} finding{breakdown.findingCount !== 1 ? "s" : ""}</p>
                {breakdown.criticalCount > 0 && (
                  <p className="text-xs text-red-400">{breakdown.criticalCount} critical</p>
                )}
              </div>
            );
          })}
        </div>
      </div>

      {/* Per-page tabs */}
      <div className="rounded-2xl bg-slate-800/50 border border-slate-700/50 overflow-hidden">
        <div className="p-5 space-y-4">
          <h4 className="text-sm font-semibold text-slate-300 uppercase tracking-wide">
            Per-Page Analysis
          </h4>
          {evals.map((ev, idx) => (
            <details key={ev.pageUrl} open={idx === 0} className="group">
              <summary className="flex items-center justify-between cursor-pointer rounded-xl bg-slate-900/40 border border-slate-700/40 p-4 list-none select-none hover:border-slate-600/60 transition-colors">
                <div className="flex items-center gap-3">
                  <span className="text-sm font-semibold text-slate-200">{ev.pageLabel}</span>
                  <span className="text-xs text-slate-500 truncate max-w-[180px]">{ev.pageUrl}</span>
                </div>
                <div className="flex items-center gap-3">
                  {ev.mobileScreenshotUrl && (
                    <a
                      href={ev.mobileScreenshotUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-xs text-blue-400 hover:text-blue-300 transition-colors"
                      onClick={(e) => e.stopPropagation()}
                    >
                      Screenshot
                    </a>
                  )}
                  <span className={`text-sm font-bold ${TIER_CONFIG[
                    ev.mobileScore >= 85 ? "excellent" : ev.mobileScore >= 65 ? "good" : ev.mobileScore >= 45 ? "needs_improvement" : "poor"
                  ].scoreClass}`}>
                    {ev.mobileScore}/100
                  </span>
                </div>
              </summary>
              <div className="pt-3 space-y-3">
                <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-4 text-xs">
                  <div className="rounded-lg bg-slate-900/30 p-2.5">
                    <p className="text-slate-500 mb-0.5">Viewport</p>
                    <p className={ev.viewport.isOptimal ? "text-emerald-400" : "text-red-400"}>
                      {ev.viewport.isOptimal ? "Optimal" : ev.viewport.hasViewportMeta ? "Issues" : "Missing"}
                    </p>
                  </div>
                  <div className="rounded-lg bg-slate-900/30 p-2.5">
                    <p className="text-slate-500 mb-0.5">Touch Targets</p>
                    <p className={ev.touchTargets.passRate >= 80 ? "text-emerald-400" : ev.touchTargets.passRate >= 60 ? "text-amber-400" : "text-red-400"}>
                      {ev.touchTargets.passRate}% pass rate
                    </p>
                  </div>
                  <div className="rounded-lg bg-slate-900/30 p-2.5">
                    <p className="text-slate-500 mb-0.5">Mobile Schema</p>
                    <p className={ev.mobileSchema.hasMobileSpecificSchema ? "text-emerald-400" : "text-amber-400"}>
                      {ev.mobileSchema.hasMobileSpecificSchema ? "Present" : ev.mobileSchema.detectedTypes.length > 0 ? "Partial" : "Absent"}
                    </p>
                  </div>
                  <div className="rounded-lg bg-slate-900/30 p-2.5">
                    <p className="text-slate-500 mb-0.5">Above-Fold Score</p>
                    <p className={ev.aboveFoldComposition.score >= 70 ? "text-emerald-400" : ev.aboveFoldComposition.score >= 40 ? "text-amber-400" : "text-red-400"}>
                      {ev.aboveFoldComposition.score}/100
                    </p>
                  </div>
                </div>
                {ev.findings.length > 0 && (
                  <div className="space-y-2">
                    {ev.findings.slice(0, 4).map((f) => (
                      <FindingCard key={f.id} finding={f} />
                    ))}
                  </div>
                )}
              </div>
            </details>
          ))}
        </div>
      </div>

      {/* Vertical-specific notes */}
      {mobileFirstAudit.verticalSpecificNotes.length > 0 && (
        <div className="rounded-xl bg-blue-500/10 border border-blue-500/20 p-4 space-y-2">
          <p className="text-xs font-semibold text-blue-400 uppercase tracking-wide">
            Industry-Specific Notes
          </p>
          <ul className="space-y-1.5">
            {mobileFirstAudit.verticalSpecificNotes.map((note, i) => (
              <li key={i} className="text-sm text-slate-300 flex gap-2">
                <span className="text-blue-400 flex-shrink-0">--</span>
                {note}
              </li>
            ))}
          </ul>
        </div>
      )}
    </section>
  );
}
