import { useState, useEffect } from "react"; import { Button } from "@/components/ui/button"; import { InputWithContext } from "@/components/ui/input-with-context"; import { Label } from "@/components/ui/label"; import { XCircle, Calendar, StopCircle, Globe, Lock, Bookmark, Heart, Key, Eye, EyeOff, ChevronDown, ChevronUp, Info, RotateCcw, Trash2, Clock, CloudDownload, User, Users, FileText, Hourglass, CheckCircle, AlertCircle, } from "lucide-react"; import { Spinner } from "@/components/ui/spinner"; import { Checkbox } from "@/components/ui/checkbox"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Tooltip, TooltipContent, TooltipTrigger, } from "@/components/ui/tooltip"; import { Settings as SettingsIcon } from "lucide-react"; import { FetchHistory } from "@/components/FetchHistory"; import type { HistoryItem } from "@/components/FetchHistory"; import { cn } from "@/lib/utils"; export type FetchMode = "public" | "private"; export type PrivateType = "bookmarks" | "likes"; export type FetchType = "single" | "multiple"; // Local storage keys for auth tokens const PUBLIC_AUTH_TOKEN_KEY = "twitter_public_auth_token"; const PRIVATE_AUTH_TOKEN_KEY = "twitter_private_auth_token"; export interface MultipleAccount { id: string; username: string; status: "pending" | "fetching" | "completed" | "incomplete" | "failed"; accountInfo?: { name: string; nick: string; profile_image: string; }; mediaCount: number; previousMediaCount: number; elapsedTime: number; remainingTime: number | null; error?: string; showDiff?: boolean; cursor?: string; } interface SearchBarProps { username: string; loading: boolean; onUsernameChange: (username: string) => void; onFetch: ( useDateRange: boolean, startDate?: string, endDate?: string, mediaType?: string, retweets?: boolean, mode?: FetchMode, privateType?: PrivateType, authToken?: string, isResume?: boolean ) => void; onStopFetch: () => void; onResume?: (authToken: string, mediaType?: string, retweets?: boolean) => void; onClearResume?: () => void; resumeInfo?: { canResume: boolean; mediaCount: number } | null; history: HistoryItem[]; onHistorySelect: (item: HistoryItem) => void; onHistoryRemove: (id: string) => void; hasResult: boolean; elapsedTime?: number; remainingTime?: number | null; // Multiple mode props fetchType?: FetchType; onFetchTypeChange?: (type: FetchType) => void; multipleAccounts?: MultipleAccount[]; onImportFile?: () => void; onFetchAll?: () => void; onStopAll?: () => void; onStopAccount?: (accountId: string) => void; onRetryAccount?: (accountId: string) => void; isFetchingAll?: boolean; // Mode control mode?: FetchMode; privateType?: PrivateType; onModeChange?: (mode: FetchMode, privateType?: PrivateType) => void; } export function SearchBar({ username, loading, onUsernameChange, onFetch, onStopFetch, onResume, onClearResume, resumeInfo, history, onHistorySelect, onHistoryRemove, hasResult, elapsedTime = 0, remainingTime = null, fetchType = "single", onFetchTypeChange, multipleAccounts = [], onImportFile, onFetchAll, onStopAll, onStopAccount, onRetryAccount, isFetchingAll = false, mode: externalMode, privateType: externalPrivateType, onModeChange, }: SearchBarProps) { const [useDateRange, setUseDateRange] = useState(false); const [startDate, setStartDate] = useState(""); const [endDate, setEndDate] = useState(""); const [mediaType, setMediaType] = useState("all"); const [retweets, setRetweets] = useState(false); const [mode, setMode] = useState(externalMode || "public"); const [privateType, setPrivateType] = useState(externalPrivateType || "bookmarks"); // Sync with external mode if provided useEffect(() => { if (externalMode !== undefined) { setMode(externalMode); } }, [externalMode]); useEffect(() => { if (externalPrivateType !== undefined) { setPrivateType(externalPrivateType); } }, [externalPrivateType]); const [showAuthInput, setShowAuthInput] = useState(false); const [showAdvanced, setShowAdvanced] = useState(false); // Separate auth tokens for public and private modes const [publicAuthToken, setPublicAuthToken] = useState(""); const [privateAuthToken, setPrivateAuthToken] = useState(""); const [showPublicToken, setShowPublicToken] = useState(false); const [showPrivateToken, setShowPrivateToken] = useState(false); // Load saved auth tokens on mount useEffect(() => { const savedPublicToken = localStorage.getItem(PUBLIC_AUTH_TOKEN_KEY) || ""; const savedPrivateToken = localStorage.getItem(PRIVATE_AUTH_TOKEN_KEY) || ""; setPublicAuthToken(savedPublicToken); setPrivateAuthToken(savedPrivateToken); }, []); // Save auth tokens when they change const handlePublicTokenChange = (value: string) => { setPublicAuthToken(value); localStorage.setItem(PUBLIC_AUTH_TOKEN_KEY, value); }; const handlePrivateTokenChange = (value: string) => { setPrivateAuthToken(value); localStorage.setItem(PRIVATE_AUTH_TOKEN_KEY, value); }; const handleFetch = () => { const authToken = mode === "public" ? publicAuthToken : privateAuthToken; onFetch(useDateRange, startDate, endDate, mediaType, retweets, mode, privateType, authToken, false); }; const handleResume = () => { const authToken = mode === "public" ? publicAuthToken : privateAuthToken; if (onResume) { onResume(authToken, mediaType, retweets); } }; const currentAuthToken = mode === "public" ? publicAuthToken : privateAuthToken; const hasAuthToken = currentAuthToken.trim().length > 0; // Likes needs username (URL is /username/likes), bookmarks doesn't const isLikesMode = mode === "private" && privateType === "likes"; const isBookmarksMode = mode === "private" && privateType === "bookmarks"; const formatTime = (seconds: number): string => { const mins = Math.floor(seconds / 60); const secs = seconds % 60; return `${mins}:${String(secs).padStart(2, "0")}`; }; return (
{/* Fetch Type and Mode Toggle (Single/Multiple and Public/Private in one line) */}
{fetchType === "single" && (
)}
{/* Multiple Mode UI - Import and Fetch All Buttons */} {fetchType === "multiple" && (

One username per line, example:
masteraoko
xbatchdemo
takomayuyi

{isFetchingAll && ( )}
)} {/* Username Input - for public mode and likes mode, only in single mode */} {fetchType === "single" && (mode === "public" || isLikesMode) && (
onUsernameChange(e.target.value)} onKeyDown={(e) => e.key === "Enter" && handleFetch()} className="pr-8" /> {username && ( )}
{loading && ( <> {/* Timer Display */} {(remainingTime !== null || elapsedTime > 0) && (
{remainingTime !== null && remainingTime >= 0 ? `${Math.floor(remainingTime / 60)}:${String(remainingTime % 60).padStart(2, "0")}` : `${Math.floor(elapsedTime / 60)}:${String(elapsedTime % 60).padStart(2, "0")}`}
)} )} {/* Resume button - show when there's resumable data */} {!loading && resumeInfo?.canResume && mode === "public" && ( <> Clear resume data )}
)} {/* Auth Token & Advanced Settings Row */}
{/* Auth Token Button */} {/* Advanced Settings Button */} {/* Private Mode Options - My Bookmarks / My Likes */} {mode === "private" && fetchType === "single" && ( <> )} {/* Bookmarks Mode - Fetch button inline */} {isBookmarksMode && (
{loading && ( <> {/* Timer Display */} {(remainingTime !== null || elapsedTime > 0) && (
{remainingTime !== null && remainingTime >= 0 ? `${Math.floor(remainingTime / 60)}:${String(remainingTime % 60).padStart(2, "0")}` : `${Math.floor(elapsedTime / 60)}:${String(elapsedTime % 60).padStart(2, "0")}`}
)} )}
)}
{/* Auth Token Input (collapsible) */} {showAuthInput && (
{mode === "private" ? (

Use auth token from the account whose bookmarks/likes you want to fetch

) : (

Recommended to use a dummy account, not your main account.
Excessive usage may cause suspension

)}
mode === "public" ? handlePublicTokenChange(e.target.value) : handlePrivateTokenChange(e.target.value) } className="pr-10 bg-background" />
)} {/* Advanced Settings (collapsible) */} {showAdvanced && (
{/* Options Row */}
{/* Media Type */}
{/* Include Retweets */}
setRetweets(checked as boolean)} className="bg-background" />
{/* Date Range Toggle - only for public mode */} {mode === "public" && ( <>
setUseDateRange(checked as boolean)} className="bg-background" />
{/* Date Range Inputs - inline */} {useDateRange && ( <> setStartDate(e.target.value)} className="w-[140px] h-8 bg-background" /> - setEndDate(e.target.value)} className="w-[140px] h-8 bg-background" /> )} )}
)} {/* Statistics for Multiple Fetch - below auth token and advanced settings */} {fetchType === "multiple" && multipleAccounts.length > 0 && (
Completed: {multipleAccounts.filter((acc) => acc.status === "completed").length}
Incomplete: {multipleAccounts.filter((acc) => acc.status === "incomplete").length}
Failed: {multipleAccounts.filter((acc) => acc.status === "failed").length}
Total: {multipleAccounts.filter((acc) => acc.status === "completed" || acc.status === "incomplete" || acc.status === "failed" ).length}/{multipleAccounts.length}
)} {/* Account List - below auth token and advanced settings */} {fetchType === "multiple" && multipleAccounts.length > 0 && (

Accounts to Fetch ({multipleAccounts.length})

{multipleAccounts.map((account) => (
{account.accountInfo ? ( {account.accountInfo.nick} ) : (
)}
{account.accountInfo ? ( <>
{account.accountInfo.nick} @{account.accountInfo.name}
{account.mediaCount.toLocaleString()} items found {account.showDiff && account.previousMediaCount > 0 && account.mediaCount > account.previousMediaCount && ( +{account.mediaCount - account.previousMediaCount} )}
) : (
@{account.username}
)}
{account.status === "fetching" && ( <>
{account.remainingTime !== null && account.remainingTime >= 0 ? formatTime(account.remainingTime) : formatTime(account.elapsedTime)}
)} {account.status === "pending" && ( Pending )} {account.status === "completed" && ( Completed )} {account.status === "incomplete" && ( <> Incomplete )} {account.status === "failed" && ( <> Failed )}
))}
)} {!hasResult && mode === "public" && fetchType === "single" && ( )}
); }