"use client"; import { useState, useMemo, useEffect } from "react"; import "react-datepicker/dist/react-datepicker.css"; import DatePicker from "react-datepicker"; import { InstagramAccount, Post } from "@prisma/client"; import CoverFrameSelector from "./CoverFrameSelector"; import TimePicker from "./TimePicker"; import { UploadCloud, Image as ImageIcon, Video, Layers, Calendar, Clock, X, ChevronDown, Smile, Hash, GripVertical, Heart, MessageCircle, Send, Bookmark, MoreHorizontal, ImagePlus, PlusCircle, FileText, User as UserIcon, Tag as TagIcon, LayoutTemplate } from "lucide-react"; import MediaPreview from "./MediaPreview"; import { useRouter } from "next/navigation"; import Image from "next/image"; import { format } from "date-fns"; import TipTapEditor from "@/components/TipTapEditor"; // Styled Components / Token Classes const PAGE_CONTAINER = "max-w-4xl mx-auto flex flex-col lg:flex-row gap-8 lg:gap-16 pt-8 pb-20"; const EDITOR_COLUMN = "flex-1 min-w-0"; const PREVIEW_COLUMN = "w-[380px] flex-shrink-0 hidden lg:block"; const NOTION_PROPERTY_ROW = "flex items-start py-1.5 min-h-[32px] text-sm group"; const NOTION_PROPERTY_LABEL = "w-[120px] pt-1 text-gray-400 flex items-center gap-2 select-none truncate"; const NOTION_PROPERTY_VALUE = "flex-1 min-w-0 flex flex-wrap items-center gap-2"; const NOTION_TITLE = "text-4xl font-bold text-foreground placeholder-gray-200 outline-none bg-transparent w-full resize-none overflow-hidden h-auto block mb-6"; export default function PostCreator({ accounts, initialMediaType = "IMAGE", initialPost }: { accounts: InstagramAccount[], initialMediaType?: string, initialPost?: Post | null }) { const router = useRouter(); // -- State -- const [postType, setPostType] = useState<"FEED" | "REELS">( initialPost ? (initialPost.mediaType === "REELS" ? "REELS" : "FEED") : (initialMediaType.toLowerCase() === "video" || initialMediaType === "REELS" ? "REELS" : "FEED") ); const [selectedAccountIds, setSelectedAccountIds] = useState( initialPost ? [initialPost.instagramAccountId] : (accounts.length > 0 ? [accounts[0].id] : []) ); const [caption, setCaption] = useState(initialPost?.caption || ""); const [mediaItems, setMediaItems] = useState<(File | string)[]>( initialPost?.mediaUrl ? initialPost.mediaUrl.split(',') : [] ); const [activeMediaIndex, setActiveMediaIndex] = useState(0); const [coverItem, setCoverItem] = useState(initialPost?.coverUrl || null); const [isCoverModalOpen, setIsCoverModalOpen] = useState(false); const [scheduledAt, setScheduledAt] = useState( initialPost?.scheduledAt ? new Date(initialPost.scheduledAt) : null ); const [isSubmitting, setIsSubmitting] = useState(false); // For "Notion Page Title" simulation (visual only or internal name?) // Instagram doesn't have a title. We'll keep it visual. const [title, setTitle] = useState("Untitled"); // -- Helpers -- const toggleAccount = (id: string) => { setSelectedAccountIds(prev => prev.includes(id) ? prev.filter(accId => accId !== id) : [...prev, id] ); }; const handleFileSelect = (e: React.ChangeEvent) => { if (e.target.files && e.target.files.length > 0) { const newFiles = Array.from(e.target.files); if (postType === "REELS") { setMediaItems([newFiles[0]]); setCoverItem(null); setActiveMediaIndex(0); } else { setMediaItems(prev => [...prev, ...newFiles]); } } }; const handleReorder = (fromIndex: number, toIndex: number) => { setMediaItems(prev => { const newItems = [...prev]; const [movedItem] = newItems.splice(fromIndex, 1); newItems.splice(toIndex, 0, movedItem); return newItems; }); setActiveMediaIndex(toIndex); }; const coverObjectUrl = useMemo(() => { if (!coverItem) return null; if (typeof coverItem === "string") return coverItem; return URL.createObjectURL(coverItem); }, [coverItem]); const primaryAccount = accounts.find(a => a.id === selectedAccountIds[0]); // -- Submit Handler -- const handleSubmit = async () => { if (selectedAccountIds.length === 0 || mediaItems.length === 0) { alert("Please select an account and add media."); return; } setIsSubmitting(true); try { // Upload Logic (Similar to before) const newMediaFiles = mediaItems.filter(item => item instanceof File) as File[]; const newCoverFile = coverItem instanceof File ? coverItem : null; let uploadedMediaUrls: string[] = []; let uploadedCoverUrl: string | null = null; if (newMediaFiles.length > 0 || newCoverFile) { const formData = new FormData(); newMediaFiles.forEach(file => formData.append("file", file)); if (newCoverFile) formData.append("file", newCoverFile); const uploadRes = await fetch("/api/upload", { method: "POST", body: formData }); if (!uploadRes.ok) throw new Error("Upload failed"); const { urls } = await uploadRes.json(); const newMediaCount = newMediaFiles.length; uploadedMediaUrls = urls.slice(0, newMediaCount); if (newCoverFile) uploadedCoverUrl = urls[newMediaCount]; } let nextUploadIndex = 0; const finalMediaUrls = mediaItems.map(item => { if (typeof item === "string") return item; return uploadedMediaUrls[nextUploadIndex++]; }); const finalCoverUrl = newCoverFile ? uploadedCoverUrl : (typeof coverItem === "string" ? coverItem : null); let finalMediaType: string = postType; if (postType === "FEED") { if (finalMediaUrls.length > 1) { finalMediaType = "CAROUSEL"; } else if (finalMediaUrls.length === 1) { // content checks to discern VIDEO vs IMAGE // We can check the original item type if it's a File, or extension if string const originalItem = mediaItems[0]; let isVideo = false; if (originalItem instanceof File) { isVideo = originalItem.type.startsWith("video"); } else if (typeof originalItem === 'string') { isVideo = originalItem.endsWith(".mp4") || originalItem.endsWith(".mov") || originalItem.includes("/video/"); } finalMediaType = isVideo ? "VIDEO" : "IMAGE"; } } const postData = { caption, mediaUrl: finalMediaUrls.join(","), mediaType: finalMediaType, coverUrl: finalCoverUrl, scheduledAt: scheduledAt ? scheduledAt.toISOString() : null, }; if (initialPost) { await fetch("/api/posts", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id: initialPost.id, ...postData }), }); } else { for (const accId of selectedAccountIds) { await fetch("/api/posts", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ instagramAccountId: accId, ...postData }), }); } } router.push(scheduledAt ? "/dashboard/scheduled" : "/dashboard/posted"); router.refresh(); } catch (error) { console.error(error); alert("Failed to save post."); } finally { setIsSubmitting(false); } }; return (
{/* --- EDITOR COLUMN (Notion Page Style) --- */}
{/* Properties Table */}
{/* 1. Account Property */}
Account
{accounts.map(acc => { const isSelected = selectedAccountIds.includes(acc.id); return ( ); })}
{/* 3. Date Property */}
Date
{ const newDate = date || new Date(); if (scheduledAt) newDate.setHours(scheduledAt.getHours(), scheduledAt.getMinutes()); setScheduledAt(newDate); }} dateFormat="MMM d, yyyy" placeholderText="Empty" className="bg-transparent border-none outline-none text-sm text-foreground p-0 cursor-pointer placeholder-gray-300 hover:text-primary-green transition-colors" /> {scheduledAt && (
@
)}
{/* Content Block: Media */}
{mediaItems.length === 0 ? (
Add an image or video
) : (
{ setMediaItems(prev => prev.filter((_, i) => i !== index)); if (activeMediaIndex >= index && activeMediaIndex > 0) setActiveMediaIndex(prev => prev - 1); }} activeIndex={activeMediaIndex} onIndexChange={setActiveMediaIndex} onReorder={handleReorder} />
{postType === "FEED" && ( )} {postType === "REELS" && ( )}
)}
{/* Content Block: Caption (TipTap) */}
{/* Character Count */}
2200 ? "text-red-500 font-medium" : ""}`}> {caption.length} / 2200
{/* Footer / Actions - Inline at bottom */}
{/* --- PREVIEW COLUMN --- */}

Preview

{/* Phone Frame */}
{/* Status Bar */}
9:41
{/* Content Area */}
{postType === "REELS" ? ( /* --- REELS LAYOUT (Full height media + Overlay UI) --- */
{/* Background Media */} {mediaItems.length > 0 ? (
{(typeof mediaItems[0] === 'string' ? (mediaItems[0].endsWith(".mp4") || mediaItems[0].includes("/video/")) : mediaItems[0].type.startsWith("video") ) ? (
) : (
)} {/* Overlay UI */}
Reels
{/* Spacer/Camera icon place */}
{/* User Info */}
{(primaryAccount as any)?.profilePictureUrl && }
{primaryAccount?.username || "username"}
{/* Caption */}
{caption || "Caption goes here..."}
♫ Original Audio
{/* Right Side Actions */}
12.5k
523
{/* Audio thumb */} {(primaryAccount as any)?.profilePictureUrl && }
) : ( /* --- FEED LAYOUT (Standard) --- */
{/* User Info Header */}
{(primaryAccount as any)?.profilePictureUrl ? : null}
{primaryAccount?.username || "username"} {/* Location or Audio could go here */}
{/* Media - 4:5 Aspect Ratio Standard */}
{mediaItems.length > 0 ? ( <> {(typeof mediaItems[activeMediaIndex] === 'string' ? (mediaItems[activeMediaIndex].endsWith(".mp4") || mediaItems[activeMediaIndex].includes("/video/")) : mediaItems[activeMediaIndex].type.startsWith("video") ) ? (
{/* Action Bar */}
{/* Likes & Caption */}

1,234 likes

{primaryAccount?.username || "username"}
{caption || Caption goes here...}

2 hours ago

)}
setIsCoverModalOpen(false)} videoFile={mediaItems.length > 0 && postType === "REELS" ? mediaItems[0] : null} onSave={(file) => { setCoverItem(file); setIsCoverModalOpen(false); }} />
); }