import { useLabMeta } from "@/components/labs/hooks-v2";
import { useMe } from "@/components/me-context";
import { Badge } from "@/components/ui/badge";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { useLocaleFunction } from "@/hooks/use-localed";
import type { LabInstanceMeta } from "@/lib/api/labs.v2";
import { isServerError } from "@/lib/errors";
import { cn } from "@/lib/utils";
import { Loader2Icon } from "lucide-react";
import Link from "next/link";

export default function SiteHeaderLab({
  activeLabInstance,
  isLoading,
  restSeconds,
  error,
  className,
}: {
  activeLabInstance?: LabInstanceMeta | null;
  isLoading: boolean;
  restSeconds: number;
  error: Error | null;
  className?: string;
}) {
  const { data: me } = useMe();
  const { data: meta } = useLabMeta(activeLabInstance?.lab_code);

  const t = useLocaleFunction();

  if (!me) {
    return undefined;
  }

  if (isLoading) {
    return (
      <Badge
        variant="outline"
        className={cn("text-muted-foreground", className)}
      >
        <Loader2Icon className="size-4 animate-spin repeat-infinite mr-2" />
        {t("common.loading")}
      </Badge>
    );
  }

  if ((error && isServerError(error, 404)) || !activeLabInstance) {
    return (
      <Badge
        variant="outline"
        className={cn("text-muted-foreground", className)}
      >
        <div className="w-2 h-2 rounded-full bg-gray-400 mr-2"></div>
        {t("header.no-active-lab")}
      </Badge>
    );
  }

  return (
    <TooltipProvider>
      <Tooltip>
        <TooltipTrigger asChild>
          <Link href={`/lab?instance=${activeLabInstance.id}`} prefetch={false}>
            <Badge variant="secondary" className={className}>
              {activeLabInstance.status === "running" && (
                <span className="relative w-max h-max mr-0.5 inline-flex items-center justify-center p-0.5">
                  <span className="absolute left-0.5 top-0.5 w-2 h-2 bg-green-400 dark:bg-green-500 rounded-full animate-ripple" />
                  <span className="bg-green-400 dark:bg-green-500 inline-block w-2 h-2 rounded-full" />
                </span>
              )}
              {activeLabInstance.status === "creating" && (
                <span className="relative w-max h-max mr-0.5 inline-flex items-center justify-center p-0.5">
                  <span className="absolute left-0.5 top-0.5 w-2 h-2 bg-yellow-400 dark:bg-yellow-500 rounded-full animate-ripple" />
                  <span className="bg-yellow-400 dark:bg-yellow-500 inline-block w-2 h-2 rounded-full" />
                </span>
              )}
              {(activeLabInstance.status === "timeout" ||
                activeLabInstance.status === "creating_failed") && (
                <span className="relative w-max h-max mr-0.5 inline-flex items-center justify-center p-0.5">
                  <span className="absolute left-0.5 top-0.5 w-2 h-2 bg-destructive dark:bg-destructive rounded-full animate-ripple" />
                  <span className="bg-destructive dark:bg-destructive inline-block w-2 h-2 rounded-full" />
                </span>
              )}
              <span className="pl-1 text-muted-foreground">
                {t("header.running-lab", formatSeconds(restSeconds))}
              </span>
            </Badge>
          </Link>
        </TooltipTrigger>
        <TooltipContent side="bottom" sideOffset={8}>
          <span className="font-semibold mr-2">{t(meta, "title")}</span>
          <span className="text-muted-foreground w-12 font-mono">
            {formatSeconds(restSeconds)}
          </span>
        </TooltipContent>
      </Tooltip>
    </TooltipProvider>
  );
}

export function SiteHeaderLabMobile({
  activeLabInstance,
  isLoading,
  restSeconds,
  error,
  className,
}: {
  activeLabInstance?: LabInstanceMeta | null;
  isLoading: boolean;
  restSeconds: number;
  error: Error | null;
  className?: string;
}) {
  const { data: me } = useMe();

  const t = useLocaleFunction();

  if (!me) {
    return undefined;
  }

  if (isLoading) {
    return (
      <DropdownMenuItem className={className}>
        <Loader2Icon className="size-4 animate-spin repeat-infinite mr-2" />
        <span className="text-muted-foreground">{t("common.loading")}</span>
      </DropdownMenuItem>
    );
  }

  if ((error && isServerError(error, 404)) || !activeLabInstance) {
    return (
      <DropdownMenuItem className={className}>
        <span className="text-muted-foreground">
          {t("header.no-active-lab")}
        </span>
      </DropdownMenuItem>
    );
  }

  return (
    <DropdownMenuItem className={cn("cursor-pointer", className)}>
      <Link className="w-full flex items-center" href="/lab" prefetch={false}>
        <span>{t("header.running-lab")}</span>
        <span className="ml-2 text-muted-foreground w-12 font-mono">
          {formatSeconds(restSeconds)}
        </span>
        {activeLabInstance.status === "running" && (
          <span className="ml-auto relative w-max h-max inline-flex items-center justify-center p-0.5 mr-0.5">
            <span className="absolute left-0.5 top-0.5 w-2 h-2 bg-green-400 dark:bg-green-500 rounded-full animate-ripple" />
            <span className="bg-green-400 dark:bg-green-500 inline-block w-2 h-2 rounded-full" />
          </span>
        )}
        {activeLabInstance.status === "creating" && (
          <span className="ml-auto relative w-max h-max inline-flex items-center justify-center p-0.5 mr-0.5">
            <span className="absolute left-0.5 top-0.5 w-2 h-2 bg-yellow-400 dark:bg-yellow-500 rounded-full animate-ripple" />
            <span className="bg-yellow-400 dark:bg-yellow-500 inline-block w-2 h-2 rounded-full" />
          </span>
        )}
        {(activeLabInstance.status === "timeout" ||
          activeLabInstance.status === "creating_failed") && (
          <span className="ml-auto relative w-max h-max inline-flex items-center justify-center p-0.5 mr-0.5">
            <span className="absolute left-0.5 top-0.5 w-2 h-2 bg-destructive dark:bg-destructive rounded-full animate-ripple" />
            <span className="bg-destructive dark:bg-destructive inline-block w-2 h-2 rounded-full" />
          </span>
        )}
      </Link>
    </DropdownMenuItem>
  );
}

function formatSeconds(seconds: number) {
  let minutes = 0;
  let hours = 0;
  if (seconds > 60) {
    minutes = Math.floor(seconds / 60);
    seconds = seconds % 60;
  }

  if (minutes > 60) {
    hours = Math.floor(minutes / 60);
    minutes = minutes % 60;
  }

  if (hours > 0) {
    return `${hours}h${minutes}m`;
  }
  if (minutes > 10) {
    return `${minutes}m`;
  } else if (minutes > 0) {
    return `${minutes}m${seconds}s`;
  } else {
    return `${seconds}s`;
  }
}
