"use client";

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

const PRD_SECTIONS = [
  { id: "executive_summary",    label: "Executive Summary" },
  { id: "problem_statement",    label: "Problem Statement" },
  { id: "vision_metrics",       label: "Vision & Success Metrics" },
  { id: "users_personas",       label: "Users & Personas" },
  { id: "user_flows",           label: "User Flows" },
  { id: "feature_requirements", label: "Feature Requirements" },
  { id: "screen_specs",         label: "Screen Specs" },
  { id: "business_model",       label: "Business Model" },
  { id: "integrations",         label: "Integrations & Dependencies" },
  { id: "non_functional",       label: "Non-Functional Reqs" },
  { id: "risks",                label: "Risks & Mitigations" },
  { id: "open_questions",       label: "Open Questions" },
];

interface PRDSection {
  id: string;
  label: string;
  status: "done" | "active" | "pending";
  pct: number;
  content?: string;
}

interface Project {
  id: string;
  prd?: string;
  prdSections?: Record<string, { status: string; pct: number; content?: string }>;
}

export default function PRDPage() {
  const params = useParams();
  const projectId = params.projectId as string;
  const [project, setProject] = useState<Project | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(`/api/projects/${projectId}`)
      .then((r) => r.json())
      .then((d) => {
        setProject(d.project);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, [projectId]);

  // Build sections with real status if available
  const sections: PRDSection[] = PRD_SECTIONS.map((s) => {
    const saved = project?.prdSections?.[s.id];
    return {
      ...s,
      status: (saved?.status as PRDSection["status"]) ?? "pending",
      pct: saved?.pct ?? 0,
      content: saved?.content,
    };
  });

  // If we have a raw PRD markdown, show that instead of the section list
  const hasPRD = Boolean(project?.prd);

  const totalPct = Math.round(sections.reduce((a, s) => a + s.pct, 0) / sections.length);
  const doneCount = sections.filter((s) => s.status === "done").length;

  if (loading) {
    return (
      <div style={{ display: "flex", alignItems: "center", justifyContent: "center", height: "100%", fontFamily: "Outfit, sans-serif", color: "#a09a90" }}>
        Loading…
      </div>
    );
  }

  return (
    <div
      className="vibn-enter"
      style={{ padding: "28px 32px", flex: 1, overflow: "auto", fontFamily: "Outfit, sans-serif" }}
    >
      {hasPRD ? (
        /* ── Raw PRD view ── */
        <div style={{ maxWidth: 760 }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 20 }}>
            <h3 style={{ fontFamily: "Newsreader, serif", fontSize: "1.2rem", fontWeight: 400, color: "#1a1a1a", margin: 0 }}>
              Product Requirements
            </h3>
            <span style={{ fontFamily: "IBM Plex Mono, monospace", fontSize: "0.72rem", color: "#6b6560", background: "#f0ece4", padding: "4px 10px", borderRadius: 5 }}>
              PRD approved
            </span>
          </div>
          <div style={{
            background: "#fff", borderRadius: 10, border: "1px solid #e8e4dc",
            padding: "28px 32px", lineHeight: 1.8,
            fontSize: "0.88rem", color: "#2a2824",
            whiteSpace: "pre-wrap", fontFamily: "Outfit, sans-serif",
          }}>
            {project?.prd}
          </div>
        </div>
      ) : (
        /* ── Section progress view ── */
        <div style={{ maxWidth: 640 }}>
          {/* Progress bar */}
          <div style={{
            display: "flex", alignItems: "center", gap: 16,
            padding: "16px 20px", background: "#fff",
            border: "1px solid #e8e4dc", borderRadius: 10,
            marginBottom: 20, boxShadow: "0 1px 2px #1a1a1a05",
          }}>
            <div style={{
              fontFamily: "IBM Plex Mono, monospace",
              fontSize: "1.4rem", fontWeight: 500, color: "#1a1a1a", minWidth: 48,
            }}>
              {totalPct}%
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ height: 4, borderRadius: 2, background: "#eae6de" }}>
                <div style={{
                  height: "100%", borderRadius: 2,
                  width: `${totalPct}%`, background: "#1a1a1a",
                  transition: "width 0.6s ease",
                }} />
              </div>
            </div>
            <span style={{ fontSize: "0.75rem", color: "#a09a90" }}>
              {doneCount}/{sections.length} approved
            </span>
          </div>

          {/* Sections */}
          {sections.map((s, i) => (
            <div
              key={s.id}
              style={{
                display: "flex", alignItems: "center", gap: 12,
                padding: "14px 18px", marginBottom: 4,
                background: "#fff", borderRadius: 8,
                border: "1px solid #e8e4dc",
                cursor: "pointer", transition: "border-color 0.12s",
                animationDelay: `${i * 0.04}s`,
              }}
              className="vibn-enter"
              onMouseEnter={(e) => (e.currentTarget.style.borderColor = "#d0ccc4")}
              onMouseLeave={(e) => (e.currentTarget.style.borderColor = "#e8e4dc")}
            >
              {/* Status icon */}
              <div style={{
                width: 24, height: 24, borderRadius: 6, flexShrink: 0,
                background: s.status === "done" ? "#2e7d3210"
                  : s.status === "active" ? "#d4a04a12"
                  : "#f6f4f0",
                display: "flex", alignItems: "center", justifyContent: "center",
                fontSize: "0.65rem", fontWeight: 700,
                color: s.status === "done" ? "#2e7d32"
                  : s.status === "active" ? "#9a7b3a"
                  : "#c5c0b8",
              }}>
                {s.status === "done" ? "✓" : s.status === "active" ? "◐" : "○"}
              </div>

              <span style={{ flex: 1, fontSize: "0.84rem", color: "#1a1a1a", fontWeight: 450 }}>
                {s.label}
              </span>

              {/* Mini progress bar */}
              <div style={{ width: 60, height: 3, borderRadius: 2, background: "#eae6de" }}>
                <div style={{
                  height: "100%", borderRadius: 2, width: `${s.pct}%`,
                  background: s.status === "done" ? "#2e7d32"
                    : s.status === "active" ? "#d4a04a"
                    : "#d0ccc4",
                }} />
              </div>

              <span style={{
                fontSize: "0.68rem", fontFamily: "IBM Plex Mono, monospace",
                color: s.status === "done" ? "#2e7d32" : "#a09a90",
                fontWeight: 500, minWidth: 28, textAlign: "right",
              }}>
                {s.pct}%
              </span>
            </div>
          ))}

          {/* Hint */}
          <p style={{ fontSize: "0.78rem", color: "#b5b0a6", marginTop: 20, textAlign: "center" }}>
            Continue chatting with Atlas to complete your PRD
          </p>
        </div>
      )}
    </div>
  );
}
