"use client";

import { useEffect, useState } from "react";
import type { ComponentType, CSSProperties, ReactNode } from "react";
import { AnimatePresence, motion } from "framer-motion";
import { Bell, Camera, ChevronDown, CreditCard, Heart, HelpCircle, Home, MapPinned, Menu, Package, PanelLeftClose, PanelLeftOpen, Pencil, Search, Settings2, Star, Store, UserCircle2 } from "lucide-react";
import Image from "next/image";
import ClientPortalLogoutButton from "@/components/ClientPortalLogoutButton";
import { getReadableTextColor } from "@/lib/color-contrast";
import {
  AvatarBadge,
  NavItem,
  PremiumCard,
  ProgressRing,
  SnapshotRow,
  StatusPill,
  formatDateTime,
  getInitials,
  hexToRgba,
} from "@/components/client-portal/shared";

type ShellProps = {
  slug: string;
  storeName: string;
  logoUrl: string;
  primaryColor: string;
  customerName: string;
  client: {
    email?: string | null;
    phone?: string | null;
    portal_last_login_at?: string | null;
    avatar_url?: string | null;
  };
  completion: number;
  totalSpent: number;
  latestOrder: {
    number: number;
    created_at: string;
    status: string;
  } | null;
  orders: Array<{
    total_amount: number;
  }>;
  activeSection: string;
  sidebarOpen: boolean;
  searchQuery: string;
  navItems: NavItem[];
  onOpenSection: (section: NavItem["id"]) => void;
  onToggleSidebar: (open: boolean) => void;
  onSearchChange: (value: string) => void;
  onAvatarClick?: () => void;
  contentLayout?: "default" | "integrated";
  children: ReactNode;
};

export function PortalShell({
  slug,
  storeName,
  logoUrl,
  primaryColor,
  customerName,
  client,
  activeSection,
  sidebarOpen,
  searchQuery,
  navItems,
  onOpenSection,
  onToggleSidebar,
  onSearchChange,
  onAvatarClick,
  contentLayout = "default",
  children,
}: ShellProps) {
  const [desktopSidebarCollapsed, setDesktopSidebarCollapsed] = useState(false);
  const isIntegratedLayout = contentLayout === "integrated";
  const headerHeightClass = "h-[76px] lg:h-[92px]";
  const headerOffsetClass = "pt-[76px] lg:pt-[92px]";
  const sidebarTopClass = "top-[76px] lg:top-[92px]";
  const desktopSidebarWidthClass = desktopSidebarCollapsed ? "w-[84px]" : "w-[236px]";
  const desktopSidebarInsetClass = desktopSidebarCollapsed ? "lg:pl-[108px]" : "lg:pl-[268px]";

  const shellStyle = {
    background: "linear-gradient(180deg, #fcfcfc 0%, #f8f8f8 100%)",
  };
  const sidebarStyle = {
    background: "#ffffff",
    borderColor: "#ece7f2",
    boxShadow: "none",
  };
  const brandPanelStyle = {
    backgroundColor: primaryColor,
    borderColor: hexToRgba(primaryColor, 0.18),
  };

  useEffect(() => {
    if (!sidebarOpen) return;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = previousOverflow;
    };
  }, [sidebarOpen]);

  return (
    <div className="min-h-screen text-zinc-900" style={shellStyle}>
      <header
        className="fixed inset-x-0 top-0 z-40 border-b lg:border-[#efedf2] lg:bg-white"
        style={{
          backgroundColor: primaryColor,
          borderColor: hexToRgba(primaryColor, 0.24), color: getReadableTextColor(primaryColor) }}
      >
        <div className={`flex ${headerHeightClass}`}>
          <div
            className={`hidden h-full shrink-0 items-center border-r px-6 lg:flex ${desktopSidebarWidthClass} ${
              desktopSidebarCollapsed ? "justify-center" : ""
            }`}
            style={brandPanelStyle}
          >
            <div className="min-w-0">
              {logoUrl ? (
                desktopSidebarCollapsed ? (
                  <div className="flex h-10 w-10 items-center justify-center text-lg font-semibold text-white">
                    {storeName.slice(0, 1).toUpperCase()}
                  </div>
                ) : (
                  <Image
                    src={logoUrl}
                    alt={storeName}
                    width={260}
                    height={56}
                    className="h-11 w-auto max-w-none object-contain"
                    unoptimized
                  />
                )
              ) : (
                <div className={`truncate font-semibold tracking-[-0.03em] text-white ${desktopSidebarCollapsed ? "text-lg" : "text-xl"}`}>
                  {desktopSidebarCollapsed ? storeName.slice(0, 1).toUpperCase() : storeName}
                </div>
              )}
            </div>
          </div>

          <div className="flex min-w-0 flex-1 items-center justify-end gap-2 px-3 sm:gap-4 sm:px-6 lg:px-8">
            <div className="mr-auto flex min-w-0 items-center gap-2 lg:hidden">
              <button
                type="button"
                onClick={() => onToggleSidebar(true)}
                className="inline-flex h-10 w-10 items-center justify-center border text-white transition hover:bg-white/10 sm:h-11 sm:w-11"
                style={{ borderColor: "rgba(255,255,255,0.22)", backgroundColor: "rgba(255,255,255,0.08)" }}
              >
                <Menu className="h-5 w-5" />
              </button>
              <div className="min-w-0 px-1 py-1 sm:px-2">
                {logoUrl ? (
                  <Image
                    src={logoUrl}
                    alt={storeName}
                    width={260}
                    height={56}
                    className="h-8 w-auto max-w-[148px] object-contain sm:h-10 sm:max-w-none"
                    unoptimized
                  />
                ) : (
                  <div className="max-w-[140px] truncate text-base font-semibold tracking-[-0.03em] text-white sm:max-w-none sm:text-lg">{storeName}</div>
                )}
              </div>
            </div>

            <div className="flex min-w-0 items-center gap-2 sm:gap-3">
              <label className="group hidden h-12 min-w-[420px] items-center gap-3 border border-[#efedf2] bg-white px-4 xl:flex">
                <Search className="h-4 w-4 text-zinc-400 transition group-focus-within:text-zinc-700" />
                <input
                  value={searchQuery}
                  onChange={(event) => onSearchChange(event.target.value)}
                  placeholder="Buscar pedidos ou produtos"
                  className="h-full w-full bg-transparent text-sm text-zinc-900 outline-none placeholder:text-zinc-400"
                />
              </label>

              <button
                type="button"
                onClick={() => onOpenSection("catalog")}
                className="inline-flex h-10 items-center gap-2 border px-3 text-sm font-semibold transition sm:h-12 sm:px-4 lg:border-[#efedf2] lg:bg-white lg:text-zinc-700 lg:hover:bg-zinc-50 lg:hover:text-zinc-950"
                style={{
                  borderColor: hexToRgba(getReadableTextColor(primaryColor), 0.22),
                  backgroundColor: hexToRgba(getReadableTextColor(primaryColor), 0.08),
                  color: getReadableTextColor(primaryColor),
                }}
              >
                <Store className="h-4 w-4" />
                <span className="hidden sm:inline">Catálogo</span>
              </button>
              <details className="relative">
                <summary
                  className="relative inline-flex h-10 w-10 cursor-pointer list-none items-center justify-center border transition sm:h-12 sm:w-12 lg:border-[#efedf2] lg:bg-white lg:text-zinc-700 lg:hover:bg-zinc-50 lg:hover:text-zinc-950"
                  style={{
                    borderColor: hexToRgba(getReadableTextColor(primaryColor), 0.22),
                    backgroundColor: hexToRgba(getReadableTextColor(primaryColor), 0.08),
                    color: getReadableTextColor(primaryColor),
                  }}
                >
                  <Bell className="h-5 w-5" />
                  <span
                    className="absolute right-2 top-2 h-2.5 w-2.5 rounded-full border-2 border-white"
                    style={{ backgroundColor: primaryColor, color: getReadableTextColor(primaryColor) }}
                  />
                </summary>
                <div className="absolute right-0 top-[calc(100%+10px)] w-72 rounded-2xl border border-zinc-200/80 bg-white p-3 shadow-[0_24px_60px_rgba(15,23,42,0.12)]">
                  <button
                    type="button"
                    onClick={() => onOpenSection("orders")}
                    className="flex w-full items-center justify-between rounded-xl px-3 py-2.5 text-left text-sm font-medium text-zinc-700 transition hover:bg-zinc-50 hover:text-zinc-950"
                  >
                    Ver pedidos recentes
                  </button>
                  <div className="rounded-xl px-3 py-2 text-xs text-zinc-500">Sem novas notificações</div>
                </div>
              </details>
            </div>
          </div>
        </div>
      </header>

      <AnimatePresence>
        {sidebarOpen ? (
          <>
            <motion.button
              type="button"
              aria-label="Fechar navegação"
              className="fixed inset-0 z-40 bg-[#111827]/25 backdrop-blur-sm lg:hidden"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => onToggleSidebar(false)}
            />
            <motion.aside
              initial={{ x: -24, opacity: 0 }}
              animate={{ x: 0, opacity: 1 }}
              exit={{ x: -24, opacity: 0 }}
              transition={{ duration: 0.2, ease: "easeOut" }}
              className="fixed inset-y-0 left-0 top-0 z-50 flex h-[100dvh] w-[88vw] max-w-[340px] flex-col overflow-hidden border-r text-zinc-900 lg:hidden"
              style={sidebarStyle}
            >
              <div
                className="flex items-center justify-between border-b px-4 py-4"
                style={{
                  backgroundColor: primaryColor,
                  borderColor: hexToRgba(primaryColor, 0.22), color: getReadableTextColor(primaryColor) }}
              >
                <div className="min-w-0">
                  {logoUrl ? (
                    <Image
                      src={logoUrl}
                      alt={storeName}
                      width={220}
                      height={56}
                      className="h-9 w-auto max-w-[170px] object-contain"
                      unoptimized
                    />
                  ) : (
                    <div className="truncate text-lg font-semibold tracking-[-0.03em] text-white">{storeName}</div>
                  )}
                </div>
                <button
                  type="button"
                  onClick={() => onToggleSidebar(false)}
                  className="inline-flex h-10 w-10 items-center justify-center border text-white transition hover:bg-white/10"
                  style={{ borderColor: "rgba(255,255,255,0.22)", backgroundColor: "rgba(255,255,255,0.08)" }}
                  aria-label="Fechar menu"
                >
                  <PanelLeftClose className="h-5 w-5" />
                </button>
              </div>
              <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain p-3.5 sm:p-4">
                <SidebarContent
                  slug={slug}
                  primaryColor={primaryColor}
                  customerName={customerName}
                  client={client}
                  navItems={navItems}
                  activeSection={activeSection}
                  onOpenSection={onOpenSection}
                  onAvatarClick={onAvatarClick}
                  onToggleCollapse={() => setDesktopSidebarCollapsed((current) => !current)}
                  collapsed={false}
                  mobile
                />
              </div>
            </motion.aside>
          </>
        ) : null}
      </AnimatePresence>

      <div className={`relative z-10 min-h-screen ${isIntegratedLayout ? headerOffsetClass : `pt-[88px] lg:pt-[108px]`}`}>
        <aside
          className={`fixed bottom-0 left-0 z-30 hidden border-r border-t text-zinc-900 transition-all duration-300 lg:block ${desktopSidebarWidthClass} ${sidebarTopClass}`}
          style={sidebarStyle}
        >
          <div className="h-full p-4">
            <SidebarContent
              slug={slug}
              primaryColor={primaryColor}
              customerName={customerName}
              client={client}
              navItems={navItems}
              activeSection={activeSection}
              onOpenSection={onOpenSection}
              onAvatarClick={onAvatarClick}
              onToggleCollapse={() => setDesktopSidebarCollapsed((current) => !current)}
              collapsed={desktopSidebarCollapsed}
            />
          </div>
        </aside>

        <div
          className={`px-3 sm:px-6 lg:pr-8 ${desktopSidebarInsetClass} ${
            isIntegratedLayout ? "pb-0" : "pb-12"
          }`}
        >
          <div className="mx-auto w-full max-w-[1800px]">
            <main className={isIntegratedLayout ? "pt-0" : "pt-4"}>{children}</main>
          </div>
        </div>
      </div>
    </div>
  );
}

function SidebarContent({
  slug,
  primaryColor,
  customerName,
  client,
  navItems,
  activeSection,
  onOpenSection,
  onAvatarClick,
  onToggleCollapse,
  collapsed = false,
  mobile = false,
}: {
  slug: string;
  primaryColor: string;
  customerName: string;
  client: {
    email?: string | null;
    phone?: string | null;
    portal_last_login_at?: string | null;
    avatar_url?: string | null;
  };
  navItems: NavItem[];
  activeSection: string;
  onOpenSection: (section: NavItem["id"]) => void;
  onAvatarClick?: () => void;
  onToggleCollapse?: () => void;
  collapsed?: boolean;
  mobile?: boolean;
}) {
  const defaultIconById: Record<NavItem["id"], ComponentType<{ className?: string }>> = {
    overview: Home,
    orders: Package,
    catalog: Store,
    favorites: Heart,
    reviews: Star,
    finance: CreditCard,
    addresses: MapPinned,
    account: UserCircle2,
    support: HelpCircle,
    settings: Settings2,
  };

  const items = navItems.map((item) => ({
    id: item.id,
    label: item.label,
    icon: item.icon || defaultIconById[item.id],
  })).filter((item) => item.id !== "finance" && item.id !== "settings");

  const firstName = customerName.split(" ").filter(Boolean)[0] || "Cliente";
  const navInteractiveStyle = {
    "--portal-nav-hover": hexToRgba(primaryColor, 0.08),
    "--portal-nav-color": primaryColor,
  } as CSSProperties;

  return (
    <div className={`flex h-full min-h-full flex-col ${collapsed ? "items-center" : ""}`}>
      {!collapsed && !mobile ? (
        <div className="mb-5 flex justify-end">
          <button
            type="button"
            onClick={onToggleCollapse}
            className="inline-flex h-10 w-10 items-center justify-center border border-zinc-200 bg-white text-zinc-700 transition hover:bg-[var(--portal-nav-hover)] hover:text-[var(--portal-nav-color)]"
            style={navInteractiveStyle}
            aria-label="Alternar menu lateral"
          >
            <PanelLeftClose className="h-5 w-5" />
          </button>
        </div>
      ) : !mobile ? (
        <AvatarBadge
          customerName={customerName}
          avatarUrl={client.avatar_url || ""}
          primaryColor={primaryColor}
          size="sm"
        />
      ) : null}

      {!collapsed ? (
        <div className="mb-5 flex flex-col items-center">
          <div className="relative">
            <div className="h-20 w-20 overflow-hidden rounded-full border border-zinc-200 bg-white">
              {client.avatar_url ? (
                <Image
                  src={client.avatar_url}
                  alt={customerName}
                  width={80}
                  height={80}
                  className="h-full w-full object-cover"
                  unoptimized
                />
              ) : (
                <div
                  className="flex h-full w-full items-center justify-center text-lg font-bold text-white"
                  style={{ backgroundColor: primaryColor, color: getReadableTextColor(primaryColor) }}
                >
                  {firstName.slice(0, 1).toUpperCase()}
                </div>
              )}
            </div>
            <button
              type="button"
              onClick={onAvatarClick}
              className="absolute -bottom-1 -right-1 inline-flex h-8 w-8 cursor-pointer items-center justify-center rounded-full border-2 border-white bg-white text-zinc-900 transition hover:scale-105"
            >
              <Pencil className="h-3.5 w-3.5" />
            </button>
          </div>
          <div className="mt-3 text-sm font-semibold text-zinc-900">{firstName}</div>
        </div>
      ) : null}

      <div className={`mt-1 flex-1 space-y-1 ${collapsed ? "w-full px-1" : ""}`}>
        {items.map((item) => {
          const active = activeSection === item.id;
          const Icon = item.icon;
          return (
            <button
              key={item.id}
              type="button"
              onClick={() => onOpenSection(item.id)}
              className={`group flex items-center gap-3 text-zinc-700 transition hover:bg-[var(--portal-nav-hover)] hover:text-[var(--portal-nav-color)] ${
                collapsed ? "h-11 w-11 justify-center" : "w-full px-3 py-2.5 text-left"
              }`}
              style={
                active
                  ? {
                      ...navInteractiveStyle,
                      color: primaryColor,
                      backgroundColor: hexToRgba(primaryColor, 0.1),
                    }
                  : navInteractiveStyle
              }
            >
              <Icon className="h-4.5 w-4.5 shrink-0" />
              {!collapsed ? <span className="truncate text-sm font-medium">{item.label}</span> : null}
            </button>
          );
        })}
      </div>

      {!collapsed ? (
        <div className="mt-5 border-t border-zinc-200 pt-4">
          <details className="group border border-zinc-200 bg-white text-zinc-900">
            <summary className="flex cursor-pointer list-none items-center justify-between gap-2.5 p-3">
              <div className="flex min-w-0 items-center gap-2.5">
                <AvatarBadge
                  customerName={customerName}
                  avatarUrl={client.avatar_url || ""}
                  primaryColor={primaryColor}
                  size="sm"
                />
                <div className="min-w-0">
                  <div className="truncate text-[18px] font-semibold leading-5 text-zinc-900">{firstName}</div>
                  <div className="truncate text-xs text-zinc-500">{client.email || "conta@ativa.com"}</div>
                </div>
              </div>
              <ChevronDown className="h-4 w-4 shrink-0 text-zinc-500 transition group-open:rotate-180" />
            </summary>
            <div className="border-t border-zinc-200/80 px-3 pb-3 pt-2">
              <button
                type="button"
                onClick={() => onOpenSection("account")}
                className="inline-flex w-full items-center rounded-xl px-3 py-2.5 text-left text-sm font-semibold text-zinc-700 transition hover:bg-zinc-100 hover:text-zinc-950"
              >
                Alterar senha
              </button>
              <ClientPortalLogoutButton
                slug={slug}
                className="mt-1 w-full justify-start rounded-xl border-red-200 bg-white text-red-600 hover:border-red-300 hover:text-red-700"
              />
              <div className="px-1 pt-1 text-[11px] text-zinc-500">{formatDateTime(client.portal_last_login_at)}</div>
            </div>
          </details>
        </div>
      ) : (
        <div className="mt-4">
          <button
            type="button"
            onClick={onToggleCollapse}
            className="mb-2 inline-flex h-11 w-11 items-center justify-center rounded-2xl border border-zinc-200 bg-white text-zinc-700 shadow-sm transition hover:bg-[var(--portal-nav-hover)] hover:text-[var(--portal-nav-color)]"
            style={navInteractiveStyle}
            aria-label="Expandir menu lateral"
          >
            <PanelLeftOpen className="h-5 w-5" />
          </button>
          <ClientPortalLogoutButton slug={slug} className="h-11 w-11 justify-center rounded-xl px-0" />
        </div>
      )}
    </div>
  );
}

export function AccountSnapshot({
  customerName,
  client,
  primaryColor,
  completion,
  addressSummary,
  onAvatarChange,
  ordersCount,
  latestOrder,
}: {
  customerName: string;
  client: {
    email?: string | null;
    phone?: string | null;
    portal_last_login_at?: string | null;
    avatar_url?: string | null;
  };
  primaryColor: string;
  completion: number;
  addressSummary: string;
  onAvatarChange?: (file: File) => void;
  ordersCount: number;
  latestOrder: {
    number: number;
    created_at: string;
    status: string;
  } | null;
}) {
  return (
    <PremiumCard className="overflow-hidden p-6 sm:p-7">
      <div
        className="absolute inset-x-0 top-0 h-32 opacity-85"
        style={{
          background: `linear-gradient(180deg, ${hexToRgba(primaryColor, 0.14)} 0%, rgba(255,255,255,0) 100%)`,
        }}
      />
      <div className="relative">
        <div className="flex flex-col gap-7 xl:flex-row xl:items-start xl:justify-between">
          <div className="flex flex-col gap-5 sm:flex-row sm:items-center">
            <div className="relative">
              <div className="h-28 w-28 overflow-hidden rounded-[32px] border border-white/80 bg-white shadow-[0_18px_40px_rgba(15,23,42,0.12)] sm:h-36 sm:w-36">
                {client.avatar_url ? (
                  <Image
                    src={client.avatar_url}
                    alt={customerName}
                    width={144}
                    height={144}
                    className="h-full w-full object-cover"
                    unoptimized
                  />
                ) : (
                  <div
                    className="flex h-full w-full items-center justify-center text-3xl font-black text-white sm:text-4xl"
                    style={{
                      background: `linear-gradient(135deg, ${primaryColor} 0%, ${hexToRgba(primaryColor, 0.75)} 100%)`,
                    }}
                  >
                    {getInitials(customerName)}
                  </div>
                )}
              </div>
              <label
                htmlFor="client-avatar-upload"
                className="absolute -bottom-1 -right-1 inline-flex h-11 w-11 cursor-pointer items-center justify-center rounded-full border-4 border-white bg-zinc-950 text-white shadow-[0_10px_30px_rgba(15,23,42,0.18)] transition hover:scale-105"
              >
                <Camera className="h-4.5 w-4.5" />
              </label>
              <input
                id="client-avatar-upload"
                type="file"
                accept="image/*"
                className="hidden"
                onChange={(event) => {
                  const file = event.target.files?.[0];
                  if (!file || !onAvatarChange) return;
                  onAvatarChange(file);
                }}
              />
            </div>

            <div className="min-w-0">
              <div className="text-[11px] font-semibold uppercase tracking-[0.22em] text-zinc-400">
                Perfil do cliente
              </div>
              <div className="mt-2 text-3xl font-semibold tracking-[-0.06em] text-zinc-950 sm:text-[38px]">
                {customerName}
              </div>
              <div className="mt-2 text-sm text-zinc-500">{client.email || client.phone || "Cadastro ativo"}</div>
              <div className="mt-4 flex flex-wrap gap-2">
                <StatusPill label="Conta liberada" color="#059669" background="#ecfdf3" />
                <StatusPill label="Cliente comprador" color="#52525b" background="#f4f4f5" />
                <StatusPill
                  label={completion >= 80 ? "Cadastro completo" : "Faltam dados"}
                  color={completion >= 80 ? primaryColor : "#b45309"}
                  background={completion >= 80 ? hexToRgba(primaryColor, 0.08) : "#fffbeb"}
                />
              </div>
            </div>
          </div>

          <div className="flex items-start justify-between gap-4 sm:justify-start">
            <ProgressRing value={completion} primaryColor={primaryColor} />
          </div>
        </div>

        <div className="mt-6 grid gap-4 sm:grid-cols-3">
          <StatPanel label="Compras" value={String(ordersCount).padStart(2, "0")} />
          <StatPanel label="Último pedido" value={latestOrder ? `#${latestOrder.number}` : "--"} />
          <StatPanel label="Cadastro" value={`${completion}%`} />
        </div>

        <div className="mt-5 grid gap-3">
          <SnapshotRow label="Contato" value={client.email || client.phone || "Não informado"} />
          <SnapshotRow label="Entrega" value={addressSummary || "Não informado"} />
        </div>
      </div>
    </PremiumCard>
  );
}

function StatPanel({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-[26px] border border-zinc-200/70 bg-white/86 px-5 py-5">
      <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-zinc-400">{label}</div>
      <div className="mt-3 text-[30px] font-semibold tracking-[-0.06em] text-zinc-950">{value}</div>
    </div>
  );
}
