"use client";

import { useState } from "react";
import Link from "next/link";
import { useSession } from "next-auth/react";
import { Briefcase, MessageSquareText, Plus } from "lucide-react";
import { cn } from "@/lib/utils/cn";
import { FEATURES } from "@/config/features";
import { setActiveMode } from "@/lib/actions/participant";
import { swalToast } from "@/lib/utils/swal";
import type { ActiveMode } from "@/types/participant";

interface ModeSwitchProps {
  current: ActiveMode;
  onNavigate?: () => void;
}

const MODES: Array<{ id: ActiveMode; label: string; icon: typeof Briefcase }> = [
  { id: "creator", label: "Creator", icon: Briefcase },
  { id: "participant", label: "Participant", icon: MessageSquareText },
];

/**
 * Creator ⇄ Participant toggle. Renders only when the user has both
 * capabilities; otherwise offers a link to add the missing one.
 */
export function ModeSwitch({ current, onNavigate }: ModeSwitchProps) {
  const { data: session, update } = useSession();
  const [pending, setPending] = useState<ActiveMode | null>(null);

  if (!FEATURES.participantPlatform || !session?.user) return null;

  const user = session.user;
  if (user.impersonatorAdminId) return null;

  const hasCreator = user.hasCreatorCapability ?? Boolean(user.workspaceId);
  const hasParticipant = user.hasParticipantCapability ?? false;

  if (!hasParticipant || !hasCreator) {
    if (user.role !== "client") return null;
    const addParticipant = hasCreator && !hasParticipant;
    return (
      <Link
        href={
          addParticipant
            ? "/onboarding?intent=participate"
            : "/onboarding?intent=create"
        }
        onClick={onNavigate}
        className="mb-4 flex items-center gap-2 rounded-[10px] border border-dashed border-white/20 px-3 py-2 text-[12px] font-semibold text-white/70 transition-colors hover:border-white/40 hover:text-white"
      >
        <Plus className="h-3.5 w-3.5" />
        {addParticipant ? "Start answering surveys" : "Create your own surveys"}
      </Link>
    );
  }

  async function switchTo(mode: ActiveMode) {
    if (mode === current || pending) return;
    setPending(mode);
    const result = await setActiveMode(mode);
    if (!result.success) {
      setPending(null);
      void swalToast.fire({ icon: "error", title: result.error });
      return;
    }
    await update({});
    onNavigate?.();
    window.location.assign(result.data!.redirectTo);
  }

  return (
    <div
      role="tablist"
      aria-label="Workspace mode"
      className="mb-4 grid grid-cols-2 gap-1 rounded-[10px] bg-white/6 p-1"
    >
      {MODES.map(({ id, label, icon: Icon }) => {
        const active = id === current;
        return (
          <button
            key={id}
            type="button"
            role="tab"
            aria-selected={active}
            disabled={Boolean(pending)}
            onClick={() => switchTo(id)}
            className={cn(
              "flex items-center justify-center gap-1.5 rounded-[7px] px-2 py-1.5 text-[12px] font-semibold transition-colors",
              active
                ? "bg-white text-navy"
                : "text-white/70 hover:bg-white/10 hover:text-white",
              pending === id && "opacity-70"
            )}
          >
            <Icon className="h-3.5 w-3.5" />
            {label}
          </button>
        );
      })}
    </div>
  );
}
