"use client";

import { useState, useEffect, useRef, useCallback } from "react";
import { getSupabaseClient } from "@/lib/supabase";
import { getCompanyContext, shouldUseEmployeeUi } from "@/lib/company-context";
import type { User } from "@supabase/supabase-js";
import { LogOut, CreditCard, Sparkles, ChevronUp, Lock, User as UserIcon } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import ImageUpload from "@/components/image-upload";
import { createPortal } from "react-dom";
import Image from "next/image";

const passthroughLoader = ({ src }: { src: string }) => src;

type Profile = {
  store_name: string | null;
  catalog_name: string | null;
  logo_url: string | null;
  catalog_logo_url: string | null;
};

type Plan = {
  name: string;
  days_remaining: number;
  progress: number;
  active: boolean;
};

export default function UserNav({ mobile = false }: { mobile?: boolean }) {
  const router = useRouter();
  const [isOpen, setIsOpen] = useState(false);
  const [user, setUser] = useState<User | null>(null);
  const [profile, setProfile] = useState<Profile | null>(null);
  const [plan, setPlan] = useState<Plan | null>(null);
  const [loading, setLoading] = useState(true);
  const menuRef = useRef<HTMLDivElement>(null);
  const triggerRef = useRef<HTMLButtonElement>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const [dropdownPosition, setDropdownPosition] = useState<{ top: number; left: number } | null>(null);

  const updateDropdownPosition = useCallback(() => {
    if (!triggerRef.current || typeof window === "undefined") return;
    const rect = triggerRef.current.getBoundingClientRect();
    const menuWidth = 288;
    const menuHeight = dropdownRef.current?.getBoundingClientRect().height ?? 340;
    const rawLeft = mobile ? rect.right - menuWidth : rect.left;
    const left = Math.max(12, Math.min(rawLeft, window.innerWidth - menuWidth - 12));
    let top = rect.bottom + 8;
    if (top + menuHeight > window.innerHeight - 12) {
      top = Math.max(12, rect.top - menuHeight - 8);
    }
    setDropdownPosition({ top, left });
  }, [mobile]);

  useEffect(() => {
    fetchData();

    function handleClickOutside(event: MouseEvent) {
      const target = event.target as Node;
      const clickedTrigger = Boolean(menuRef.current?.contains(target));
      const clickedDropdown = Boolean(dropdownRef.current?.contains(target));
      if (!clickedTrigger && !clickedDropdown) {
        setIsOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  useEffect(() => {
    if (!isOpen) return;
    updateDropdownPosition();
    const handleViewportChange = () => updateDropdownPosition();
    window.addEventListener("resize", handleViewportChange);
    window.addEventListener("scroll", handleViewportChange, true);
    return () => {
      window.removeEventListener("resize", handleViewportChange);
      window.removeEventListener("scroll", handleViewportChange, true);
    };
  }, [isOpen, updateDropdownPosition]);

  async function fetchData() {
    try {
      const supabase = getSupabaseClient();
      const { data: { user } } = await supabase.auth.getUser();
      
      if (user) {
        setUser(user);
        
        // Fetch Profile
        const ctx = await getCompanyContext(supabase, user);
        const profileCandidates = Array.from(new Set([ctx.ownerId, user.id].filter(Boolean))) as string[];
        const profileLookup = profileCandidates.length > 0 ? profileCandidates : [user.id];
        const { data: profileData } = await supabase
          .from("profiles")
          .select("id,store_name,catalog_name,logo_url,catalog_logo_url")
          .in("id", profileLookup);
        const profiles = (profileData ?? []) as Profile[];
        const resolvedProfile =
          profiles.find((entry) => entry.logo_url || entry.catalog_logo_url) ||
          profiles.find((entry) => entry.catalog_name || entry.store_name) ||
          profiles[0] ||
          null;
        setProfile(resolvedProfile);

        // Fetch Plan
        const { data: planData } = await supabase
          .from('users_app') 
          .select('plan, expires_at, status')
          .eq('email', user.email) // Usando email para garantir match se o ID for diferente
          .maybeSingle();

        if (planData) {
           // Calcular dias restantes
           let daysRemaining = 0;
           let progress = 0;
           
           if (planData.expires_at) {
             const endDate = new Date(planData.expires_at);
             const now = new Date();
             const totalTime = 30 * 24 * 60 * 60 * 1000; // Assumindo ciclo de 30 dias para cálculo de barra
             const diffTime = endDate.getTime() - now.getTime();
             daysRemaining = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
             progress = Math.max(0, Math.min(100, (diffTime / totalTime) * 100));
           }

           setPlan({
             name: planData.plan || "Plano Ativo",
             days_remaining: daysRemaining > 0 ? daysRemaining : 0,
             progress: progress,
             active: planData.status === 'active'
           });
        } else {
          // Fallback se não encontrar plano
          setPlan({
            name: "Plano Gratuito",
            days_remaining: 0,
            progress: 0,
            active: false
          });
        }
      }
    } catch (error) {
      console.error("Erro ao carregar dados do usuário:", error);
    } finally {
      setLoading(false);
    }
  }

  const handleLogout = async () => {
    const supabase = getSupabaseClient();
    await supabase.auth.signOut();
    router.refresh();
    router.push('/');
  };

  if (loading) {
    return <div className="w-10 h-10 rounded-full bg-zinc-100 animate-pulse" />;
  }

  const logoUrl = profile?.logo_url || profile?.catalog_logo_url || "";
  const storeName = profile?.catalog_name || profile?.store_name;

  return (
    <div className="relative" ref={menuRef}>
      <button
        ref={triggerRef}
        onClick={(event) => {
          const rect = (event.currentTarget as HTMLButtonElement).getBoundingClientRect();
          setIsOpen((prev) => {
            const next = !prev;
            if (next) {
              const menuWidth = 288;
              const menuHeight = dropdownRef.current?.getBoundingClientRect().height ?? 340;
              const rawLeft = mobile ? rect.right - menuWidth : rect.left;
              const left = Math.max(12, Math.min(rawLeft, window.innerWidth - menuWidth - 12));
              let top = rect.bottom + 8;
              if (top + menuHeight > window.innerHeight - 12) {
                top = Math.max(12, rect.top - menuHeight - 8);
              }
              setDropdownPosition({ top, left });
              requestAnimationFrame(() => {
                updateDropdownPosition();
              });
            }
            return next;
          });
        }}
        className="ks-usernav-trigger"
      >
        <div className="w-10 h-10 rounded-full bg-white/15 p-[3px] flex-shrink-0">
          <div className="w-full h-full rounded-full bg-white flex items-center justify-center overflow-hidden">
            {logoUrl ? (
              <Image
                src={logoUrl}
                alt="Logo"
                width={36}
                height={36}
                sizes="36px"
                className="w-full h-full object-cover"
                loader={passthroughLoader}
                unoptimized
              />
            ) : (
              <span className="text-sm font-extrabold text-[var(--ks-brand-700)]">
                {storeName?.[0]?.toUpperCase() || user?.email?.[0]?.toUpperCase()}
              </span>
            )}
          </div>
        </div>
        {/* O nome só some no modo compacto (`mobile`), nunca pela largura da tela:
            no menu do celular a pílula ficava larga e só com a bolinha dentro. */}
        {!mobile && (
          <div className="flex flex-col items-start text-sm overflow-hidden">
             <span className="font-bold text-white max-w-[120px] truncate block">
               {storeName || "Minha Loja"}
             </span>
             <span className="text-[10px] uppercase tracking-wider font-bold text-white/55 block">Gerenciar</span>
          </div>
        )}
        {!mobile && <ChevronUp size={16} className="text-white/55 ml-auto" />}
      </button>

      {typeof document !== "undefined"
        ? createPortal(
            <AnimatePresence>
              {isOpen && dropdownPosition ? (
                <motion.div
                  ref={dropdownRef}
                  initial={{ opacity: 0, y: 6 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: 6 }}
                  transition={{ duration: 0.08 }}
                  className="fixed w-80 bg-[var(--ks-color-bg-elevated)] rounded-[var(--ks-radius-lg)] shadow-[var(--ks-shadow-overlay)] overflow-hidden z-[9999]"
                  style={{ top: dropdownPosition.top, left: dropdownPosition.left }}
                >
            {/* Header do Menu */}
            <div className="p-4 bg-[var(--ks-brand-50)] border-b border-[var(--ks-color-border-subtle)]">
              <div className="flex items-center gap-3 mb-3">
                <div className="w-10 h-10 rounded-full bg-[var(--ks-color-primary-light)] flex items-center justify-center text-[var(--ks-color-primary)] font-bold flex-shrink-0 overflow-hidden">
                  {logoUrl ? (
                    <Image
                      src={logoUrl}
                      alt="Logo"
                      width={40}
                      height={40}
                      sizes="40px"
                      className="w-full h-full object-cover"
                      loader={passthroughLoader}
                      unoptimized
                    />
                  ) : (
                    storeName?.[0]?.toUpperCase() || "L"
                  )}
                </div>
                <div className="flex-1 overflow-hidden">
                  <p className="font-medium text-zinc-900 truncate">{storeName || "Minha Loja"}</p>
                  <p className="text-xs text-zinc-500 truncate">{user?.email}</p>
                </div>
              </div>
              
              {/* Seção do Plano */}
              <div className="bg-white rounded-xl border border-[rgba(68,37,167,0.16)] p-3 shadow-[0_10px_24px_rgba(68,37,167,0.08)]">
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center gap-1.5">
                    <Sparkles size={14} className="text-amber-500 fill-amber-500" />
                    <span className="text-xs font-semibold text-zinc-700">{plan?.name}</span>
                  </div>
                  {plan?.active ? (
                    <span className="text-[10px] font-medium bg-[var(--ks-color-success-light)] text-[var(--ks-color-success)] px-2 py-0.5 rounded-full">Ativo</span>
                  ) : (
                    <span className="text-[10px] font-medium bg-zinc-100 text-zinc-500 px-2 py-0.5 rounded-full">Inativo</span>
                  )}
                </div>
                
                {plan?.active && (
                  <div className="space-y-1.5 mb-3">
                    <div className="flex justify-between text-[10px] text-zinc-500">
                      <span>Tempo restante</span>
                      <span>{plan?.days_remaining} dias</span>
                    </div>
                    <div className="h-1.5 w-full bg-zinc-100 rounded-full overflow-hidden">
                      <div 
                        className="h-full bg-gradient-to-r from-[var(--ks-color-primary)] to-[var(--ks-color-primary-light)] rounded-full"
                        style={{ width: `${plan?.progress || 0}%` }}
                      />
                    </div>
                  </div>
                )}

                <button
                  type="button"
                  onClick={() => router.push("/dashboard/assinatura")}
                  className="w-full py-1.5 text-xs font-medium text-white bg-zinc-900 hover:bg-zinc-800 rounded-lg transition-colors flex items-center justify-center gap-2"
                >
                  <CreditCard size={12} />
                  {plan?.active ? "Gerenciar Assinatura" : "Fazer Upgrade"}
                </button>
              </div>
            </div>

            {/* Menu Options */}
            <div className="p-2.5 space-y-1.5 bg-gray-50 border-t border-gray-100">
              <Link
                href="/dashboard/settings/password"
                className="flex items-center gap-3 w-full px-3 py-2.5 text-sm text-[var(--ks-color-text-primary)] hover:bg-[rgba(68,37,167,0.08)] rounded-xl transition-colors"
              >
                <Lock size={16} />
                Alterar senha
              </Link>
              <button
                onClick={handleLogout}
                className="flex items-center gap-3 w-full px-3 py-2.5 text-sm text-red-600 hover:bg-red-50 rounded-xl transition-colors"
              >
                <LogOut size={16} />
                Sair
              </button>
            </div>
                </motion.div>
              ) : null}
            </AnimatePresence>,
            document.body
          )
        : null}
    </div>
  );
}

type EmployeeProfile = {
  full_name: string | null;
  avatar_url: string | null;
  phone: string | null;
};

export function EmployeeNav({ mobile = false }: { mobile?: boolean }) {
  const router = useRouter();
  const [isOpen, setIsOpen] = useState(false);
  const [isProfileOpen, setIsProfileOpen] = useState(false);
  const [user, setUser] = useState<User | null>(null);
  const [isEmployee, setIsEmployee] = useState(false);
  const [fullName, setFullName] = useState("");
  const [phone, setPhone] = useState("");
  const [avatarUrl, setAvatarUrl] = useState("");
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [errorText, setErrorText] = useState<string | null>(null);
  const menuRef = useRef<HTMLDivElement>(null);
  const triggerRef = useRef<HTMLButtonElement>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const [dropdownPosition, setDropdownPosition] = useState<{ top: number; left: number } | null>(null);

  const updateDropdownPosition = useCallback(() => {
    if (!triggerRef.current || typeof window === "undefined") return;
    const rect = triggerRef.current.getBoundingClientRect();
    const menuWidth = 288;
    const menuHeight = dropdownRef.current?.getBoundingClientRect().height ?? 260;
    const rawLeft = rect.right - menuWidth;
    const left = Math.max(12, Math.min(rawLeft, window.innerWidth - menuWidth - 12));
    let top = rect.bottom + 8;
    if (top + menuHeight > window.innerHeight - 12) {
      top = Math.max(12, rect.top - menuHeight - 8);
    }
    setDropdownPosition({ top, left });
  }, []);

  useEffect(() => {
    load();

    function handleClickOutside(event: MouseEvent) {
      const target = event.target as Node;
      const clickedTrigger = Boolean(menuRef.current?.contains(target));
      const clickedDropdown = Boolean(dropdownRef.current?.contains(target));
      if (!clickedTrigger && !clickedDropdown) {
        setIsOpen(false);
      }
    }

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  useEffect(() => {
    if (!isOpen) return;
    updateDropdownPosition();
    const handleViewportChange = () => updateDropdownPosition();
    window.addEventListener("resize", handleViewportChange);
    window.addEventListener("scroll", handleViewportChange, true);
    return () => {
      window.removeEventListener("resize", handleViewportChange);
      window.removeEventListener("scroll", handleViewportChange, true);
    };
  }, [isOpen, updateDropdownPosition]);

  async function load() {
    try {
      const supabase = getSupabaseClient();
      const {
        data: { user },
      } = await supabase.auth.getUser();
      setUser(user ?? null);

      if (!user) return;

      const ctx = await getCompanyContext(supabase, user);
      const employee = shouldUseEmployeeUi(ctx, user.id);
      setIsEmployee(employee);
      if (!employee) return;

      const { data, error } = await supabase
        .from("employee_profiles")
        .select("full_name,avatar_url,phone")
        .eq("user_id", user.id)
        .maybeSingle();

      if (error) {
        return;
      }

      const nextProfile = (data ?? null) as EmployeeProfile | null;
      setFullName(nextProfile?.full_name ?? "");
      setPhone(nextProfile?.phone ?? "");
      setAvatarUrl(nextProfile?.avatar_url ?? "");
    } finally {
      setLoading(false);
    }
  }

  const handleLogout = async () => {
    const supabase = getSupabaseClient();
    await supabase.auth.signOut();
    router.refresh();
    router.push("/");
  };

  async function handleSaveProfile() {
    if (!user) return;
    setSaving(true);
    setErrorText(null);
    try {
      const supabase = getSupabaseClient();
      const payload = {
        user_id: user.id,
        full_name: fullName.trim() || null,
        phone: phone.trim() || null,
        avatar_url: avatarUrl.trim() || null,
      };

      const { error } = await supabase.from("employee_profiles").upsert(payload, { onConflict: "user_id" });
      if (error) {
        setErrorText("Não foi possível salvar seu perfil.");
        return;
      }

      setIsProfileOpen(false);
      router.refresh();
    } finally {
      setSaving(false);
    }
  }

  if (loading || !isEmployee) {
    return null;
  }

  const initial = (fullName || user?.email || "?").trim()[0]?.toUpperCase() || "?";
  const profileModalNode =
    isProfileOpen && typeof document !== "undefined"
      ? createPortal(
          <AnimatePresence>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="fixed inset-0 z-[120] flex items-start justify-center bg-black/40 backdrop-blur-sm px-4 py-10 overflow-y-auto"
              onClick={() => (saving ? null : setIsProfileOpen(false))}
            >
              <motion.div
                initial={{ opacity: 0, y: 10, scale: 0.98 }}
                animate={{ opacity: 1, y: 0, scale: 1 }}
                exit={{ opacity: 0, y: 10, scale: 0.98 }}
                transition={{ duration: 0.12 }}
                className="w-full max-w-xl max-h-[calc(100vh-5rem)] bg-[var(--ks-color-bg-elevated)] rounded-[var(--ks-radius-lg)] shadow-[var(--ks-shadow-soft)] overflow-hidden border border-[var(--ks-color-border-subtle)] flex flex-col"
                onClick={(e) => e.stopPropagation()}
              >
                <div className="p-4 border-b border-[var(--ks-color-border-subtle)]">
                  <div className="text-sm font-semibold text-[var(--ks-color-brand-dark)]">Meu perfil</div>
                  <div className="text-xs text-[var(--ks-color-text-muted)]">Preencha seus dados básicos.</div>
                </div>

                <div className="p-5 space-y-4 overflow-y-auto">
                  <div className="space-y-2">
                    <span className="block text-sm font-medium text-[var(--ks-color-text-muted)]">Foto</span>
                    <ImageUpload
                      bucket="products"
                      folder={user ? `employee-avatars/${user.id}` : "employee-avatars"}
                      value={avatarUrl}
                      onChange={setAvatarUrl}
                      disabled={saving}
                      className="items-start"
                    />
                  </div>

                  <Input
                    id="employee-full-name"
                    label="Nome"
                    value={fullName}
                    onChange={(e) => setFullName(e.target.value)}
                    placeholder="Seu nome"
                    disabled={saving}
                  />

                  <Input
                    id="employee-phone"
                    label="Telefone"
                    value={phone}
                    onChange={(e) => setPhone(e.target.value)}
                    placeholder="(00) 90000-0000"
                    disabled={saving}
                  />

                  {errorText ? (
                    <div className="p-3 rounded-xl border border-red-200 bg-red-50 text-sm text-red-700">
                      {errorText}
                    </div>
                  ) : null}

                  <div className="flex gap-3 pt-2">
                    <Button
                      type="button"
                      variant="secondary"
                      onClick={() => setIsProfileOpen(false)}
                      disabled={saving}
                      className="flex-1"
                    >
                      Cancelar
                    </Button>
                    <Button type="button" onClick={handleSaveProfile} disabled={saving} className="flex-1">
                      Salvar
                    </Button>
                  </div>
                </div>
              </motion.div>
            </motion.div>
          </AnimatePresence>,
          document.body
        )
      : null;

  return (
    <div className="relative" ref={menuRef}>
      <button
        ref={triggerRef}
        type="button"
        onClick={(event) => {
          const trigger = event.currentTarget as HTMLButtonElement;
          setIsOpen((prev) => {
            const next = !prev;
            if (next) {
              const rect = trigger.getBoundingClientRect();
              const menuWidth = 288;
              const menuHeight = dropdownRef.current?.getBoundingClientRect().height ?? 260;
              const rawLeft = rect.right - menuWidth;
              const left = Math.max(12, Math.min(rawLeft, window.innerWidth - menuWidth - 12));
              let top = rect.bottom + 8;
              if (top + menuHeight > window.innerHeight - 12) {
                top = Math.max(12, rect.top - menuHeight - 8);
              }
              setDropdownPosition({ top, left });
              requestAnimationFrame(() => {
                updateDropdownPosition();
              });
            }
            return next;
          });
        }}
        className={[
          "flex items-center gap-3 rounded-2xl transition-all focus:outline-none bg-white border border-gray-100 hover:bg-gray-50 hover:border-gray-200 text-gray-900",
          mobile ? "p-1.5" : "px-2.5 py-1.5",
        ].join(" ")}
      >
        <div className="w-9 h-9 rounded-xl bg-gray-100 p-0.5 flex-shrink-0">
          <div className="w-full h-full rounded-[10px] bg-white flex items-center justify-center overflow-hidden border border-gray-100">
            {avatarUrl ? (
              <Image
                src={avatarUrl}
                alt="Foto"
                width={36}
                height={36}
                sizes="36px"
                className="w-full h-full object-cover"
                loader={passthroughLoader}
                unoptimized
              />
            ) : (
              <span className="text-sm font-bold text-gray-600">{initial}</span>
            )}
          </div>
        </div>

        {!mobile ? (
          <div className="flex flex-col items-start text-sm overflow-hidden">
            <span className="font-semibold text-gray-900 max-w-[160px] truncate block">
              {fullName || user?.email}
            </span>
            <span className="text-[10px] uppercase tracking-wider font-bold text-gray-400 block">Meu perfil</span>
          </div>
        ) : null}

        {!mobile ? <ChevronUp size={16} className="text-gray-400 ml-auto" /> : null}
      </button>

      {typeof document !== "undefined"
        ? createPortal(
            <AnimatePresence>
              {isOpen && dropdownPosition ? (
                <motion.div
                  ref={dropdownRef}
                  initial={{ opacity: 0, y: 6 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: 6 }}
                  transition={{ duration: 0.08 }}
                  className="fixed w-80 bg-[var(--ks-color-bg-elevated)] rounded-[var(--ks-radius-lg)] shadow-[var(--ks-shadow-overlay)] overflow-hidden z-[9999]"
                  style={{ top: dropdownPosition.top, left: dropdownPosition.left }}
                >
            <div className="p-4 bg-[var(--ks-brand-50)] border-b border-[var(--ks-color-border-subtle)]">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-full bg-[var(--ks-color-primary-soft)] flex items-center justify-center text-[var(--ks-color-primary-strong)] font-bold flex-shrink-0 overflow-hidden">
                  {avatarUrl ? (
                    <Image
                      src={avatarUrl}
                      alt="Foto"
                      width={40}
                      height={40}
                      sizes="40px"
                      className="w-full h-full object-cover"
                      loader={passthroughLoader}
                      unoptimized
                    />
                  ) : (
                    initial
                  )}
                </div>
                <div className="flex-1 overflow-hidden">
                  <p className="font-medium text-zinc-900 truncate">{fullName || "Funcionário"}</p>
                  <p className="text-xs text-zinc-500 truncate">{user?.email}</p>
                </div>
              </div>
            </div>

            <div className="p-2.5 space-y-1.5 bg-gray-50 border-t border-gray-100">
              <button
                type="button"
                onClick={() => {
                  setIsOpen(false);
                  setIsProfileOpen(true);
                }}
                className="flex items-center gap-3 w-full px-3 py-2.5 text-sm text-[var(--ks-color-text-primary)] hover:bg-[rgba(68,37,167,0.08)] rounded-xl transition-colors"
              >
                <UserIcon size={16} />
                Meu perfil
              </button>

              <button
                type="button"
                onClick={handleLogout}
                className="flex items-center gap-3 w-full px-3 py-2.5 text-sm text-red-600 hover:bg-red-50 rounded-xl transition-colors"
              >
                <LogOut size={16} />
                Sair
              </button>
            </div>
                </motion.div>
              ) : null}
            </AnimatePresence>,
            document.body
          )
        : null}
      {profileModalNode}
    </div>
  );
}
