"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { useSession } from "next-auth/react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { OrchestratorChat } from "@/components/OrchestratorChat";
import { AtlasChat } from "@/components/AtlasChat";
import {
  Terminal,
  Loader2,
  RefreshCw,
} from "lucide-react";
import { toast } from "sonner";

interface Project {
  id: string;
  name: string;
  productName: string;
  productVision?: string;
  status?: string;
  currentPhase?: string;
  theiaWorkspaceUrl?: string;
  stage?: 'discovery' | 'architecture' | 'building' | 'active';
  prd?: string;
}


export default function ProjectOverviewPage() {
  const params = useParams();
  const projectId = params.projectId as string;
  const { status: authStatus } = useSession();

  const [project, setProject] = useState<Project | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [refreshing, setRefreshing] = useState(false);
  const [provisioning, setProvisioning] = useState(false);

  const fetchProject = async () => {
    try {
      const res = await fetch(`/api/projects/${projectId}`);
      if (!res.ok) {
        const err = await res.json();
        throw new Error(err.error || "Failed to load project");
      }
      const data = await res.json();
      setProject(data.project);
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Unknown error");
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => {
    if (authStatus === "authenticated") fetchProject();
    else if (authStatus === "unauthenticated") setLoading(false);
  }, [authStatus, projectId]);

  const handleRefresh = () => {
    setRefreshing(true);
    fetchProject();
  };

  const handleProvisionWorkspace = async () => {
    setProvisioning(true);
    try {
      const res = await fetch(`/api/projects/${projectId}/workspace`, { method: 'POST' });
      const data = await res.json();
      if (res.ok && data.workspaceUrl) {
        toast.success('Workspace provisioned — starting up…');
        await fetchProject();
      } else {
        toast.error(data.error || 'Failed to provision workspace');
      }
    } catch {
      toast.error('An error occurred');
    } finally {
      setProvisioning(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-32">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (error || !project) {
    return (
      <div className="container mx-auto py-8 px-6 max-w-5xl">
        <div className="rounded-xl border border-red-500/30 bg-red-500/5 py-8 text-center">
          <p className="text-sm text-red-600">{error ?? "Project not found"}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto py-8 px-6 max-w-5xl space-y-6">

      {/* ── Header ── */}
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-bold">{project.productName}</h1>
          {project.productVision && (
            <p className="text-muted-foreground text-sm mt-1 max-w-xl">{project.productVision}</p>
          )}
          <div className="flex items-center gap-2 mt-2">
            <Badge variant={project.status === "active" ? "default" : "secondary"}>
              {project.status ?? "active"}
            </Badge>
            {project.currentPhase && (
              <Badge variant="outline">{project.currentPhase}</Badge>
            )}
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm" onClick={handleRefresh} disabled={refreshing}>
            <RefreshCw className={`h-4 w-4 mr-1.5 ${refreshing ? "animate-spin" : ""}`} />
            Refresh
          </Button>
          {project.theiaWorkspaceUrl ? (
            <Button size="sm" asChild>
              <a href={project.theiaWorkspaceUrl} target="_blank" rel="noopener noreferrer">
                <Terminal className="h-4 w-4 mr-1.5" />
                Open IDE
              </a>
            </Button>
          ) : (
            <Button size="sm" onClick={handleProvisionWorkspace} disabled={provisioning}>
              {provisioning
                ? <><Loader2 className="h-4 w-4 mr-1.5 animate-spin" />Provisioning…</>
                : <><Terminal className="h-4 w-4 mr-1.5" />Provision IDE</>
              }
            </Button>
          )}
        </div>
      </div>

      {/* ── Agent Panel — Atlas for discovery, Orchestrator once PRD is done ── */}
      {(!project.stage || project.stage === 'discovery') ? (
        <AtlasChat
          projectId={projectId}
          projectName={project.productName}
        />
      ) : (
        <OrchestratorChat
          projectId={projectId}
          projectName={project.productName}
        />
      )}

    </div>
  );
}
