import React, { useState, useMemo } from 'react';
import { Loader2, Calendar, CheckCircle, AlertCircle, Video, Instagram, Youtube, ChevronLeft, ChevronRight, Circle, ExternalLink } from 'lucide-react';
import { apiFetch } from '../lib/api';
import Modal from './ui/Modal';
import SegmentedControl from './ui/SegmentedControl';
import TikTokDraftNotice from './TikTokDraftNotice';
const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const TIMEZONES = [
{ value: 'Pacific/Midway', label: '(GMT-11:00) Midway' },
{ value: 'Pacific/Honolulu', label: '(GMT-10:00) Honolulu' },
{ value: 'America/Anchorage', label: '(GMT-09:00) Alaska' },
{ value: 'America/Los_Angeles', label: '(GMT-08:00) Los Angeles' },
{ value: 'America/Denver', label: '(GMT-07:00) Denver' },
{ value: 'America/Mexico_City', label: '(GMT-06:00) Mexico City' },
{ value: 'America/Chicago', label: '(GMT-06:00) Chicago' },
{ value: 'America/New_York', label: '(GMT-05:00) New York' },
{ value: 'America/Bogota', label: '(GMT-05:00) Bogota' },
{ value: 'America/Caracas', label: '(GMT-04:00) Caracas' },
{ value: 'America/Santiago', label: '(GMT-04:00) Santiago' },
{ value: 'America/Argentina/Buenos_Aires', label: '(GMT-03:00) Buenos Aires' },
{ value: 'America/Sao_Paulo', label: '(GMT-03:00) Sao Paulo' },
{ value: 'Atlantic/Azores', label: '(GMT-01:00) Azores' },
{ value: 'UTC', label: '(GMT+00:00) UTC' },
{ value: 'Europe/London', label: '(GMT+00:00) London' },
{ value: 'Europe/Madrid', label: '(GMT+01:00) Madrid' },
{ value: 'Europe/Paris', label: '(GMT+01:00) Paris' },
{ value: 'Europe/Berlin', label: '(GMT+01:00) Berlin' },
{ value: 'Europe/Rome', label: '(GMT+01:00) Rome' },
{ value: 'Africa/Lagos', label: '(GMT+01:00) Lagos' },
{ value: 'Europe/Istanbul', label: '(GMT+03:00) Istanbul' },
{ value: 'Asia/Dubai', label: '(GMT+04:00) Dubai' },
{ value: 'Asia/Kolkata', label: '(GMT+05:30) India' },
{ value: 'Asia/Bangkok', label: '(GMT+07:00) Bangkok' },
{ value: 'Asia/Shanghai', label: '(GMT+08:00) Shanghai' },
{ value: 'Asia/Tokyo', label: '(GMT+09:00) Tokyo' },
{ value: 'Australia/Sydney', label: '(GMT+10:00) Sydney' },
{ value: 'Pacific/Auckland', label: '(GMT+12:00) Auckland' },
];
const PLATFORM_OPTIONS = [
{ value: 'tiktok', label: 'TikTok', icon: },
{ value: 'instagram', label: 'Instagram', icon: },
{ value: 'youtube', label: 'YouTube', icon: },
];
function getDayLabel(date) {
const today = new Date();
today.setHours(0, 0, 0, 0);
const tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate() + 1);
const target = new Date(date);
target.setHours(0, 0, 0, 0);
if (target.getTime() === today.getTime()) return 'Today';
if (target.getTime() === tomorrow.getTime()) return 'Tomorrow';
return DAYS[target.getDay()];
}
function formatDate(date) {
return `${MONTHS[date.getMonth()]} ${date.getDate()}`;
}
function detectTimezone() {
try {
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
if (TIMEZONES.find(t => t.value === tz)) return tz;
return 'UTC';
} catch {
return 'UTC';
}
}
export default function ScheduleWeekModal({ isOpen, onClose, clips, jobId, uploadPostKey, uploadUserId, isManaged }) {
const [time, setTime] = useState('12:00');
const [timezone, setTimezone] = useState(detectTimezone);
const [platforms, setPlatforms] = useState({
tiktok: true,
instagram: true,
youtube: true
});
const [startOffset, setStartOffset] = useState(1);
const schedule = useMemo(() => {
if (!clips) return [];
return clips.map((clip, i) => {
const date = new Date();
date.setDate(date.getDate() + startOffset + i);
date.setHours(0, 0, 0, 0);
return { clip, index: i, date };
});
}, [clips, startOffset]);
const [scheduling, setScheduling] = useState(false);
const [progress, setProgress] = useState({ current: 0, total: 0, results: [] });
const [done, setDone] = useState(false);
// Reset state when modal reopens
const prevOpen = React.useRef(false);
React.useEffect(() => {
if (isOpen && !prevOpen.current) {
setScheduling(false);
setDone(false);
setProgress({ current: 0, total: 0, results: [] });
}
prevOpen.current = isOpen;
}, [isOpen]);
if (!isOpen) return null;
const selectedPlatforms = Object.keys(platforms).filter(k => platforms[k]);
// Managed (cloud plan/trial) users post with the server-side key — no BYOK needed
const canPost = isManaged || (uploadPostKey && uploadUserId);
const handleScheduleAll = async () => {
if (!canPost) return;
if (selectedPlatforms.length === 0) return;
setScheduling(true);
setDone(false);
const total = schedule.length;
setProgress({ current: 0, total, results: [] });
const results = [];
for (let i = 0; i < schedule.length; i++) {
const { clip, index, date } = schedule[i];
// Build local datetime string: "2026-04-06T12:00:00"
// Upload-Post accepts this + timezone IANA parameter
const pad = (n) => String(n).padStart(2, '0');
const scheduledDate = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${time}:00`;
const payload = {
job_id: jobId,
clip_index: index,
api_key: uploadPostKey,
user_id: uploadUserId,
platforms: selectedPlatforms,
title: clip.video_title_for_youtube_short || 'Viral Short',
description: clip.video_description_for_instagram || clip.video_description_for_tiktok || '',
scheduled_date: scheduledDate,
timezone
};
try {
const res = await apiFetch('/api/social/post', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (!res.ok) {
const errText = await res.text();
throw new Error(errText);
}
results.push({ index: i, success: true });
} catch (e) {
results.push({ index: i, success: false, error: e.message });
}
setProgress({ current: i + 1, total, results: [...results] });
}
setDone(true);
setScheduling(false);
};
const successCount = progress.results.filter(r => r.success).length;
const failCount = progress.results.filter(r => !r.success).length;
const footer = (
{done ? 'close' : 'cancel'}
{!done ? (
{scheduling ? (
<>
scheduling...
>
) : (
<>
schedule {clips?.length || 0} clips
>
)}
) : (
view calendar
)}
);
return (
{clips?.length || 0} CLIPS · 1/DAY
{!canPost && (
Set your Upload-Post API key in Settings first.
)}
{/* Time + Timezone */}
{/* Start day offset */}
start from
setStartOffset(Math.max(1, startOffset - 1))}
disabled={startOffset <= 1 || scheduling}
className="btn-quiet px-2 py-2 disabled:opacity-40 disabled:cursor-not-allowed"
>
{(() => {
const d = new Date();
d.setDate(d.getDate() + startOffset);
return `${getDayLabel(d)} · ${formatDate(d)}`;
})()}
setStartOffset(startOffset + 1)}
disabled={scheduling}
className="btn-quiet px-2 py-2 disabled:opacity-40 disabled:cursor-not-allowed"
>
{/* Calendar list */}
{schedule.map(({ clip, index, date }) => (
{getDayLabel(date)} · {formatDate(date)}
{clip.video_title_for_youtube_short || 'Viral Short'}
{time} · {TIMEZONES.find(t => t.value === timezone)?.label || timezone}
{progress.results[index]?.success === true && (
)}
{progress.results[index]?.success === false && (
)}
{scheduling && progress.current === index && (
)}
{!scheduling && progress.results[index] === undefined && (
)}
))}
{/* Platforms */}
platforms
({ ...opt, disabled: scheduling }))}
value={selectedPlatforms}
onChange={(arr) => setPlatforms({
tiktok: arr.includes('tiktok'),
instagram: arr.includes('instagram'),
youtube: arr.includes('youtube')
})}
/>
{/* A whole week of tiktok posts is a whole week of silent drafts:
this modal writes no captions of its own either (it sends the
clip's generated title/description), and tiktok keeps none of
them on a draft. Say it before the button, not after. */}
{platforms.tiktok && !scheduling && !done && }
{/* Progress bar */}
{(scheduling || done) && (
{scheduling ? 'scheduling...' : 'complete'}
{progress.current}/{progress.total}
0 ? 'bg-danger' : 'bg-brass'}`}
style={{ width: `${(progress.current / progress.total) * 100}%` }}
/>
{done && (
{failCount === 0 ? (
all clips scheduled
) : (
{successCount} scheduled, {failCount} failed
)}
)}
)}
);
}