"use client";

import { useState, useEffect } from "react";
import { getSupabaseClient } from "@/lib/supabase";
import { Plus, GripVertical, Trash2, Pencil, Image as ImageIcon, Check, Settings, Camera, X, Upload, ChevronRight, ShoppingCart, MoreVertical, Search, Eye, EyeOff } from "lucide-react";
import { DragDropContext, Droppable, Draggable, DropResult } from "@hello-pangea/dnd";
import Image from "next/image";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { usePermissoes } from "@/lib/permissoes-do-usuario";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { toast } from "sonner";
import ImageUpload from "@/components/image-upload";
import { PageHeader } from "@/components/ui/page-header";
import { AnimatePresence, motion } from "framer-motion";

interface StoryItem {
  id: string;
  group_id: string;
  product_id: string | null;
  image_url: string;
  position: number;
}

interface StoryGroup {
  id: string;
  title: string;
  thumbnail_url: string | null;
  active: boolean;
  position: number;
  items?: StoryItem[];
}

export default function StoriesClient({ initialGroups, products, profile }: { initialGroups: StoryGroup[], products: any[], profile: any }) {
  const { pode } = usePermissoes();
  const podeMexerNoCatalogo = pode("catalog.stories.write");

  const [groups, setGroups] = useState<StoryGroup[]>(initialGroups);
  const [loading, setLoading] = useState(false);
  const [isGroupModalOpen, setIsGroupModalOpen] = useState(false);
  const [editingGroup, setEditingGroup] = useState<StoryGroup | null>(null);
  const [globalStoriesEnabled, setGlobalStoriesEnabled] = useState(profile?.catalog_stories_enabled ?? true);
  const [groupTitle, setGroupTitle] = useState("");
  const [groupThumbnail, setGroupThumbnail] = useState("");
  const [groupActive, setGroupActive] = useState(true);

  // States for items management modal
  const [isViewerOpen, setIsViewerOpen] = useState(false);
  const [activeGroupForItems, setActiveGroupForItems] = useState<StoryGroup | null>(null);
  const [viewerItemIndex, setViewerItemIndex] = useState(0);
  const [viewerProgress, setViewerProgress] = useState(0);
  const [isPaused, setIsPaused] = useState(false);
  
  // States for Insta-like Camera UI
  const [isCameraUiOpen, setIsCameraUiOpen] = useState(false);
  const [cameraImage, setCameraImage] = useState("");
  const [cameraProductId, setCameraProductId] = useState<string>("none");
  const [isProductSelectorOpen, setIsProductSelectorOpen] = useState(false);
  const [productSearchQuery, setProductSearchQuery] = useState("");

  const supabase = getSupabaseClient();

  const handleDragEnd = async (result: DropResult) => {
    if (!result.destination) return;
    
    const items = Array.from(groups);
    const [reorderedItem] = items.splice(result.source.index, 1);
    items.splice(result.destination.index, 0, reorderedItem);

    setGroups(items);

    try {
      const updates = items.map((g, index) => ({
        id: g.id,
        position: index
      }));

      await Promise.all(
        updates.map(u => 
          supabase.from("catalog_story_groups").update({ position: u.position }).eq("id", u.id)
        )
      );
    } catch (error) {
      toast.error("Erro ao reordenar grupos");
    }
  };

  const handleSaveGroup = async () => {
    if (!groupTitle) {
      toast.error("O título é obrigatório");
      return;
    }

    setLoading(true);
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) throw new Error("Não autenticado");

      /* O destaque e da loja (perfil do dono), nao de quem esta logado: um
         funcionario gravava no proprio id e a loja, que le pelo dono, nao via. */
      const groupData = {
        title: groupTitle,
        thumbnail_url: groupThumbnail,
        active: groupActive,
        user_id: String(profile?.id || user.id)
      };

      if (editingGroup) {
        const { data, error } = await supabase
          .from("catalog_story_groups")
          .update(groupData)
          .eq("id", editingGroup.id)
          .select("*, items:catalog_story_items(*)")
          .single();

        if (error) throw error;
        setGroups(groups.map(g => g.id === editingGroup.id ? data : g));
        toast.success("Grupo atualizado!");
      } else {
        const { data, error } = await supabase
          .from("catalog_story_groups")
          .insert({ ...groupData, position: groups.length })
          .select("*, items:catalog_story_items(*)")
          .single();

        if (error) throw error;
        setGroups([...groups, data]);
        toast.success("Grupo criado!");
      }
      setIsGroupModalOpen(false);
    } catch (error) {
      console.error(error);
      toast.error("Erro ao salvar grupo");
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteGroup = async (id: string) => {
    if (!confirm("Tem certeza que deseja excluir este destaque inteiro? Todas as fotos dentro dele serão perdidas!")) return;
    
    try {
      // Find the group to delete
      const groupToDelete = groups.find(g => g.id === id);
      if (!groupToDelete) return;

      // 1. Delete all images from Storage
      const filesToDelete = [];
      
      // Add thumbnail if exists
      if (groupToDelete.thumbnail_url) {
        const thumbUrlObj = new URL(groupToDelete.thumbnail_url);
        const thumbPath = thumbUrlObj.pathname.split('/object/public/products/')[1];
        if (thumbPath) filesToDelete.push(thumbPath);
      }

      // Add all story items images
      if (groupToDelete.items && groupToDelete.items.length > 0) {
        for (const item of groupToDelete.items) {
          const itemUrlObj = new URL(item.image_url);
          const itemPath = itemUrlObj.pathname.split('/object/public/products/')[1];
          if (itemPath) filesToDelete.push(itemPath);
        }
      }

      // Perform Storage deletion if there are files
      if (filesToDelete.length > 0) {
        const { error: storageError } = await supabase.storage
          .from('products')
          .remove(filesToDelete);
        
        if (storageError) {
          console.error("Erro ao deletar arquivos do storage:", storageError);
          // Continuing anyway to ensure database record is deleted
        }
      }

      // 2. Delete from Database
      const { error } = await supabase.from("catalog_story_groups").delete().eq("id", id);
      if (error) throw error;
      
      setGroups(groups.filter(g => g.id !== id));
      setIsGroupModalOpen(false); // Close modal if it was open
      toast.success("Destaque excluído com sucesso!");
    } catch (error) {
      toast.error("Erro ao excluir destaque");
    }
  };

  const openNewGroupModal = () => {
    setEditingGroup(null);
    setGroupTitle("");
    setGroupThumbnail("");
    setGroupActive(true);
    setIsGroupModalOpen(true);
  };

  const openEditGroupModal = (group: StoryGroup) => {
    setEditingGroup(group);
    setGroupTitle(group.title);
    setGroupThumbnail(group.thumbnail_url || "");
    setGroupActive(group.active);
    setIsGroupModalOpen(true);
  };

  const openViewer = (group: StoryGroup) => {
    setActiveGroupForItems(group);
    setViewerItemIndex(0);
    setViewerProgress(0);
    setIsPaused(false);
    
    // Se o grupo não tem fotos, abre a câmera direto
    if (!group.items || group.items.length === 0) {
      openCameraUi();
    } else {
      setIsViewerOpen(true);
    }
  };

  const openCameraUi = () => {
    setCameraImage("");
    setCameraProductId("none");
    setIsProductSelectorOpen(false);
    setIsViewerOpen(false);
    setIsCameraUiOpen(true);
  };

  const closeViewer = () => {
    setIsViewerOpen(false);
    setActiveGroupForItems(null);
    setViewerItemIndex(0);
    setViewerProgress(0);
  };

  const handleViewerNext = () => {
    if (!activeGroupForItems || !activeGroupForItems.items) return;
    if (viewerItemIndex < activeGroupForItems.items.length - 1) {
      setViewerItemIndex(prev => prev + 1);
      setViewerProgress(0);
    } else {
      closeViewer();
    }
  };

  const handleViewerPrev = () => {
    if (!activeGroupForItems || !activeGroupForItems.items) return;
    if (viewerItemIndex > 0) {
      setViewerItemIndex(prev => prev - 1);
      setViewerProgress(0);
    }
  };

  // Timer do Visualizador
  useEffect(() => {
    if (!isViewerOpen || !activeGroupForItems || !activeGroupForItems.items?.length || isPaused) {
      return;
    }

    const duration = 5000;
    const interval = 50;
    const step = (interval / duration) * 100;

    const timer = setInterval(() => {
      setViewerProgress(prev => {
        if (prev >= 100) {
          clearInterval(timer);
          handleViewerNext();
          return 0;
        }
        return prev + step;
      });
    }, interval);

    return () => clearInterval(timer);
  }, [isViewerOpen, viewerItemIndex, activeGroupForItems, isPaused]);

  const toggleGlobalStories = async (checked: boolean) => {
    try {
      const { error } = await supabase
        .from('profiles')
        .update({ catalog_stories_enabled: checked })
        .eq('id', profile.id);
        
      if (error) throw error;
      setGlobalStoriesEnabled(checked);
      toast.success(checked ? "Stories ativados na loja!" : "Stories ocultos na loja!");
    } catch (error) {
      console.error(error);
      toast.error("Erro ao atualizar configuração");
    }
  };

  const filteredProducts = products.filter(p => 
    p.name.toLowerCase().includes(productSearchQuery.toLowerCase())
  );

  const handleAddItem = async () => {
    if (!activeGroupForItems || !cameraImage) {
      toast.error("Adicione uma imagem para o story");
      return;
    }

    setLoading(true);
    try {
      const position = activeGroupForItems.items?.length || 0;
      
      const { data, error } = await supabase
        .from("catalog_story_items")
        .insert({
          group_id: activeGroupForItems.id,
          image_url: cameraImage,
          product_id: cameraProductId === "none" ? null : cameraProductId,
          position
        })
        .select()
        .single();

      if (error) throw error;

      // Update local state
      const updatedGroup = {
        ...activeGroupForItems,
        items: [...(activeGroupForItems.items || []), data]
      };
      
      setGroups(groups.map(g => g.id === updatedGroup.id ? updatedGroup : g));
      setActiveGroupForItems(updatedGroup);
      
      toast.success("Foto adicionada ao story!");
      setIsCameraUiOpen(false); // Fecha a câmera e volta pro modal de itens
      
    } catch (error) {
      console.error(error);
      toast.error("Erro ao adicionar foto");
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteItem = async (itemId: string) => {
    if (!activeGroupForItems) return;
    
    try {
      // Find item to get image URL
      const itemToDelete = activeGroupForItems.items?.find(i => i.id === itemId);
      
      // 1. Delete from Storage
      if (itemToDelete?.image_url) {
        const urlObj = new URL(itemToDelete.image_url);
        const path = urlObj.pathname.split('/object/public/products/')[1];
        
        if (path) {
          const { error: storageError } = await supabase.storage
            .from('products')
            .remove([path]);
            
          if (storageError) {
            console.error("Erro ao deletar arquivo do storage:", storageError);
          }
        }
      }

      // 2. Delete from Database
      const { error } = await supabase.from("catalog_story_items").delete().eq("id", itemId);
      if (error) throw error;
      
      const updatedGroup = {
        ...activeGroupForItems,
        items: (activeGroupForItems.items || []).filter(i => i.id !== itemId)
      };
      
      setGroups(groups.map(g => g.id === updatedGroup.id ? updatedGroup : g));
      setActiveGroupForItems(updatedGroup);
      toast.success("Foto removida!");
    } catch (error) {
      toast.error("Erro ao remover foto");
    }
  };

  const toggleGroupActive = async (id: string, current: boolean) => {
    try {
      setGroups(groups.map(g => g.id === id ? { ...g, active: !current } : g));
      await supabase.from("catalog_story_groups").update({ active: !current }).eq("id", id);
    } catch (error) {
      toast.error("Erro ao atualizar status");
    }
  };

  return (
    <div className="space-y-6 max-w-5xl mx-auto pb-12">
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
        <div>
          <PageHeader title="Stories do Catálogo" />
          <p className="text-sm text-muted-foreground mt-1">Gerencie os stories da sua loja.</p>
        </div>
        <div className="flex items-center gap-3">
          <div className="flex items-center gap-2 bg-white px-4 py-2 rounded-xl border shadow-sm">
            <span className="text-sm font-medium text-gray-700">Visível na Loja</span>
            <Switch checked={globalStoriesEnabled} onCheckedChange={toggleGlobalStories} />
          </div>
        </div>
      </div>

      <div className="bg-white rounded-2xl border p-6 shadow-sm">
        <h2 className="text-sm font-semibold text-gray-500 uppercase tracking-wider mb-6">Pré-visualização e Ordem</h2>
        
        <div className="flex items-start gap-6 overflow-x-auto pb-4 no-scrollbar">
          
          {/* Botão de Adicionar (Estilo Seu Story) */}
          <button 
            onClick={openNewGroupModal}
            className="flex flex-col items-center gap-2 shrink-0 group focus:outline-none"
          >
            <div className="relative w-[76px] h-[76px] rounded-full p-[2px] border-[2px] border-dashed border-gray-300 group-hover:border-gray-400 transition-colors flex items-center justify-center bg-gray-50">
              <Plus className="text-gray-400 group-hover:text-gray-600" size={32} />
            </div>
            <span className="text-[12px] font-medium text-gray-500 w-[80px] truncate text-center">
              Novo
            </span>
          </button>

          <DragDropContext onDragEnd={handleDragEnd}>
            <Droppable droppableId="stories-groups" direction="horizontal">
              {(provided) => (
                <div 
                  {...provided.droppableProps} 
                  ref={provided.innerRef} 
                  className="flex items-start gap-6"
                >
                  {groups.map((group, index) => (
                    <Draggable key={group.id} draggableId={group.id} index={index}>
                      {(provided, snapshot) => (
                        <div
                          ref={provided.innerRef}
                          {...provided.draggableProps}
                          {...provided.dragHandleProps}
                          className="flex flex-col items-center gap-2 shrink-0 group relative"
                        >
                          {/* Ações Hover */}
                          <div className={`absolute -top-10 left-1/2 -translate-x-1/2 bg-white shadow-xl border rounded-lg p-1 flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10 pointer-events-none group-hover:pointer-events-auto ${snapshot.isDragging ? 'hidden' : ''}`}>
                            <button onClick={(e) => { e.stopPropagation(); openEditGroupModal(group); }} className="p-1.5 text-gray-600 hover:text-[var(--ks-color-primary)] hover:bg-gray-100 rounded-md" title="Editar Destaque">
                              <Settings size={14} />
                            </button>
                            <button onClick={(e) => { e.stopPropagation(); handleDeleteGroup(group.id); }} className="p-1.5 text-gray-600 hover:text-red-600 hover:bg-red-50 rounded-md" title="Excluir">
                              <Trash2 size={14} />
                            </button>
                          </div>

                          {/* Bolinha do Story */}
                          <button 
                            onClick={() => openViewer(group)}
                            className="relative w-[76px] h-[76px] rounded-full p-[2px] transition-transform hover:scale-105 focus:outline-none flex items-center justify-center shrink-0"
                            style={{ 
                              background: group.active 
                                ? 'linear-gradient(45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%)' 
                                : '#e5e7eb' 
                            }}
                          >
                            <div className={`w-full h-full rounded-full border-[2.5px] border-white bg-gray-100 overflow-hidden relative ${!group.active ? 'opacity-50 grayscale' : ''}`}>
                              {group.thumbnail_url ? (
                                <Image src={group.thumbnail_url} alt={group.title} fill className="object-cover" />
                              ) : (
                                <div className="flex items-center justify-center w-full h-full text-gray-400 bg-white">
                                  <ImageIcon size={24}/>
                                </div>
                              )}
                            </div>
                            
                            {/* Indicador de Quantidade de Fotos */}
                            <div className="absolute -bottom-1 -right-1 bg-gray-900 text-white text-[10px] font-bold w-5 h-5 rounded-full flex items-center justify-center border-2 border-white">
                              {group.items?.length || 0}
                            </div>
                          </button>
                          
                          {/* Título */}
                          <span className={`text-[12px] font-medium w-[80px] truncate text-center ${!group.active ? 'text-gray-400 line-through' : 'text-gray-800'}`}>
                            {group.title}
                          </span>
                        </div>
                      )}
                    </Draggable>
                  ))}
                  {provided.placeholder}
                </div>
              )}
            </Droppable>
          </DragDropContext>
        </div>
      </div>

      <Dialog open={isGroupModalOpen} onOpenChange={setIsGroupModalOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{editingGroup ? "Editar Destaque" : "Novo Destaque"}</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div>
              <label className="block text-sm font-medium mb-1">Capa (Bolinha)</label>
              <ImageUpload
                value={groupThumbnail}
                onChange={setGroupThumbnail}
                bucket="products"
                folder="stories"
              />
              <p className="text-xs text-gray-500 mt-1">Esta é a imagem que aparece na bolinha do destaque.</p>
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">Título</label>
              <Input value={groupTitle} onChange={e => setGroupTitle(e.target.value)} placeholder="Ex: Lançamentos, Promoção..." />
            </div>
            {editingGroup && (
              <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg border">
                <div>
                  <label className="text-sm font-medium text-gray-900">Status do Destaque</label>
                  <p className="text-xs text-gray-500">Se inativo, não aparecerá na loja pública.</p>
                </div>
                <Switch checked={groupActive} onCheckedChange={setGroupActive} />
              </div>
            )}
          </div>
          <DialogFooter className="flex items-center justify-between sm:justify-between w-full">
            {editingGroup && podeMexerNoCatalogo ? (
              <Button
                type="button"
                variant="ghost"
                onClick={() => handleDeleteGroup(editingGroup.id)}
                className="text-red-600 hover:text-red-700 hover:bg-red-50"
              >
                Excluir Destaque
              </Button>
            ) : (
              <div></div>
            )}
            <div className="flex items-center gap-2">
              <Button variant="outline" onClick={() => setIsGroupModalOpen(false)}>Cancelar</Button>
              {podeMexerNoCatalogo && (<Button onClick={handleSaveGroup} disabled={loading}>{loading ? "Salvando..." : "Salvar"}</Button>)}
            </div>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* STORY VIEWER MODAL (Igual ao Público) */}
      <Dialog open={isViewerOpen} onOpenChange={setIsViewerOpen}>
        <DialogContent className="max-w-md w-full h-[100dvh] md:h-[85vh] p-0 overflow-hidden bg-black border-0 rounded-none md:rounded-3xl flex flex-col">
          <DialogTitle className="sr-only">Visualizador de Story</DialogTitle>
          
          {activeGroupForItems && activeGroupForItems.items && activeGroupForItems.items.length > 0 && (
            <>
              {/* Progress Bars */}
              <div className="absolute top-0 left-0 right-0 p-4 z-20 flex gap-1">
                {activeGroupForItems.items.map((item, idx) => (
                  <div key={item.id} className="h-1 flex-1 bg-white/30 rounded-full overflow-hidden">
                    <div 
                      className="h-full bg-white transition-all duration-75 ease-linear"
                      style={{ 
                        width: idx < viewerItemIndex ? '100%' : idx === viewerItemIndex ? `${viewerProgress}%` : '0%' 
                      }}
                    />
                  </div>
                ))}
              </div>

              {/* Header */}
              <div className="absolute top-6 left-0 right-0 px-4 z-20 flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <div className="w-8 h-8 rounded-full overflow-hidden relative border border-white/50">
                    {activeGroupForItems.thumbnail_url && (
                      <Image src={activeGroupForItems.thumbnail_url} alt="" fill className="object-cover" />
                    )}
                  </div>
                  <span className="text-white font-semibold text-sm drop-shadow-md">{activeGroupForItems.title}</span>
                </div>
                <div className="flex items-center gap-2">
                  <button onClick={closeViewer} className="text-white p-2">
                    <X size={24} />
                  </button>
                </div>
              </div>

              {/* Content area with tap zones */}
              <div className="flex-1 relative flex items-center justify-center">
                <div className="absolute inset-0">
                  <Image 
                    src={activeGroupForItems.items[viewerItemIndex].image_url} 
                    alt="" 
                    fill 
                    className="object-contain"
                    priority
                  />
                </div>

                {/* Tap zones */}
                <div 
                  className="absolute inset-y-0 left-0 w-1/3 z-10" 
                  onClick={handleViewerPrev}
                  onPointerDown={() => setIsPaused(true)}
                  onPointerUp={() => setIsPaused(false)}
                  onPointerLeave={() => setIsPaused(false)}
                />
                <div 
                  className="absolute inset-y-0 right-0 w-2/3 z-10" 
                  onClick={handleViewerNext}
                  onPointerDown={() => setIsPaused(true)}
                  onPointerUp={() => setIsPaused(false)}
                  onPointerLeave={() => setIsPaused(false)}
                />
              </div>

              {/* Bottom Actions (Admin Specific) */}
              <div className="absolute bottom-0 left-0 right-0 p-4 pb-8 z-20 bg-gradient-to-t from-black/80 via-black/40 to-transparent">
                
                {/* Product Card (If linked) */}
                {activeGroupForItems.items[viewerItemIndex].product_id && (
                  <div className="bg-white/10 backdrop-blur-md border border-white/20 rounded-full p-2 px-4 flex items-center gap-2 mb-6 w-max mx-auto shadow-lg">
                    <ShoppingCart className="text-white shrink-0" size={14} />
                    <span className="font-semibold text-white truncate text-xs drop-shadow-md">
                      {products.find(p => p.id === activeGroupForItems.items![viewerItemIndex].product_id)?.name}
                    </span>
                  </div>
                )}

                {/* Admin Controls (Instagram Style) */}
                <div className="flex items-center justify-between px-2">
                  <div className="flex items-center gap-4">
                    <button 
                      className="flex flex-col items-center gap-1 text-white hover:text-red-400 transition-colors group"
                      onClick={() => {
                        handleDeleteItem(activeGroupForItems.items![viewerItemIndex].id);
                        if (activeGroupForItems.items!.length <= 1) {
                          closeViewer();
                        } else if (viewerItemIndex > 0) {
                          setViewerItemIndex(prev => prev - 1);
                        }
                      }}
                    >
                      <div className="w-10 h-10 rounded-full bg-black/40 backdrop-blur-md flex items-center justify-center border border-white/10 group-hover:border-red-500/50">
                        <Trash2 size={20} />
                      </div>
                      <span className="text-[10px] font-medium drop-shadow-md">Excluir</span>
                    </button>
                  </div>
                  
                  <div className="flex items-center gap-4">
                    <button 
                      className="flex flex-col items-center gap-1 text-white hover:text-gray-300 transition-colors group"
                      onClick={openCameraUi}
                    >
                      <div className="w-10 h-10 rounded-full bg-black/40 backdrop-blur-md flex items-center justify-center border border-white/10">
                        <Plus size={24} />
                      </div>
                      <span className="text-[10px] font-medium drop-shadow-md">Adicionar</span>
                    </button>
                    
                    <button 
                      className="flex flex-col items-center gap-1 text-white hover:text-gray-300 transition-colors group"
                      onClick={() => {
                        setIsViewerOpen(false);
                        openEditGroupModal(activeGroupForItems);
                      }}
                    >
                      <div className="w-10 h-10 rounded-full bg-black/40 backdrop-blur-md flex items-center justify-center border border-white/10">
                        <Settings size={20} />
                      </div>
                      <span className="text-[10px] font-medium drop-shadow-md">Ajustes</span>
                    </button>
                  </div>
                </div>
              </div>
            </>
          )}
        </DialogContent>
      </Dialog>

      {/* INSTAGRAM CAMERA UI MODAL (Tela Cheia) */}
      <Dialog open={isCameraUiOpen} onOpenChange={setIsCameraUiOpen}>
        <DialogContent className="max-w-md w-full h-[100dvh] md:h-[85vh] p-0 overflow-hidden bg-black border-0 rounded-none md:rounded-3xl flex flex-col">
          <DialogTitle className="sr-only">Câmera do Story</DialogTitle>
          {/* Header Actions */}
          <div className="absolute top-0 left-0 right-0 z-50 p-4 flex items-center justify-between bg-gradient-to-b from-black/60 to-transparent">
            <button onClick={() => setIsCameraUiOpen(false)} className="text-white p-2 hover:bg-white/10 rounded-full transition-colors">
              <X size={24} />
            </button>
            <div className="flex gap-4 text-white">
              <button className="p-2 hover:bg-white/10 rounded-full transition-colors"><Settings size={22} /></button>
            </div>
          </div>

          {/* Camera Viewfinder / Image Preview */}
          <div className="flex-1 relative bg-zinc-900 flex items-center justify-center overflow-hidden">
            {cameraImage ? (
              <Image src={cameraImage} alt="Preview" fill className="object-cover" />
            ) : (
              <div className="text-white/50 flex flex-col items-center gap-4 text-center px-8">
                <div className="w-16 h-16 border-2 border-white/20 rounded-full flex items-center justify-center mb-2">
                  <Camera size={28} className="text-white/80" />
                </div>
                <p className="text-sm">Faça upload de uma foto da sua galeria.</p>
                <p className="text-xs text-white/30">O formato ideal é 9:16 (vertical).</p>
              </div>
            )}
            
            {/* Link Indicator Overlay */}
            {cameraProductId !== "none" && cameraImage && (
              <div className="absolute bottom-24 left-1/2 -translate-x-1/2 bg-white/90 backdrop-blur-md px-4 py-2 rounded-full flex items-center gap-2 shadow-lg max-w-[80%]">
                <ShoppingCart size={14} className="text-[var(--ks-color-primary)] shrink-0" />
                <span className="text-xs font-bold text-gray-900 truncate">
                  {products.find(p => p.id === cameraProductId)?.name}
                </span>
              </div>
            )}
          </div>

          {/* Bottom Controls (Instagram Style) */}
          <div className="bg-black text-white pb-safe pt-4 px-6 flex flex-col gap-6 relative z-50">
            {/* Action Row */}
            <div className="flex items-center justify-between">
              
              {/* Gallery Upload Button (Left) */}
              <div className="relative w-10 h-10 rounded-md overflow-hidden border border-white/30 bg-zinc-800 flex items-center justify-center shrink-0">
                {cameraImage ? (
                  <Image src={cameraImage} alt="Thumb" fill className="object-cover opacity-50" />
                ) : (
                  <ImageIcon size={20} className="text-white/70" />
                )}
                <div className="absolute inset-0 z-10 opacity-0 overflow-hidden [&>div]:h-full [&>div]:w-full [&_button]:h-full [&_button]:w-full [&_button]:absolute [&_button]:inset-0">
                  <ImageUpload
                    value={cameraImage}
                    onChange={setCameraImage}
                    bucket="products"
                    folder="stories"
                  />
                </div>
              </div>

              {/* Center Shutter Button (Fake for aesthetics, since it's a web app) */}
              <div className="w-16 h-16 rounded-full border-4 border-white p-1 shrink-0 opacity-50 cursor-not-allowed">
                <div className="w-full h-full rounded-full bg-white"></div>
              </div>

              {/* Product Link Button (Right) */}
              <button 
                onClick={() => setIsProductSelectorOpen(!isProductSelectorOpen)}
                className={`w-10 h-10 rounded-full flex items-center justify-center transition-colors shrink-0 ${cameraProductId !== "none" ? "bg-[var(--ks-color-primary)] text-white" : "bg-zinc-800 text-white"}`}
              >
                <ShoppingCart size={18} />
              </button>

            </div>

            {/* Product Selector Slider (Custom Modal) */}
            <AnimatePresence>
              {isProductSelectorOpen && (
                <motion.div 
                  initial={{ opacity: 0, y: "100%" }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: "100%" }}
                  transition={{ type: "spring", damping: 25, stiffness: 200 }}
                  className="absolute inset-x-0 bottom-0 bg-zinc-900 rounded-t-3xl pt-2 pb-8 px-4 z-[60] flex flex-col h-[70vh] shadow-[0_-10px_40px_rgba(0,0,0,0.5)]"
                >
                  {/* Handle bar */}
                  <div className="w-12 h-1.5 bg-zinc-700 rounded-full mx-auto mb-6 shrink-0" />
                  
                  <div className="flex items-center justify-between mb-4 shrink-0">
                    <h3 className="text-white font-semibold text-lg">Vincular Produto</h3>
                    <button 
                      onClick={() => setIsProductSelectorOpen(false)}
                      className="p-2 bg-zinc-800 rounded-full text-zinc-400 hover:text-white"
                    >
                      <X size={18} />
                    </button>
                  </div>

                  {/* Search */}
                  <div className="relative mb-4 shrink-0">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-500" size={18} />
                    <input 
                      type="text" 
                      placeholder="Buscar produto..." 
                      className="w-full bg-zinc-800 text-white placeholder:text-zinc-500 rounded-xl py-3 pl-10 pr-4 outline-none focus:ring-2 focus:ring-[var(--ks-color-primary)] border border-zinc-700 focus:border-transparent transition-all"
                      value={productSearchQuery}
                      onChange={(e) => setProductSearchQuery(e.target.value)}
                    />
                  </div>

                  {/* Product List */}
                  <div className="flex-1 overflow-y-auto no-scrollbar space-y-2 pb-safe">
                    {/* Option: None */}
                    <button
                      onClick={() => {
                        setCameraProductId("none");
                        setIsProductSelectorOpen(false);
                      }}
                      className={`w-full flex items-center gap-4 p-3 rounded-xl transition-colors ${cameraProductId === "none" ? 'bg-[var(--ks-color-primary)]/20 border border-[var(--ks-color-primary)]/50' : 'hover:bg-zinc-800 border border-transparent'}`}
                    >
                      <div className="w-12 h-12 rounded-lg bg-zinc-800 flex items-center justify-center shrink-0 border border-zinc-700">
                        <X size={20} className="text-zinc-400" />
                      </div>
                      <div className="flex-1 text-left">
                        <p className={`font-medium ${cameraProductId === "none" ? 'text-[var(--ks-color-primary-light)]' : 'text-white'}`}>Nenhum produto</p>
                        <p className="text-xs text-zinc-400">Apenas foto no story</p>
                      </div>
                      {cameraProductId === "none" && <Check className="text-[var(--ks-color-primary)]" size={20} />}
                    </button>

                    {/* Products */}
                    {filteredProducts.length === 0 ? (
                      <div className="text-center text-zinc-500 py-8 text-sm">
                        Nenhum produto encontrado.
                      </div>
                    ) : (
                      filteredProducts.map(p => (
                        <button
                          key={p.id}
                          onClick={() => {
                            setCameraProductId(p.id);
                            setIsProductSelectorOpen(false);
                          }}
                          className={`w-full flex items-center gap-4 p-3 rounded-xl transition-colors ${cameraProductId === p.id ? 'bg-[var(--ks-color-primary)]/20 border border-[var(--ks-color-primary)]/50' : 'hover:bg-zinc-800 border border-transparent'}`}
                        >
                          <div className="w-12 h-12 rounded-lg bg-zinc-800 overflow-hidden relative shrink-0 border border-zinc-700">
                            {p.image_url ? (
                              <Image src={p.image_url} alt={p.name} fill className="object-cover" />
                            ) : (
                              <div className="w-full h-full flex items-center justify-center text-zinc-600"><ImageIcon size={16} /></div>
                            )}
                          </div>
                          <div className="flex-1 text-left min-w-0">
                            <p className={`font-medium truncate ${cameraProductId === p.id ? 'text-[var(--ks-color-primary-light)]' : 'text-white'}`}>{p.name}</p>
                            <p className="text-xs text-zinc-400 font-medium mt-0.5">
                              {new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(p.price || 0)}
                            </p>
                          </div>
                          {cameraProductId === p.id && <Check className="text-[var(--ks-color-primary)]" size={20} />}
                        </button>
                      ))
                    )}
                  </div>
                </motion.div>
              )}
            </AnimatePresence>

            {/* Bottom Actions Row (Your Story / Close Friends / Next) */}
            <div className="flex items-center justify-between pb-6 pt-2">
              <div className="flex gap-2">
                <button className="bg-zinc-800 hover:bg-zinc-700 transition-colors rounded-full py-2 px-4 flex items-center gap-2 cursor-default opacity-50">
                  <div className="w-5 h-5 rounded-full overflow-hidden relative border border-white">
                    {activeGroupForItems?.thumbnail_url ? (
                      <Image src={activeGroupForItems.thumbnail_url} alt="" fill className="object-cover" />
                    ) : (
                      <div className="w-full h-full bg-gray-500"></div>
                    )}
                  </div>
                  <span className="text-xs font-medium">Seu Destaque</span>
                </button>
              </div>

              {/* Next/Save Button */}
              <button 
                onClick={handleAddItem} 
                disabled={loading || !cameraImage}
                className="w-10 h-10 rounded-full flex items-center justify-center bg-white text-black hover:bg-gray-200 transition-colors disabled:opacity-50 shrink-0"
              >
                {loading ? <div className="w-4 h-4 border-2 border-black border-t-transparent rounded-full animate-spin" /> : <ChevronRight size={24} />}
              </button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
