"use client";

import { useEffect, useState } from "react";
import { db } from "@/lib/firebase/config";
import { doc, onSnapshot } from "firebase/firestore";
import { CollectorChecklist } from "./collector-checklist";
import { ExtractionReviewChecklist } from "./extraction-review-checklist";
import { ExtractionResults } from "./extraction-results";
import { CollectorActions } from "./collector-actions";
import { ProjectConfigGenerator } from "./project-config-generator";

interface PhaseSidebarProps {
  projectId: string;
  projectName?: string;
  className?: string;
}

export function PhaseSidebar({ projectId, projectName, className }: PhaseSidebarProps) {
  const [currentPhase, setCurrentPhase] = useState<string>("collector");
  const [projectNameState, setProjectNameState] = useState<string>(projectName || "");

  useEffect(() => {
    if (!projectId) return;

    const unsubscribe = onSnapshot(
      doc(db, "projects", projectId),
      (snapshot) => {
        if (snapshot.exists()) {
          const data = snapshot.data();
          const phase = data?.currentPhase || "collector";
          setCurrentPhase(phase);
          setProjectNameState(data?.name || data?.productName || "");
        }
      }
    );

    return () => unsubscribe();
  }, [projectId]);

  return (
    <div className={className}>
      {/* Top: Show checklist based on current phase */}
      {currentPhase === "collector" && (
        <CollectorChecklist projectId={projectId} />
      )}
      
      {(currentPhase === "extraction_review" || currentPhase === "analyzed") && (
        <ExtractionReviewChecklist projectId={projectId} />
      )}

      {/* Bottom: Phase-specific content */}
      <div className="mt-6 pt-6 border-t">
        {currentPhase === "collector" && (
          <>
            <h3 className="text-sm font-semibold mb-3">Quick Actions</h3>
            <div className="space-y-2">
              <ProjectConfigGenerator projectId={projectId} projectName={projectNameState} />
              <CollectorActions projectId={projectId} />
            </div>
          </>
        )}

        {(currentPhase === "extraction_review" || currentPhase === "analyzed") && (
          <p className="text-sm text-muted-foreground">
            Review the extracted insights in the chat area above.
          </p>
        )}

        {currentPhase === "vision" && (
          <>
            <h3 className="text-sm font-semibold mb-3">Vision Phase</h3>
            <p className="text-xs text-muted-foreground">
              Defining your product vision and MVP...
            </p>
          </>
        )}

        {currentPhase === "mvp" && (
          <>
            <h3 className="text-sm font-semibold mb-3">MVP Planning</h3>
            <p className="text-xs text-muted-foreground">
              Planning your minimum viable product...
            </p>
          </>
        )}
      </div>
    </div>
  );
}

