import { useContext, type ReactNode } from "react";
import { BannerFactory } from "~/components/banners";
import { Footer, MiniFooter } from "~/components/footer";
import { SiteHeader } from "~/components/navbar/site-header";
import { useTranslation } from "~/providers/I18nProvider";
import { UserViewContext, UserViewProvider } from "~/lib/userViewContext";
import Head from "next/head";
import Link from "next/link";
import {
  ExternalLink,
  Mail,
  MessagesSquare,
  Paperclip,
  Search,
  ShoppingBag,
  Tickets,
  UserCog,
} from "lucide-react";
import { Button } from "~/components/ui/button";
import { Separator } from "~/components/ui/separator";
import { usePathname } from "next/navigation";
import { api } from "~/utils/api";
import { Sidebar } from "~/components/area-riservata/sidebar";
import type { UsersId } from "~/schemas/public/Users";
import toast from "react-hot-toast";
import { useRouter } from "next/router";
import {
  useSession,
  EnforcedSessionContext,
} from "~/providers/SessionProvider";
import { WhatsAppIcon } from "~/components/svgs";
import { LoadingPage } from "~/components/loading";
import type { ValidSession } from "~/server/api/trpc";

interface Props {
  children: ReactNode;
  noFooter?: boolean;
}
export const Layout = ({ children, noFooter }: Props) => {
  const { data: bannerData } = api.settings.getBannerData.useQuery({
    area_riservata: false,
  });

  return (
    <div className="flex min-h-screen w-full flex-col">
      <SiteHeader />
      {bannerData?.map((banner) => (
        <div key={`banner-elem-${banner.idbanner}`}>
          {BannerFactory(banner)}
        </div>
      ))}
      <main className="h-full flex-1 grow">{children}</main>

      {!noFooter && <Footer />}
      {/* <CookieConsent /> */}
    </div>
  );
};

export const AreaRiservataLayout = ({
  children,
  noSidebar,
  noFooter,
  ignoreSessionCheck,
}: {
  children: ReactNode;
  noSidebar?: boolean;
  noFooter?: boolean;
  ignoreSessionCheck?: boolean;
}) => {
  const { data: bannerData } = api.settings.getBannerData.useQuery({
    area_riservata: true,
  });
  const session = useSession();
  if (!ignoreSessionCheck) {
    if (session.status === "pending")
      return (
        <div className="flex h-full min-h-screen flex-col text-clip">
          <SiteHeader />

          <main className="flex h-full flex-1 overflow-auto">
            <div className="flex h-auto w-full flex-col md:flex-row">
              <LoadingPage />;
            </div>
          </main>
          {!noFooter && <MiniFooter />}
        </div>
      );
    if (session.status !== "success" || !session.user) {
      window.location.reload();
      return (
        <div className="flex h-full min-h-screen flex-col text-clip">
          <SiteHeader />

          <main className="flex h-full flex-1 overflow-auto">
            <div className="flex h-auto w-full flex-col md:flex-row">
              <LoadingPage />;
            </div>
          </main>
          {!noFooter && <MiniFooter />}
        </div>
      );
    }
  }

  return (
    <div className="flex h-full min-h-screen flex-col text-clip">
      <SiteHeader />
      {bannerData?.map((banner) => (
        <div key={`banner-elem-${banner.idbanner}`}>
          {BannerFactory(banner)}
        </div>
      ))}
      <main className="flex h-full flex-1 overflow-auto">
        <div className="flex h-auto w-full flex-col md:flex-row">
          {noSidebar ? null : (
            <Sidebar isAdmin={session.user?.isAdmin || false} />
          )}
          <EnforcedSessionContext.Provider value={session as ValidSession}>
            {children}
          </EnforcedSessionContext.Provider>
        </div>
      </main>
      {!noFooter && <MiniFooter />}

      {/* <CookieConsent /> */}
    </div>
  );
};

export const AreaRiservataLayoutUserView = ({
  children,
}: {
  children: ReactNode & { props: { userId: UsersId } };
}) => {
  const { t } = useTranslation();

  const props = children.props as { userId: UsersId };

  return (
    <div className="flex h-full min-h-screen flex-col bg-white">
      <SiteHeader />
      <main className="flex h-full flex-1 overflow-auto">
        <UserViewProvider userId={props.userId}>
          <Head>
            <title>{t.heads.area_riservata_titolo}</title>
            <meta
              name="description"
              content={t.heads.area_riservata_description}
            />
          </Head>
          <div className="flex h-auto w-full flex-col md:flex-row">
            <Sidebar isAdmin />

            <div className="mx-4 my-3 flex-1 overflow-auto">
              <UserViewHeader />

              {children}
            </div>
          </div>
        </UserViewProvider>
      </main>

      <MiniFooter />

      {/* <CookieConsent /> */}
    </div>
  );
};

const UserViewHeader = () => {
  const data = useContext(UserViewContext);
  const pathname = usePathname();
  const router = useRouter();
  const { mutate: swap } = api.auth.swapUser.useMutation({
    onSuccess: async () => {
      toast.success("Utente cambiato con successo");
      await router.push("/area-riservata/dashboard");
      router.reload();
    },
  });
  if (!data) return <div>Errore</div>;
  return (
    <div className="mb-5 flex flex-col space-y-5">
      <div className="flex flex-row flex-wrap items-baseline gap-3">
        <div className="text-3xl">{data.username}</div>
        <div className="text-muted-foreground text-sm">
          {data.email} | {data.telefono}
        </div>

        <Link href={`https://wa.me/${data.telefono}`} target="_blank">
          <Button
            className="flex items-center gap-2"
            variant="success"
            size="sm"
          >
            <WhatsAppIcon className="size-4 fill-white" />
            WhatsApp
          </Button>
        </Link>
      </div>
      <div className="flex flex-row flex-wrap gap-2">
        <Link href={`/area-riservata/admin/user-view/edit-user/${data.id}`}>
          <Button
            className="flex items-center gap-2 border"
            variant={pathname.includes("edit-user") ? "secondary" : "outline"}
            size="sm"
          >
            <UserCog /> Profilo
          </Button>
        </Link>
        <Link href={`/area-riservata/admin/user-view/servizio/${data.id}`}>
          <Button
            className="flex items-center gap-2 border"
            variant={pathname.includes("servizio") ? "secondary" : "outline"}
            size="sm"
          >
            <Tickets /> Servizi
          </Button>
        </Link>

        <Link href={`/area-riservata/admin/user-view/ricerca/${data.id}`}>
          <Button
            className="flex items-center gap-2 border"
            variant={pathname.includes("ricerca") ? "secondary" : "outline"}
            size="sm"
          >
            <Search /> Ricerca
          </Button>
        </Link>
        <Link href={`/area-riservata/admin/user-view/comunicazioni/${data.id}`}>
          <Button
            className="flex items-center gap-2 border"
            variant={
              pathname.includes("comunicazioni") ? "secondary" : "outline"
            }
            size="sm"
          >
            <Mail /> Comunicazioni
          </Button>
        </Link>

        <Link href={`/area-riservata/admin/user-view/ordini/${data.id}`}>
          <Button
            className="flex items-center gap-2 border"
            variant={pathname.includes("ordini") ? "secondary" : "outline"}
            size="sm"
          >
            <ShoppingBag /> Ordini
          </Button>
        </Link>
        <Link href={`/area-riservata/admin/user-view/allegati/${data.id}`}>
          <Button
            className="flex items-center gap-2 border"
            variant={pathname.includes("allegati") ? "secondary" : "outline"}
            size="sm"
          >
            <Paperclip /> Allegati
          </Button>
        </Link>

        <Link
          href={
            data.chatid
              ? {
                  pathname: "/area-riservata/admin/chats",
                  query: { chatid: data.chatid },
                }
              : "/area-riservata/admin/chats"
          }
          target="_blank"
        >
          <Button
            className="flex items-center gap-2 border"
            variant={!data.chatid ? "ghost" : "outline"}
            size="sm"
          >
            <MessagesSquare /> Chat
          </Button>
        </Link>

        <Button
          size="sm"
          className="flex gap-2"
          onClick={() =>
            swap({
              id: data.id,
            })
          }
        >
          <ExternalLink /> Login
        </Button>
      </div>
      <Separator />
    </div>
  );
};
