import { useEffect, useState } from 'react'
import type { CreateExperimentPhaseRequest, MachineType } from '../lib/supabase'
import { machineTypeManagement } from '../lib/supabase'

interface PhaseFormProps {
    onSubmit: (data: CreateExperimentPhaseRequest) => void
    onCancel: () => void
    loading?: boolean
}

export function PhaseForm({ onSubmit, onCancel, loading = false }: PhaseFormProps) {
    const [formData, setFormData] = useState<CreateExperimentPhaseRequest>({
        name: '',
        description: '',
        has_soaking: false,
        has_airdrying: false,
        has_cracking: false,
        has_shelling: false
    })
    const [errors, setErrors] = useState<Record<string, string>>({})
    const [machineTypes, setMachineTypes] = useState<MachineType[]>([])
    const [machinesLoading, setMachinesLoading] = useState(false)
    const [selectedCrackingMachineId, setSelectedCrackingMachineId] = useState<string | undefined>(undefined)

    useEffect(() => {
        // Preload machine types for cracking selection
        const loadMachines = async () => {
            try {
                setMachinesLoading(true)
                const types = await machineTypeManagement.getAllMachineTypes()
                setMachineTypes(types)
            } catch (e) {
                // Non-fatal: we will show no options if it fails
                console.warn('Failed to load machine types', e)
            } finally {
                setMachinesLoading(false)
            }
        }
        loadMachines()
    }, [])

    const validateForm = (): boolean => {
        const newErrors: Record<string, string> = {}

        // Name is required
        if (!formData.name.trim()) {
            newErrors.name = 'Phase name is required'
        }

        // At least one phase must be selected
        if (!formData.has_soaking && !formData.has_airdrying && !formData.has_cracking && !formData.has_shelling) {
            newErrors.phases = 'At least one phase must be selected'
        }

        // If cracking is enabled, require a machine selection
        if (formData.has_cracking && !selectedCrackingMachineId) {
            newErrors.cracking_machine_type_id = 'Select a cracking machine'
        }

        setErrors(newErrors)
        return Object.keys(newErrors).length === 0
    }

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault()
        if (validateForm()) {
            // Include cracking machine selection in payload when cracking is enabled
            const payload: CreateExperimentPhaseRequest = formData.has_cracking
                ? { ...formData, cracking_machine_type_id: selectedCrackingMachineId }
                : formData
            onSubmit(payload)
        }
    }

    const handleInputChange = (field: keyof CreateExperimentPhaseRequest, value: string | boolean | undefined) => {
        setFormData(prev => ({
            ...prev,
            [field]: value
        }))

        // Clear error when user starts typing
        if (errors[field]) {
            setErrors(prev => ({
                ...prev,
                [field]: ''
            }))
        }
    }

    const phaseOptions = [
        {
            key: 'has_soaking' as const,
            label: 'Soaking',
            description: 'Initial soaking process for pecans',
            icon: '🌰'
        },
        {
            key: 'has_airdrying' as const,
            label: 'Air-Drying',
            description: 'Post-soak air-drying process',
            icon: '💨'
        },
        {
            key: 'has_cracking' as const,
            label: 'Cracking',
            description: 'Pecan shell cracking process',
            icon: '🔨'
        },
        {
            key: 'has_shelling' as const,
            label: 'Shelling',
            description: 'Final shelling and yield measurement',
            icon: '📊'
        }
    ]

    return (
        <form onSubmit={handleSubmit} className="space-y-6">
            {/* Phase Name */}
            <div>
                <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-2">
                    Phase Name *
                </label>
                <input
                    type="text"
                    id="name"
                    value={formData.name}
                    onChange={(e) => handleInputChange('name', e.target.value)}
                    className={`w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${errors.name ? 'border-red-300' : 'border-gray-300'
                        }`}
                    placeholder="Enter phase name (e.g., 'Full Process Experiment')"
                    disabled={loading}
                />
                {errors.name && (
                    <p className="mt-1 text-sm text-red-600">{errors.name}</p>
                )}
            </div>

            {/* Description */}
            <div>
                <label htmlFor="description" className="block text-sm font-medium text-gray-700 mb-2">
                    Description
                </label>
                <textarea
                    id="description"
                    value={formData.description || ''}
                    onChange={(e) => handleInputChange('description', e.target.value)}
                    rows={3}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
<<<<<<< HEAD
                    placeholder="Optional description of this experiment phase"
=======
                    placeholder="Optional description of this experiment book"
>>>>>>> old-github/main
                    disabled={loading}
                />
            </div>

            {/* Phase Selection */}
            <div>
                <label className="block text-sm font-medium text-gray-700 mb-3">
                    Select Phases *
                </label>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {phaseOptions.map((option) => (
                        <div
                            key={option.key}
                            className={`relative border rounded-lg p-4 cursor-pointer transition-colors ${formData[option.key]
                                ? 'border-blue-500 bg-blue-50'
                                : 'border-gray-300 hover:border-gray-400'
                                }`}
                            onClick={() => {
                                const newVal = !formData[option.key]
                                handleInputChange(option.key, newVal)
                                if (option.key === 'has_cracking' && !newVal) {
                                    setSelectedCrackingMachineId(undefined)
                                }
                            }}
                        >
                            <div className="flex items-start">
                                <div className="flex-shrink-0">
                                    <input
                                        type="checkbox"
                                        checked={formData[option.key]}
                                        onChange={(e) => {
                                            const newVal = e.target.checked
                                            handleInputChange(option.key, newVal)
                                            if (option.key === 'has_cracking' && !newVal) {
                                                setSelectedCrackingMachineId(undefined)
                                            }
                                        }}
                                        className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                                        disabled={loading}
                                    />
                                </div>
                                <div className="ml-3 flex-1">
                                    <div className="flex items-center">
                                        <span className="text-2xl mr-2">{option.icon}</span>
                                        <span className="text-sm font-medium text-gray-900">
                                            {option.label}
                                        </span>
                                    </div>
                                    <p className="text-xs text-gray-500 mt-1">
                                        {option.description}
                                    </p>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
                {errors.phases && (
                    <p className="mt-2 text-sm text-red-600">{errors.phases}</p>
                )}
            </div>

            {/* Cracking machine selection */}
            {formData.has_cracking && (
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                        Select Cracking Machine *
                    </label>
                    <div className="max-w-sm">
                        <select
                            value={selectedCrackingMachineId || ''}
                            onChange={(e) => setSelectedCrackingMachineId(e.target.value || undefined)}
                            className={`w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${errors.cracking_machine_type_id ? 'border-red-300' : 'border-gray-300'}`}
                            disabled={loading || machinesLoading}
                        >
                            <option value="">{machinesLoading ? 'Loading...' : 'Select machine'}</option>
                            {machineTypes.map(mt => (
                                <option key={mt.id} value={mt.id}>{mt.name}</option>
                            ))}
                        </select>
                    </div>
                    {errors.cracking_machine_type_id && (
                        <p className="mt-1 text-sm text-red-600">{errors.cracking_machine_type_id}</p>
                    )}
                </div>
            )}

            {/* Selected Phases Summary */}
            {Object.values(formData).some(value => typeof value === 'boolean' && value) && (
                <div className="bg-gray-50 rounded-lg p-4">
                    <h4 className="text-sm font-medium text-gray-900 mb-2">Selected Phases:</h4>
                    <div className="flex flex-wrap gap-2">
                        {phaseOptions
                            .filter(option => formData[option.key])
                            .map(option => (
                                <span
                                    key={option.key}
                                    className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800"
                                >
                                    {option.icon} {option.label}
                                </span>
                            ))
                        }
                    </div>
                </div>
            )}

            {/* Form Actions */}
            <div className="flex justify-end space-x-3 pt-6 border-t border-gray-200">
                <button
                    type="button"
                    onClick={onCancel}
                    className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                    disabled={loading}
                >
                    Cancel
                </button>
                <button
                    type="submit"
                    className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
                    disabled={loading}
                >
                    {loading ? (
                        <div className="flex items-center">
                            <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                            </svg>
                            Creating...
                        </div>
                    ) : (
                        'Create Phase'
                    )}
                </button>
            </div>
        </form>
    )
}

