"use client";

import { useEffect, useState } from "react";
import { useRouter, useParams } from "next/navigation";

interface ArchRow {
  category: string;
  item: string;
  status: "found" | "partial" | "missing";
  detail?: string;
}

interface AnalysisResult {
  summary: string;
  rows: ArchRow[];
  suggestedSurfaces: string[];
}

interface CodeImportMainProps {
  projectId: string;
  projectName: string;
  sourceData?: { repoUrl?: string };
  analysisResult?: AnalysisResult;
  creationStage?: string;
}

type Stage = "input" | "cloning" | "mapping" | "surfaces";

const STATUS_COLORS = {
  found: { bg: "#f0fdf4", text: "#15803d", label: "Found" },
  partial: { bg: "#fffbeb", text: "#b45309", label: "Partial" },
  missing: { bg: "#fff1f2", text: "#be123c", label: "Missing" },
};

const CATEGORY_ORDER = [
  "Tech Stack", "Infrastructure", "Database", "API Surface",
  "Frontend", "Auth", "Third-party", "Missing / Gaps",
];

const PROGRESS_STEPS = [
  { key: "cloning", label: "Cloning repository" },
  { key: "reading", label: "Reading key files" },
  { key: "analyzing", label: "Mapping architecture" },
  { key: "done", label: "Analysis complete" },
];

export function CodeImportMain({
  projectId,
  projectName,
  sourceData,
  analysisResult: initialResult,
  creationStage,
}: CodeImportMainProps) {
  const router = useRouter();
  const params = useParams();
  const workspace = params?.workspace as string;

  const hasRepo = !!sourceData?.repoUrl;
  const getInitialStage = (): Stage => {
    if (initialResult) return "mapping";
    if (creationStage === "surfaces") return "surfaces";
    if (hasRepo) return "cloning";
    return "input";
  };

  const [stage, setStage] = useState<Stage>(getInitialStage);
  const [repoUrl, setRepoUrl] = useState(sourceData?.repoUrl ?? "");
  const [progressStep, setProgressStep] = useState<string>("cloning");
  const [error, setError] = useState<string | null>(null);
  const [result, setResult] = useState<AnalysisResult | null>(initialResult ?? null);
  const [confirmedSurfaces, setConfirmedSurfaces] = useState<string[]>(
    initialResult?.suggestedSurfaces ?? []
  );

  // Kick off analysis when in cloning stage
  useEffect(() => {
    if (stage !== "cloning") return;
    startAnalysis();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [stage]);

  // Poll for analysis status when cloning
  useEffect(() => {
    if (stage !== "cloning") return;
    const interval = setInterval(async () => {
      try {
        const res = await fetch(`/api/projects/${projectId}/analysis-status`);
        const data = await res.json();
        setProgressStep(data.stage ?? "cloning");
        if (data.stage === "done" && data.analysisResult) {
          setResult(data.analysisResult);
          setConfirmedSurfaces(data.analysisResult.suggestedSurfaces ?? []);
          clearInterval(interval);
          setStage("mapping");
        }
      } catch { /* keep polling */ }
    }, 2500);
    return () => clearInterval(interval);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [stage]);

  const startAnalysis = async () => {
    setError(null);
    try {
      await fetch(`/api/projects/${projectId}/analyze-repo`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ repoUrl }),
      });
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to start analysis");
      setStage("input");
    }
  };

  const handleConfirmSurfaces = async () => {
    try {
      await fetch(`/api/projects/${projectId}/design-surfaces`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ surfaces: confirmedSurfaces }),
      });
      router.push(`/${workspace}/project/${projectId}/design`);
    } catch { /* navigate anyway */ }
  };

  const toggleSurface = (s: string) => {
    setConfirmedSurfaces(prev =>
      prev.includes(s) ? prev.filter(x => x !== s) : [...prev, s]
    );
  };

  // ── Stage: input ──────────────────────────────────────────────────────────
  if (stage === "input") {
    const isValid = repoUrl.trim().startsWith("http");
    return (
      <div style={{ height: "100%", overflow: "auto", display: "flex", alignItems: "center", justifyContent: "center", padding: 32 }}>
        <div style={{ width: "100%", maxWidth: 540, fontFamily: "Outfit, sans-serif" }}>
          <div style={{ marginBottom: 28 }}>
            <h2 style={{ fontFamily: "Newsreader, serif", fontSize: "1.7rem", fontWeight: 400, color: "#1a1a1a", margin: 0, marginBottom: 6 }}>
              Import your repository
            </h2>
            <p style={{ fontSize: "0.82rem", color: "#a09a90", margin: 0 }}>
              {projectName} — paste a clone URL to map your existing stack.
            </p>
          </div>
          {error && (
            <div style={{ padding: "12px 16px", borderRadius: 8, background: "#fff0f0", border: "1px solid #fca5a5", color: "#991b1b", fontSize: "0.8rem", marginBottom: 16 }}>
              {error}
            </div>
          )}
          <label style={{ display: "block", fontSize: "0.72rem", fontWeight: 600, color: "#6b6560", marginBottom: 6, letterSpacing: "0.02em" }}>
            Repository URL (HTTPS)
          </label>
          <input
            type="text"
            value={repoUrl}
            onChange={e => setRepoUrl(e.target.value)}
            placeholder="https://github.com/yourorg/your-repo"
            style={{
              width: "100%", padding: "12px 14px", marginBottom: 16,
              borderRadius: 8, border: "1px solid #e0dcd4",
              background: "#faf8f5", fontSize: "0.9rem",
              fontFamily: "Outfit, sans-serif", color: "#1a1a1a",
              outline: "none", boxSizing: "border-box",
            }}
            onFocus={e => (e.currentTarget.style.borderColor = "#1a1a1a")}
            onBlur={e => (e.currentTarget.style.borderColor = "#e0dcd4")}
            onKeyDown={e => { if (e.key === "Enter" && isValid) setStage("cloning"); }}
            autoFocus
          />
          <div style={{ fontSize: "0.75rem", color: "#a09a90", marginBottom: 20, lineHeight: 1.55, padding: "12px 14px", background: "#faf8f5", borderRadius: 8, border: "1px solid #f0ece4" }}>
            Atlas will clone and map your stack — tech, database, auth, APIs, and what's missing for a complete go-to-market build.
          </div>
          <button
            onClick={() => { if (isValid) setStage("cloning"); }}
            disabled={!isValid}
            style={{
              width: "100%", padding: "13px", borderRadius: 8, border: "none",
              background: isValid ? "#1a1a1a" : "#e0dcd4",
              color: isValid ? "#fff" : "#b5b0a6",
              fontSize: "0.9rem", fontWeight: 600, fontFamily: "Outfit, sans-serif",
              cursor: isValid ? "pointer" : "not-allowed",
            }}
          >
            Map this repo →
          </button>
        </div>
      </div>
    );
  }

  // ── Stage: cloning ────────────────────────────────────────────────────────
  if (stage === "cloning") {
    const currentIdx = PROGRESS_STEPS.findIndex(s => s.key === progressStep);
    return (
      <div style={{ height: "100%", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "Outfit, sans-serif" }}>
        <div style={{ textAlign: "center", maxWidth: 400 }}>
          <div style={{
            width: 52, height: 52, borderRadius: "50%",
            border: "3px solid #e0dcd4", borderTopColor: "#1a1a1a",
            animation: "vibn-repo-spin 0.85s linear infinite",
            margin: "0 auto 24px",
          }} />
          <style>{`@keyframes vibn-repo-spin { to { transform:rotate(360deg); } }`}</style>
          <h3 style={{ fontSize: "1.1rem", fontWeight: 600, color: "#1a1a1a", margin: "0 0 8px" }}>
            Mapping your codebase
          </h3>
          <p style={{ fontSize: "0.8rem", color: "#a09a90", margin: "0 0 28px" }}>
            {repoUrl || sourceData?.repoUrl || "Repository"}
          </p>
          <div style={{ display: "flex", flexDirection: "column", gap: 8, textAlign: "left" }}>
            {PROGRESS_STEPS.map((step, i) => {
              const done = i < currentIdx;
              const active = i === currentIdx;
              return (
                <div key={step.key} style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <div style={{
                    width: 22, height: 22, borderRadius: "50%", flexShrink: 0,
                    background: done ? "#1a1a1a" : active ? "#f6f4f0" : "#f6f4f0",
                    border: active ? "2px solid #1a1a1a" : done ? "none" : "2px solid #e0dcd4",
                    display: "flex", alignItems: "center", justifyContent: "center",
                    fontSize: "0.6rem", fontWeight: 700, color: done ? "#fff" : "#a09a90",
                  }}>
                    {done ? "✓" : active ? <span style={{ width: 8, height: 8, borderRadius: "50%", background: "#1a1a1a", display: "block" }} /> : ""}
                  </div>
                  <span style={{ fontSize: "0.8rem", fontWeight: active ? 600 : 400, color: done ? "#6b6560" : active ? "#1a1a1a" : "#b5b0a6" }}>
                    {step.label}
                  </span>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    );
  }

  // ── Stage: mapping ────────────────────────────────────────────────────────
  if (stage === "mapping" && result) {
    const byCategory: Record<string, ArchRow[]> = {};
    for (const row of result.rows) {
      const cat = row.category || "Other";
      if (!byCategory[cat]) byCategory[cat] = [];
      byCategory[cat].push(row);
    }
    const categories = [
      ...CATEGORY_ORDER.filter(c => byCategory[c]),
      ...Object.keys(byCategory).filter(c => !CATEGORY_ORDER.includes(c)),
    ];

    return (
      <div style={{ height: "100%", overflow: "auto", padding: "32px 40px", fontFamily: "Outfit, sans-serif" }}>
        <div style={{ maxWidth: 800, margin: "0 auto" }}>
          <div style={{ marginBottom: 24 }}>
            <h2 style={{ fontFamily: "Newsreader, serif", fontSize: "1.7rem", fontWeight: 400, color: "#1a1a1a", margin: 0, marginBottom: 6 }}>
              Architecture map
            </h2>
            <p style={{ fontSize: "0.8rem", color: "#a09a90", margin: "0 0 4px" }}>
              {projectName} — {result.summary}
            </p>
          </div>

          <div style={{ background: "#fff", borderRadius: 12, border: "1px solid #e8e4dc", overflow: "hidden", marginBottom: 24 }}>
            {categories.map((cat, catIdx) => (
              <div key={cat}>
                {catIdx > 0 && <div style={{ height: 1, background: "#f0ece4" }} />}
                <div style={{ padding: "12px 20px", background: "#faf8f5", fontSize: "0.68rem", fontWeight: 700, color: "#6b6560", letterSpacing: "0.06em", textTransform: "uppercase" }}>
                  {cat}
                </div>
                {byCategory[cat].map((row, i) => {
                  const sc = STATUS_COLORS[row.status];
                  return (
                    <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 20px", borderTop: "1px solid #f6f4f0" }}>
                      <div style={{ flex: 1, fontSize: "0.82rem", color: "#1a1a1a", fontWeight: 500 }}>{row.item}</div>
                      {row.detail && <div style={{ fontSize: "0.75rem", color: "#8a8478", flex: 2 }}>{row.detail}</div>}
                      <div style={{ padding: "3px 10px", borderRadius: 4, background: sc.bg, color: sc.text, fontSize: "0.68rem", fontWeight: 700, flexShrink: 0 }}>
                        {sc.label}
                      </div>
                    </div>
                  );
                })}
              </div>
            ))}
          </div>

          <button
            onClick={() => setStage("surfaces")}
            style={{
              width: "100%", padding: "13px", borderRadius: 8, border: "none",
              background: "#1a1a1a", color: "#fff",
              fontSize: "0.9rem", fontWeight: 600, fontFamily: "Outfit, sans-serif", cursor: "pointer",
            }}
            onMouseEnter={e => (e.currentTarget.style.opacity = "0.88")}
            onMouseLeave={e => (e.currentTarget.style.opacity = "1")}
          >
            Choose what to build next →
          </button>
        </div>
      </div>
    );
  }

  // ── Stage: surfaces ───────────────────────────────────────────────────────
  const SURFACE_OPTIONS = [
    { id: "marketing", label: "Marketing Site", icon: "◎", desc: "Landing page, pricing, blog" },
    { id: "web-app", label: "Web App", icon: "⬡", desc: "Core SaaS product with auth" },
    { id: "admin", label: "Admin Panel", icon: "◫", desc: "Ops dashboard, content management" },
    { id: "api", label: "API Layer", icon: "⌁", desc: "REST/GraphQL endpoints" },
  ];

  return (
    <div style={{ height: "100%", overflow: "auto", display: "flex", alignItems: "center", justifyContent: "center", padding: 32 }}>
      <div style={{ width: "100%", maxWidth: 540, fontFamily: "Outfit, sans-serif" }}>
        <div style={{ marginBottom: 28 }}>
          <h2 style={{ fontFamily: "Newsreader, serif", fontSize: "1.7rem", fontWeight: 400, color: "#1a1a1a", margin: 0, marginBottom: 6 }}>
            What should Atlas build?
          </h2>
          <p style={{ fontSize: "0.82rem", color: "#a09a90", margin: 0 }}>
            Based on the gap analysis, Atlas suggests the surfaces below. Confirm or adjust.
          </p>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 24 }}>
          {SURFACE_OPTIONS.map(s => {
            const selected = confirmedSurfaces.includes(s.id);
            return (
              <button
                key={s.id}
                onClick={() => toggleSurface(s.id)}
                style={{
                  padding: "18px", borderRadius: 10, textAlign: "left",
                  border: `2px solid ${selected ? "#1a1a1a" : "#e8e4dc"}`,
                  background: selected ? "#1a1a1a08" : "#fff",
                  cursor: "pointer", fontFamily: "Outfit, sans-serif",
                  transition: "all 0.12s",
                }}
                onMouseEnter={e => { if (!selected) e.currentTarget.style.borderColor = "#d0ccc4"; }}
                onMouseLeave={e => { if (!selected) e.currentTarget.style.borderColor = "#e8e4dc"; }}
              >
                <div style={{ fontSize: "1.2rem", marginBottom: 8 }}>{s.icon}</div>
                <div style={{ fontSize: "0.84rem", fontWeight: 700, color: "#1a1a1a", marginBottom: 3 }}>{s.label}</div>
                <div style={{ fontSize: "0.73rem", color: "#8a8478" }}>{s.desc}</div>
              </button>
            );
          })}
        </div>
        <button
          onClick={handleConfirmSurfaces}
          disabled={confirmedSurfaces.length === 0}
          style={{
            width: "100%", padding: "13px", borderRadius: 8, border: "none",
            background: confirmedSurfaces.length > 0 ? "#1a1a1a" : "#e0dcd4",
            color: confirmedSurfaces.length > 0 ? "#fff" : "#b5b0a6",
            fontSize: "0.9rem", fontWeight: 600, fontFamily: "Outfit, sans-serif",
            cursor: confirmedSurfaces.length > 0 ? "pointer" : "not-allowed",
          }}
        >
          Go to Design →
        </button>
      </div>
    </div>
  );
}
