"use client";

import { useEffect, useMemo, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { AnimatePresence, motion } from "framer-motion";
import Image from "next/image";
import OrderDetailsStandalone from "@/components/client-portal/OrderDetailsStandalone";
import {
  Camera,
  FileClock,
  FolderKanban,
  HelpCircle,
  LayoutDashboard,
  MapPinned,
  MessageSquareText,
  UserCircle2,
  X,
  Heart,
} from "lucide-react";
import ClientPortalProfileForm, {
  PortalOnboardingStepper,
  type OnboardingStep,
} from "@/components/ClientPortalProfileForm";
import { PortalShell } from "@/components/client-portal/layout";
import { getReadableTextColor } from "@/lib/color-contrast";
import {
  AccountSection,
  AddressesSection,
  CatalogSection,
  FinanceSection,
  OrdersSection,
  OverviewSection,
  SettingsSection,
  SupportSection,
  FavoritesSection,
  FavoriteProduct,
  ReviewsSection,
  ReviewHistoryItem,
} from "@/components/client-portal/sections";
import {
  ClientPortalClient,
  ClientPortalOrder,
  ClientPortalPaymentReceipt,
  NavItem,
  SectionId,
  clampPage,
  formatMoney,
  getIncompleteProfileFields,
  getProfileCompletion,
  isClientProfileComplete,
} from "@/components/client-portal/shared";

type ClientPortalDashboardProps = {
  slug: string;
  storeName: string;
  logoUrl: string;
  primaryColor: string;
  client: ClientPortalClient;
  orders: ClientPortalOrder[];
  favoriteProducts?: FavoriteProduct[];
  reviews?: ReviewHistoryItem[];
  storeEmail?: string | null;
  storeWhatsapp?: string | null;
  storePhone?: string | null;
  storeAddress?: string | null;
  initialSection?: SectionId | null;
  orderDetails?: {
    status_token?: string | null;
    status_payload?: {
      profile?: { slug?: string | null } | null;
      client?: { name?: string | null } | null;
      quote?: { currency?: string | null; delivery_date?: string | null } | null;
      order?: {
        number?: number | null;
        status?: string | null;
        created_at?: string | null;
        updated_at?: string | null;
        total_amount?: number | null;
        paid_amount?: number | null;
        production_stage_label?: string | null;
      } | null;
    } | null;
    order: {
      id: string;
      number: number;
      created_at: string;
      updated_at?: string | null;
      status: string;
      total_amount: number;
      paid_amount?: number | null;
      financial_status?: string | null;
      production_stage_label?: string | null;
      share_token?: string | null;
    };
    quote?: {
      currency?: string | null;
      subtotal?: number | null;
      discount?: number | null;
      shipping?: number | null;
      total?: number | null;
      delivery_date?: string | null;
    } | null;
    items?: Array<{
      id: string;
      product_id?: string | null;
      product_name?: string | null;
      product_image_url?: string | null;
      title?: string | null;
      description?: string | null;
      quantity: number;
      unit_price: number;
      total_price: number;
      unit_type?: string | null;
      selected_options?: { options?: Array<{ attribute_name?: string | null; label?: string | null }> } | null;
    }>;
    payment_receipt?: ClientPortalPaymentReceipt | null;
  } | null;
};

export default function ClientPortalDashboard({
  slug,
  storeName,
  logoUrl,
  primaryColor,
  client,
  orders,
  favoriteProducts = [],
  reviews = [],
  storeEmail,
  storeWhatsapp,
  storePhone,
  storeAddress,
  initialSection = null,
  orderDetails = null,
}: ClientPortalDashboardProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const allowedSections: SectionId[] = ["overview", "orders", "catalog", "finance", "addresses", "account", "support", "settings", "favorites", "reviews"];
  const buildPortalUrl = (section: SectionId) => {
    const params = new URLSearchParams(searchParams.toString());
    params.set("section", section);
    if (section !== "orders") params.delete("orderId");
    if (section === "orders") params.delete("orderId");
    return `/${slug}/cliente?${params.toString()}`;
  };
  const openSection = (section: SectionId) => {
    router.push(buildPortalUrl(section));
    setSidebarOpen(false);
    setActiveSection(section);
  };
  const normalizedInitialSection = (() => {
    const raw = String(initialSection || "").trim();
    return allowedSections.includes(raw as SectionId) ? (raw as SectionId) : null;
  })();
  const [activeSection, setActiveSection] = useState<SectionId>(() => {
    if (normalizedInitialSection) return normalizedInitialSection;
    if (orderDetails) return "orders";
    return "overview";
  });
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [searchQuery, setSearchQuery] = useState("");
  const [page, setPage] = useState(1);
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [profileClient, setProfileClient] = useState<ClientPortalClient>(client);
  const [profileDraft, setProfileDraft] = useState<ClientPortalClient>(client);
  const [avatarPreview, setAvatarPreview] = useState(client.avatar_url || "");
  const [avatarModalOpen, setAvatarModalOpen] = useState(false);
  const [avatarDraftFile, setAvatarDraftFile] = useState<File | null>(null);
  const [avatarDraftUrl, setAvatarDraftUrl] = useState(client.avatar_url || "");
  const [avatarSaving, setAvatarSaving] = useState(false);
  const [avatarError, setAvatarError] = useState("");
  const [onboardingStep, setOnboardingStep] = useState<OnboardingStep>(0);
  const avatarStorageKey = `ks:client-avatar:${slug}:${client.id || "anon"}`;

  useEffect(() => {
    const section = String(searchParams.get("section") || "").trim();
    if (allowedSections.includes(section as SectionId)) {
      setActiveSection(section as SectionId);
    }
  }, [searchParams]);

  useEffect(() => {
    setProfileClient(client);
    setProfileDraft(client);
    setAvatarPreview(client.avatar_url || "");
  }, [client]);

  useEffect(() => {
    if (typeof window === "undefined") return;
    if (client.avatar_url) return;
    const cachedAvatar = window.localStorage.getItem(avatarStorageKey) || "";
    if (cachedAvatar) setAvatarPreview(cachedAvatar);
  }, [avatarStorageKey, client.avatar_url]);

  useEffect(() => {
    return () => {
      if (avatarPreview.startsWith("blob:")) {
        URL.revokeObjectURL(avatarPreview);
      }
    };
  }, [avatarPreview]);

  useEffect(() => {
    return () => {
      if (avatarDraftUrl.startsWith("blob:")) {
        URL.revokeObjectURL(avatarDraftUrl);
      }
    };
  }, [avatarDraftUrl]);

  const resolvedClient = useMemo(() => ({
    ...profileDraft,
    ...profileClient,
    avatar_url: avatarPreview || profileClient.avatar_url || client.avatar_url || "",
  }), [profileDraft, profileClient, avatarPreview, client.avatar_url]);

  const customerName = resolvedClient.company_name || resolvedClient.name || "Cliente";
  const completion = useMemo(() => getProfileCompletion(resolvedClient), [resolvedClient]);
  const incompleteFields = useMemo(() => getIncompleteProfileFields(resolvedClient), [resolvedClient]);
  const requiresProfileCompletion = useMemo(
    () => !isClientProfileComplete(resolvedClient),
    [resolvedClient]
  );
  const totalSpent = useMemo(
    /* Pedido cancelado continua na lista, mas não é dinheiro gasto. */
    () => orders.reduce((total, order) => (order.status === "canceled" ? total : total + Number(order.total_amount || 0)), 0),
    [orders]
  );
  const latestOrder = orders[0] || null;

  useEffect(() => {
    if (requiresProfileCompletion) {
      openSection("account");
      setOnboardingStep((current) => (current > 1 ? 1 : current));
    }
  }, [requiresProfileCompletion]);

  const navItems: NavItem[] = [
    {
      id: "overview",
      label: "Inicio",
      description: "Resumo das suas compras",
      icon: LayoutDashboard,
    },
    {
      id: "orders",
      label: "Minhas compras",
      description: "Acompanhe seus pedidos",
      icon: FileClock,
    },
    {
      id: "catalog",
      label: "Catálogo",
      description: "Voltar para a loja",
      icon: FolderKanban,
    },
    {
      id: "favorites",
      label: "Meus Favoritos",
      description: "Produtos que você salvou",
      icon: Heart,
    },
    {
      id: "reviews",
      label: "Avaliacoes",
      description: "Comentarios e notas enviadas",
      icon: MessageSquareText,
    },
    {
      id: "addresses",
      label: "Entrega",
      description: "Endereco e entrega",
      icon: MapPinned,
    },
    {
      id: "account",
      label: "Meus dados",
      description: "Cadastro e contato",
      icon: UserCircle2,
    },
    {
      id: "support",
      label: "Ajuda",
      description: "Atendimento e suporte",
      icon: HelpCircle,
    },
  ];

  function openAvatarModal() {
    setAvatarError("");
    setAvatarDraftFile(null);
    setAvatarDraftUrl(avatarPreview || client.avatar_url || "");
    setAvatarModalOpen(true);
  }

  function closeAvatarModal() {
    if (avatarSaving) return;
    setAvatarError("");
    setAvatarDraftFile(null);
    setAvatarDraftUrl((current) => {
      if (current.startsWith("blob:")) URL.revokeObjectURL(current);
      return avatarPreview || client.avatar_url || "";
    });
    setAvatarModalOpen(false);
  }

  function handleAvatarFileSelect(file: File) {
    const nextUrl = URL.createObjectURL(file);
    setAvatarError("");
    setAvatarDraftFile(file);
    setAvatarDraftUrl((current) => {
      if (current.startsWith("blob:")) URL.revokeObjectURL(current);
      return nextUrl;
    });
  }

  async function saveAvatar() {
    if (!avatarDraftFile) {
      setAvatarError("Selecione uma imagem antes de salvar.");
      return;
    }

    setAvatarSaving(true);
    setAvatarError("");

    try {
      const formData = new FormData();
      formData.append("slug", slug);
      formData.append("avatar", avatarDraftFile);

      const response = await fetch("/api/client-portal/avatar", {
        method: "POST",
        body: formData,
      });
      const data = (await response.json()) as { avatar_url?: string; error?: string };
      if (!response.ok || data.error) throw new Error(data.error || "Falha ao salvar foto.");

      const nextAvatar = data.avatar_url || "";
      if (nextAvatar) {
        setAvatarPreview((current) => {
          if (current.startsWith("blob:")) URL.revokeObjectURL(current);
          return nextAvatar;
        });
        if (typeof window !== "undefined") {
          window.localStorage.setItem(avatarStorageKey, nextAvatar);
        }
      }

      setAvatarModalOpen(false);
      setAvatarDraftFile(null);
      setAvatarDraftUrl((current) => {
        if (current.startsWith("blob:")) URL.revokeObjectURL(current);
        return nextAvatar || avatarPreview || client.avatar_url || "";
      });
    } catch (error) {
      setAvatarError(error instanceof Error ? error.message : "Não foi possível salvar a foto.");
    } finally {
      setAvatarSaving(false);
    }
  }

  const filteredOrders = useMemo(() => {
    const query = searchQuery.trim().toLowerCase();
    return orders.filter((order) => {
      const matchesStatus = statusFilter === "all" || order.status === statusFilter;
      const matchesSearch =
        query.length === 0 ||
        String(order.number).includes(query) ||
        formatMoney(order.total_amount).toLowerCase().includes(query) ||
        order.status.toLowerCase().includes(query);
      return matchesStatus && matchesSearch;
    });
  }, [orders, searchQuery, statusFilter]);

  // Seção "favorites" força recarregamento do portal inteiro se não estiver refletindo
  useEffect(() => {
    if (activeSection === "favorites") {
      router.refresh();
    }
  }, [activeSection, router]);

  useEffect(() => {
    const handleFavUpdate = () => {
      if (activeSection === "favorites") {
        router.refresh();
      }
    };
    window.addEventListener("ks_favorites_updated", handleFavUpdate);
    return () => window.removeEventListener("ks_favorites_updated", handleFavUpdate);
  }, [activeSection, router]);

  const pageSize = 5;
  const totalPages = Math.max(1, Math.ceil(filteredOrders.length / pageSize));
  const safePage = clampPage(page, totalPages);
  const paginatedOrders = filteredOrders.slice((safePage - 1) * pageSize, safePage * pageSize);

  return (
    <>
      <PortalShell
        slug={slug}
        storeName={storeName}
        logoUrl={logoUrl}
        primaryColor={primaryColor}
        customerName={customerName}
        client={resolvedClient}
        completion={completion}
        totalSpent={totalSpent}
        latestOrder={latestOrder}
        orders={orders}
        activeSection={activeSection}
        sidebarOpen={sidebarOpen}
        searchQuery={searchQuery}
        navItems={navItems}
        onOpenSection={(section) => openSection(section)}
        onToggleSidebar={setSidebarOpen}
        onSearchChange={(value) => {
          setSearchQuery(value);
          setPage(1);
        }}
        onAvatarClick={openAvatarModal}
        contentLayout={orderDetails ? "integrated" : "default"}
      >
        {activeSection === "overview" ? (
          <OverviewSection
            slug={slug}
            primaryColor={primaryColor}
            client={resolvedClient}
            customerName={customerName}
            orders={orders}
            completion={completion}
            totalSpent={totalSpent}
            latestOrder={latestOrder}
            onOpenSection={(section) => openSection(section)}
          />
        ) : null}

        {activeSection === "orders" ? (
          orderDetails ? (
            <OrderDetailsStandalone
              slug={slug}
              primaryColor={primaryColor}
              client={resolvedClient}
              storeWhatsapp={storeWhatsapp}
              storePhone={storePhone}
              details={orderDetails}
              onBackToOrders={() => {
                try {
                  const key = `ks_portal_return_to:${slug}`;
                  const stored = window.sessionStorage.getItem(key) || "";
                  window.sessionStorage.removeItem(key);
                  if (stored) {
                    router.push(stored);
                    return;
                  }
                } catch {
                }
                router.push(buildPortalUrl("orders"));
              }}
            />
          ) : (
            <OrdersSection
              slug={slug}
              primaryColor={primaryColor}
              orders={orders}
              filteredOrders={filteredOrders}
              paginatedOrders={paginatedOrders}
            />
          )
        ) : null}

        {activeSection === "catalog" ? (
          <CatalogSection
            slug={slug}
            storeName={storeName}
            primaryColor={primaryColor}
            onOpenSection={() => openSection("orders")}
          />
        ) : null}

        {activeSection === "favorites" ? (
          <FavoritesSection
            slug={slug}
            primaryColor={primaryColor}
            favoriteProducts={favoriteProducts}
            onOpenCatalog={() => openSection("catalog")}
            clientId={resolvedClient.id || client.id || null}
          />
        ) : null}

        {activeSection === "reviews" ? (
          <ReviewsSection
            slug={slug}
            reviews={reviews}
            onOpenCatalog={() => openSection("catalog")}
          />
        ) : null}

        {activeSection === "finance" ? (
          <FinanceSection latestOrder={latestOrder} totalSpent={totalSpent} orders={orders} />
        ) : null}

        {activeSection === "addresses" ? (
          <AddressesSection
            slug={slug}
            client={resolvedClient}
            primaryColor={primaryColor}
            completion={completion}
            onOpenSection={() => openSection("account")}
            onClientChange={(nextClient) => {
              setProfileClient(nextClient);
              setProfileDraft(nextClient);
            }}
          />
        ) : null}

        {activeSection === "account" ? (
          <AccountSection slug={slug} primaryColor={primaryColor} client={resolvedClient} />
        ) : null}

        {activeSection === "support" ? (
          <SupportSection
            onOpenOrders={() => openSection("orders")}
            onOpenAccount={() => openSection("account")}
            primaryColor={primaryColor}
            storeEmail={storeEmail}
            storeWhatsapp={storeWhatsapp}
            storePhone={storePhone}
            storeAddress={storeAddress}
          />
        ) : null}

        {activeSection === "settings" ? (
          <SettingsSection
            completion={completion}
            lastLogin={client.portal_last_login_at}
            onOpenAccount={() => openSection("account")}
          />
        ) : null}
      </PortalShell>

      <AnimatePresence>
        {avatarModalOpen ? (
          <>
            <motion.button
              type="button"
              className="fixed inset-0 z-[70] bg-[#111827]/45 backdrop-blur-sm"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={closeAvatarModal}
            />
            <motion.div
              className="fixed left-1/2 top-1/2 z-[80] w-[calc(100vw-32px)] max-w-md -translate-x-1/2 -translate-y-1/2 rounded-[32px] border border-white/80 bg-white/98 p-6 shadow-[0_30px_80px_rgba(15,23,42,0.20)]"
              initial={{ opacity: 0, y: 18, scale: 0.98 }}
              animate={{ opacity: 1, y: 0, scale: 1 }}
              exit={{ opacity: 0, y: 12, scale: 0.98 }}
              transition={{ duration: 0.18, ease: "easeOut" }}
            >
              <div className="flex items-start justify-between gap-4">
                <div>
                  <div className="text-lg font-semibold tracking-[-0.03em] text-zinc-950">Foto do perfil</div>
                  <div className="mt-1 text-sm text-zinc-500">Escolha a imagem e salve para atualizar.</div>
                </div>
                <button
                  type="button"
                  onClick={closeAvatarModal}
                  className="inline-flex h-10 w-10 items-center justify-center rounded-2xl border border-zinc-200 text-zinc-500 transition hover:border-zinc-300 hover:text-zinc-900"
                  aria-label="Fechar modal"
                >
                  <X className="h-4 w-4" />
                </button>
              </div>

              <div className="mt-6 flex flex-col items-center">
                <div className="relative h-32 w-32 overflow-hidden rounded-full border border-zinc-200 bg-zinc-100 shadow-[0_18px_40px_rgba(15,23,42,0.10)]">
                  {avatarDraftUrl ? (
                    <Image
                      src={avatarDraftUrl}
                      alt={customerName}
                      width={128}
                      height={128}
                      className="h-full w-full object-cover"
                      unoptimized
                    />
                  ) : (
                    <div
                      className="flex h-full w-full items-center justify-center text-4xl font-black text-white"
                      style={{ backgroundColor: primaryColor, color: getReadableTextColor(primaryColor) }}
                    >
                      {customerName.slice(0, 1).toUpperCase()}
                    </div>
                  )}
                </div>

                <label
                  htmlFor="client-avatar-modal-input"
                  className="mt-4 inline-flex h-11 cursor-pointer items-center gap-2 rounded-2xl border border-zinc-200 bg-white px-4 text-sm font-semibold text-zinc-700 transition hover:border-zinc-300 hover:text-zinc-950"
                >
                  <Camera className="h-4 w-4" />
                  Escolher imagem
                </label>
                <input
                  id="client-avatar-modal-input"
                  type="file"
                  accept="image/*"
                  className="hidden"
                  onChange={(event) => {
                    const file = event.target.files?.[0];
                    if (!file) return;
                    handleAvatarFileSelect(file);
                    event.currentTarget.value = "";
                  }}
                />

                {avatarError ? <div className="mt-4 text-center text-sm font-medium text-red-600">{avatarError}</div> : null}
              </div>

              <div className="mt-6 grid grid-cols-2 gap-3">
                <button
                  type="button"
                  onClick={closeAvatarModal}
                  className="inline-flex h-12 items-center justify-center rounded-2xl border border-zinc-200 text-sm font-semibold text-zinc-700 transition hover:border-zinc-300 hover:text-zinc-950 disabled:opacity-60"
                  disabled={avatarSaving}
                >
                  Cancelar
                </button>
                <button
                  type="button"
                  onClick={saveAvatar}
                  className="inline-flex h-12 items-center justify-center rounded-2xl text-sm font-semibold text-white transition hover:opacity-90 disabled:opacity-60"
                  style={{ backgroundColor: primaryColor, color: getReadableTextColor(primaryColor) }}
                  disabled={avatarSaving}
                >
                  {avatarSaving ? "Salvando..." : "Salvar foto"}
                </button>
              </div>
            </motion.div>
          </>
        ) : null}
      </AnimatePresence>

      <AnimatePresence>
        {requiresProfileCompletion ? (
          <>
            <motion.div
              className="fixed inset-0 z-[90] bg-[#111827]/55 backdrop-blur-sm"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
            />
            <motion.div
              className="fixed inset-x-3 top-1/2 z-[100] mx-auto max-h-[86dvh] w-full max-w-[860px] -translate-y-1/2 overflow-hidden rounded-[28px] border border-white/80 bg-white shadow-[0_28px_80px_rgba(15,23,42,0.20)] sm:inset-x-6 sm:rounded-[32px]"
              initial={{ opacity: 0, y: 24, scale: 0.98 }}
              animate={{ opacity: 1, y: 0, scale: 1 }}
              exit={{ opacity: 0, y: 12, scale: 0.98 }}
              transition={{ duration: 0.2, ease: "easeOut" }}
            >
              <div className="border-b border-zinc-200/80 bg-white px-4 py-4 sm:px-6">
                <PortalOnboardingStepper
                  step={onboardingStep}
                  primaryColor={primaryColor}
                  onStepChange={(nextStep) => {
                    if (nextStep < onboardingStep) {
                      setOnboardingStep(nextStep);
                    }
                  }}
                />
              </div>
              <div className="border-b border-zinc-200/80 px-4 py-4 sm:px-6">
                <div className="text-[11px] font-semibold uppercase tracking-[0.2em] text-zinc-400">
                  Complete seu cadastro
                </div>
                <h2 className="mt-1.5 text-xl font-semibold tracking-[-0.04em] text-zinc-950 sm:text-[26px]">
                  Preencha seus dados para liberar o portal
                </h2>
                <p className="mt-1.5 max-w-2xl text-sm leading-6 text-zinc-500">
                  Antes de acompanhar pedidos e entregas, precisamos finalizar suas informações.
                </p>
              </div>
              <div className="max-h-[calc(86dvh-220px)] overflow-y-auto px-3 py-3 sm:px-5 sm:py-4">
                <ClientPortalProfileForm
                  slug={slug}
                  initial={resolvedClient}
                  primaryColor={primaryColor}
                  requireComplete
                  submitLabel="Salvar e liberar portal"
                  successMessage="Cadastro concluído. Portal liberado."
                  step={onboardingStep}
                  onStepChange={setOnboardingStep}
                  showStepper={false}
                  onSaved={(nextProfile) => {
                    setProfileDraft((current) => ({ ...current, ...nextProfile }));
                    setProfileClient((current) => ({ ...current, ...nextProfile }));
                  }}
                  onDraftChange={(draft) => {
                    setProfileDraft((current) => {
                      const next = { ...current, ...draft };
                      // Avoid setting state if nothing actually changed
                      if (JSON.stringify(current) === JSON.stringify(next)) return current;
                      return next;
                    });
                  }}
                />
              </div>
            </motion.div>
          </>
        ) : null}
      </AnimatePresence>
    </>
  );
}
