"use client";

import Link from "next/link";
import { Suspense, useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";
import { RoleAgentsPanel } from "@/components/roles/role-agents-panel";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { getBusiness } from "@/lib/data-store";
import type { Business } from "@/lib/types";

function RoleAgentsContent() {
  const searchParams = useSearchParams();
  const initialRole = searchParams.get("role") ?? undefined;
  const [business, setBusiness] = useState<Business | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    getBusiness()
      .then(setBusiness)
      .finally(() => setLoading(false));
  }, []);

  if (loading) {
    return <div className="py-8 text-sm text-slate-400">Loading role agents…</div>;
  }

  if (!business) {
    return (
      <div className="py-8">
        <Card>
          <CardContent className="p-6 text-sm text-slate-400">
            No Business Brain yet. Load a demo or complete onboarding to deploy role agents.
            <div className="mt-4 flex flex-wrap gap-2">
              <Link href="/demo">
                <Button>Explore demos</Button>
              </Link>
              <Link href="/onboarding">
                <Button variant="outline">Build My Business Brain</Button>
              </Link>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-4 py-4">
      <div>
        <h1 className="text-2xl font-semibold">Role Agents</h1>
        <p className="text-sm text-slate-400">
          Automate role-specific work for {business.input.businessName}. Each agent runs tasks and reports back with a summary and receipts.
        </p>
      </div>

      <RoleAgentsPanel business={business} onUpdate={setBusiness} initialRole={initialRole} />
    </div>
  );
}

export default function RoleAgentsPage() {
  return (
    <Suspense fallback={<div className="py-8 text-sm text-slate-400">Loading role agents…</div>}>
      <RoleAgentsContent />
    </Suspense>
  );
}
