import type { ReactNode } from 'react';
import { Loader2, ServerOff } from 'lucide-react';
import { NO_ACTIVE_SERVER } from './shared';
import { headscaleErrorMessage } from './useHeadscaleServers';
import { ErrorNote } from './Cards';

// The loading / no-server / failed states every domain section shares.
//
// "No active server" is a 409 carrying a `code`, deliberately not a 404 and deliberately not an empty
// list — an empty node table would read as "your tailnet is empty", which is a very different and much
// more alarming statement than "you haven't picked a server".

function isNoActiveServer(err: unknown): boolean {
  const raw = (err as { message?: unknown } | null)?.message;
  if (typeof raw !== 'string') return false;
  try {
    return (JSON.parse(raw) as { code?: unknown }).code === NO_ACTIVE_SERVER;
  } catch {
    return false;
  }
}

type ViewShellProps = {
  isLoading: boolean;
  error: unknown;
  /** What this section is called, for the loading and empty copy. */
  label: string;
  children: ReactNode;
};

export const ViewShell = ({ isLoading, error, label, children }: ViewShellProps) => {
  if (isLoading) {
    return (
      <div className="flex h-full items-center justify-center text-sm text-zinc-500">
        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
        Loading {label}…
      </div>
    );
  }

  if (error && isNoActiveServer(error)) {
    return (
      <div className="flex h-full flex-col items-center justify-center gap-3 p-6 text-center">
        <div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-white/5 text-zinc-400">
          <ServerOff className="h-6 w-6" />
        </div>
        <div>
          <div className="text-base font-semibold text-zinc-100">No server selected</div>
          <p className="mt-1 text-sm text-zinc-500">Pick one in the Servers section to see its {label}.</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-4">
        <ErrorNote>
          Could not load {label}: {headscaleErrorMessage(error)}
        </ErrorNote>
      </div>
    );
  }

  return <div className="h-full overflow-y-auto p-4">{children}</div>;
};

/** Centred "nothing here yet" body for a section whose fetch succeeded but returned nothing. */
export const EmptyBody = ({ icon, title, hint }: { icon: ReactNode; title: string; hint: string }) => (
  <div className="flex flex-col items-center gap-3 py-16 text-center">
    <div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-white/5 text-zinc-400">{icon}</div>
    <div>
      <div className="text-base font-semibold text-zinc-100">{title}</div>
      <p className="mt-1 max-w-sm text-sm text-zinc-500">{hint}</p>
    </div>
  </div>
);
