import {
  AppShell,
  AuthProvider,
  DefaultSidebar,
  SidebarGroup,
  SidebarItem,
  SidebarLayout,
  useAuth,
} from "@tailor-platform/app-shell";
import { useQuery } from "urql";
import { UserProfileMenu } from "@/components/composed/user-profile-menu";
import { graphql } from "@/graphql";
import { authClient } from "./lib/auth-client";
import { GraphQLProvider } from "./providers/graphql-provider";

const MeStatusQuery = graphql(`
  query MeStatus {
    me {
      status
    }
  }
`);

const AuthGuard = () => {
  const { login } = useAuth();

  return (
    <main className="min-h-screen grid place-items-center px-4">
      <div className="w-full max-w-sm rounded-lg border bg-card p-6 space-y-4">
        <h1 className="text-lg font-semibold">Sign in required</h1>
        <p className="text-sm text-muted-foreground">
          Continue with your Tailor account to access this app.
        </p>
        <button
          type="button"
          onClick={() => {
            void login();
          }}
          className="inline-flex h-9 w-full items-center justify-center rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground hover:bg-primary/90"
        >
          Sign in
        </button>
      </div>
    </main>
  );
};

const ActiveUserGuard = ({ children }: { children: React.ReactNode }) => {
  const { logout } = useAuth();
  const [{ data, fetching }] = useQuery({ query: MeStatusQuery });

  if (fetching) return null;

  if (data?.me?.status !== "ACTIVE") {
    return (
      <main className="min-h-screen grid place-items-center px-4">
        <div className="w-full max-w-sm rounded-lg border bg-card p-6 space-y-4">
          <h1 className="text-lg font-semibold">Account deactivated</h1>
          <p className="text-sm text-muted-foreground">
            Your account has been deactivated. Please contact an administrator.
          </p>
          <button
            type="button"
            onClick={() => void logout()}
            className="inline-flex h-9 w-full items-center justify-center rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground hover:bg-primary/90"
          >
            Sign out
          </button>
        </div>
      </main>
    );
  }

  return <>{children}</>;
};

const App = () => {
  return (
    <AuthProvider client={authClient} guardComponent={AuthGuard}>
      <GraphQLProvider authClient={authClient}>
        <ActiveUserGuard>
          <AppShell title="template-app">
            <SidebarLayout
              sidebar={
                <DefaultSidebar footer={<UserProfileMenu />}>
                  <SidebarGroup title="User Management">
                    <SidebarItem to="/user-management/user" />
                    <SidebarItem to="/user-management/role" />
                  </SidebarGroup>
                </DefaultSidebar>
              }
            />
          </AppShell>
        </ActiveUserGuard>
      </GraphQLProvider>
    </AuthProvider>
  );
};

export default App;
