import { useState, useEffect } from 'react' import { phaseDraftManagement, type ExperimentPhaseDraft, type ExperimentPhase, type User, type ExperimentRepetition } from '../lib/supabase' interface PhaseDraftManagerProps { repetition: ExperimentRepetition phase: ExperimentPhase currentUser: User onSelectDraft: (draft: ExperimentPhaseDraft) => void onClose: () => void } export function PhaseDraftManager({ repetition, phase, currentUser, onSelectDraft, onClose }: PhaseDraftManagerProps) { const [drafts, setDrafts] = useState([]) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) const [creating, setCreating] = useState(false) const [newDraftName, setNewDraftName] = useState('') useEffect(() => { loadDrafts() }, [repetition.id, phase]) const loadDrafts = async () => { try { setLoading(true) setError(null) const userDrafts = await phaseDraftManagement.getUserPhaseDraftsForPhase(repetition.id, phase) setDrafts(userDrafts) } catch (err: any) { setError(err.message || 'Failed to load drafts') console.error('Load drafts error:', err) } finally { setLoading(false) } } const handleCreateDraft = async () => { try { setCreating(true) setError(null) const newDraft = await phaseDraftManagement.createPhaseDraft({ experiment_id: repetition.experiment_id, repetition_id: repetition.id, phase_name: phase, draft_name: newDraftName || undefined, status: 'draft' }) setDrafts(prev => [newDraft, ...prev]) setNewDraftName('') onSelectDraft(newDraft) } catch (err: any) { setError(err.message || 'Failed to create draft') } finally { setCreating(false) } } const handleDeleteDraft = async (draftId: string) => { if (!confirm('Are you sure you want to delete this draft? This action cannot be undone.')) { return } try { await phaseDraftManagement.deletePhaseDraft(draftId) setDrafts(prev => prev.filter(draft => draft.id !== draftId)) } catch (err: any) { setError(err.message || 'Failed to delete draft') } } const handleSubmitDraft = async (draftId: string) => { if (!confirm('Are you sure you want to submit this draft? Once submitted, it can only be withdrawn by you or locked by an admin.')) { return } try { const submittedDraft = await phaseDraftManagement.submitPhaseDraft(draftId) setDrafts(prev => prev.map(draft => draft.id === draftId ? submittedDraft : draft )) } catch (err: any) { setError(err.message || 'Failed to submit draft') } } const handleWithdrawDraft = async (draftId: string) => { if (!confirm('Are you sure you want to withdraw this submitted draft? It will be marked as withdrawn.')) { return } try { const withdrawnDraft = await phaseDraftManagement.withdrawPhaseDraft(draftId) setDrafts(prev => prev.map(draft => draft.id === draftId ? withdrawnDraft : draft )) } catch (err: any) { setError(err.message || 'Failed to withdraw draft') } } const getStatusBadge = (status: string) => { switch (status) { case 'draft': return Draft case 'submitted': return Submitted case 'withdrawn': return Withdrawn default: return {status} } } const canDeleteDraft = (draft: ExperimentPhaseDraft) => { return draft.status === 'draft' && (!repetition.is_locked || currentUser.roles.includes('admin')) } const canSubmitDraft = (draft: ExperimentPhaseDraft) => { return draft.status === 'draft' && (!repetition.is_locked || currentUser.roles.includes('admin')) } const canWithdrawDraft = (draft: ExperimentPhaseDraft) => { return draft.status === 'submitted' && (!repetition.is_locked || currentUser.roles.includes('admin')) } const canCreateDraft = () => { return !repetition.is_locked || currentUser.roles.includes('admin') } const formatPhaseTitle = (phase: string) => { return phase.split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1) ).join(' ') } return (

{formatPhaseTitle(phase)} Phase Drafts

Repetition {repetition.repetition_number} {repetition.is_locked && ( 🔒 Locked )}

{error && (
{error}
)} {/* Create New Draft */}

Create New Draft

setNewDraftName(e.target.value)} className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" disabled={creating || repetition.is_locked} />
{repetition.is_locked && !currentUser.roles.includes('admin') && (

Cannot create new drafts: repetition is locked by admin

)}
{/* Drafts List */}
{loading ? (
Loading drafts...
) : drafts.length === 0 ? (
No drafts found for this phase

Create a new draft to get started

) : ( drafts.map((draft) => (

{draft.draft_name || `Draft ${draft.id.slice(-8)}`}

{getStatusBadge(draft.status)}

Created: {new Date(draft.created_at).toLocaleString()}

Updated: {new Date(draft.updated_at).toLocaleString()}

{draft.submitted_at && (

Submitted: {new Date(draft.submitted_at).toLocaleString()}

)} {draft.withdrawn_at && (

Withdrawn: {new Date(draft.withdrawn_at).toLocaleString()}

)}
{canSubmitDraft(draft) && ( )} {canWithdrawDraft(draft) && ( )} {canDeleteDraft(draft) && ( )}
)) )}
) }