import { useState } from 'react'
import { experimentPhaseManagement } from '../lib/supabase'
import type { CreateExperimentPhaseRequest, ExperimentPhase } from '../lib/supabase'
import { PhaseForm } from './PhaseForm'

interface PhaseModalProps {
    onClose: () => void
    onPhaseCreated: (phase: ExperimentPhase) => void
}

export function PhaseModal({ onClose, onPhaseCreated }: PhaseModalProps) {
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState<string | null>(null)

    const handleSubmit = async (formData: CreateExperimentPhaseRequest) => {
        try {
            setLoading(true)
            setError(null)

            const newPhase = await experimentPhaseManagement.createExperimentPhase(formData)
            onPhaseCreated(newPhase)
            onClose()
        } catch (err: any) {
            setError(err.message || 'Failed to create experiment phase')
            console.error('Create phase error:', err)
        } finally {
            setLoading(false)
        }
    }

    return (
        <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
            <div className="relative top-20 mx-auto p-5 border w-11/12 md:w-2/3 lg:w-1/2 shadow-lg rounded-md bg-white">
                <div className="mt-3">
                    {/* Header */}
                    <div className="flex items-center justify-between mb-6">
                        <h3 className="text-lg font-medium text-gray-900">
                            Create New Experiment Phase
                        </h3>
                        <button
                            onClick={onClose}
                            className="text-gray-400 hover:text-gray-600"
                        >
                            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                            </svg>
                        </button>
                    </div>

                    {/* Error Message */}
                    {error && (
                        <div className="mb-4 rounded-md bg-red-50 p-4">
                            <div className="text-sm text-red-700">{error}</div>
                        </div>
                    )}

                    {/* Form */}
                    <PhaseForm
                        onSubmit={handleSubmit}
                        onCancel={onClose}
                        loading={loading}
                    />
                </div>
            </div>
        </div>
    )
}

