"use client";

import { useEffect, useState } from "react";
import PageContainer from "@/components/layout/page-container";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { workspacesInfoContent } from "@/config/infoconfig";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";

type OrganizationSummary = {
  id: string;
  name: string;
  slug: string;
  plan: string;
  imageUrl: string | null;
  role: string;
  canManageUsers: boolean;
};

export default function WorkspacesPage() {
  const { data: session, status, update } = useSession();
  const router = useRouter();
  const [workspaceName, setWorkspaceName] = useState("");
  const [isCreating, setIsCreating] = useState(false);
  const [organizations, setOrganizations] = useState<OrganizationSummary[]>([]);
  const [isLoadingOrganizations, setIsLoadingOrganizations] = useState(false);

  const canManageOrganizations = session?.user?.systemRole === "super_admin";

  useEffect(() => {
    if (!canManageOrganizations) {
      setOrganizations([]);
      return;
    }

    let cancelled = false;

    async function loadOrganizations() {
      setIsLoadingOrganizations(true);

      try {
        const response = await fetch("/api/organizations");
        const data = (await response.json()) as {
          organizations?: OrganizationSummary[];
          message?: string;
        };

        if (!response.ok) {
          throw new Error(data.message ?? "Unable to load organizations");
        }

        if (!cancelled) {
          setOrganizations(data.organizations ?? []);
        }
      } catch (error) {
        if (!cancelled) {
          toast.error(
            error instanceof Error
              ? error.message
              : "Unable to load organizations",
          );
        }
      } finally {
        if (!cancelled) {
          setIsLoadingOrganizations(false);
        }
      }
    }

    void loadOrganizations();

    return () => {
      cancelled = true;
    };
  }, [canManageOrganizations, session?.user?.activeOrganizationId]);

  const createWorkspace = async () => {
    if (!workspaceName.trim()) {
      toast.error("Workspace name is required");
      return;
    }

    setIsCreating(true);

    try {
      const response = await fetch("/api/organizations", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: workspaceName }),
      });

      if (!response.ok) {
        const data = (await response.json().catch(() => null)) as {
          message?: string;
        } | null;
        throw new Error(data?.message ?? "Unable to create workspace");
      }

      setWorkspaceName("");
      await update();
      router.refresh();
      toast.success("Workspace created");
    } catch (error) {
      toast.error(
        error instanceof Error ? error.message : "Unable to create workspace",
      );
    } finally {
      setIsCreating(false);
    }
  };

  return (
    <PageContainer
      pageTitle="Workspaces"
      pageDescription="Manage your app-owned workspaces and switch your active organization."
      infoContent={workspacesInfoContent}
      isLoading={
        status === "loading" ||
        (canManageOrganizations && isLoadingOrganizations)
      }
      access={canManageOrganizations}
      accessFallback={
        <div className="text-muted-foreground rounded-lg border border-dashed p-8 text-center">
          Only super admins can manage workspaces.
        </div>
      }
    >
      <div className="grid gap-6 xl:grid-cols-[1.2fr_0.8fr]">
        <Card>
          <CardHeader>
            <CardTitle>Your workspaces</CardTitle>
            <CardDescription>
              The active workspace controls organization-scoped product data and
              access checks.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            {organizations.length ? (
              organizations.map((organization) => {
                const isActive =
                  organization.id === session?.user?.activeOrganizationId;

                return (
                  <button
                    key={organization.id}
                    type="button"
                    onClick={() => router.push("/dashboard/workspaces/team")}
                    aria-label={`Open workspace ${organization.name}`}
                    className={`w-full rounded-lg border p-4 text-left transition ${
                      isActive
                        ? "border-primary bg-primary/5"
                        : "hover:bg-accent"
                    }`}
                  >
                    <div className="flex items-center justify-between gap-4">
                      <div>
                        <div className="font-semibold">{organization.name}</div>
                        <div className="text-muted-foreground text-sm">
                          Role: {organization.role}
                        </div>
                      </div>
                      <div className="text-xs font-medium uppercase">
                        {isActive ? "Active" : "Open"}
                      </div>
                    </div>
                  </button>
                );
              })
            ) : (
              <div className="text-muted-foreground rounded-lg border border-dashed p-6 text-sm">
                No workspace found yet. Create your first workspace to unlock
                organization-scoped product management.
              </div>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Create workspace</CardTitle>
            <CardDescription>
              This flow is limited to super admins in the organization RBAC
              model.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <label htmlFor="workspace-name" className="text-sm font-medium">
                Workspace name
              </label>
              <Input
                id="workspace-name"
                value={workspaceName}
                onChange={(event) => setWorkspaceName(event.target.value)}
                placeholder="Acme Studio"
                disabled={isCreating}
              />
            </div>
            <Button
              className="w-full"
              isLoading={isCreating}
              onClick={createWorkspace}
            >
              Create workspace
            </Button>
          </CardContent>
        </Card>
      </div>
    </PageContainer>
  );
}
