import { useState } from 'react'
import { X } from 'lucide-react'
import { stepsApi } from '@/api/steps'
import { StepForm } from './StepForm'
import type { Step, StepCreate } from '@/types/step'

interface StepFormModalProps {
  isOpen: boolean
  onClose: () => void
  onSuccess: (step: Step) => void
  editingStep?: Step | null   // full Step (parent fetches before opening), null/undefined = create mode
}

export function StepFormModal({ isOpen, onClose, onSuccess, editingStep }: StepFormModalProps) {
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)

  if (!isOpen) return null

  const isEditMode = !!editingStep

  const handleSubmit = async (data: StepCreate) => {
    setIsSubmitting(true)
    setError(null)
    try {
      let result: Step
      if (isEditMode && editingStep) {
        result = await stepsApi.update(editingStep.id, data)
      } else {
        result = await stepsApi.create(data)
      }
      onSuccess(result)
    } catch (err) {
      console.error('Failed to save step:', err)
      setError('Failed to save step. Please try again.')
    } finally {
      setIsSubmitting(false)
    }
  }

  // Build initialData from full Step including content
  const initialData = editingStep ? {
    title: editingStep.title,
    step_type: editingStep.step_type,
    content: editingStep.content,
    visibility: editingStep.visibility,
    category_id: editingStep.category_id,
    tags: editingStep.tags,
  } : undefined

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-sm p-4">
      <div className="relative flex h-[90vh] w-full max-w-2xl flex-col bg-card border border-border rounded-2xl shadow-lg">
        {/* Header */}
        <div className="flex items-center justify-between border-b border-border p-6 pb-4">
          <h2 className="text-lg font-semibold text-foreground">
            {isEditMode ? 'Edit Step' : 'Create Step'}
          </h2>
          <button
            onClick={onClose}
            disabled={isSubmitting}
            className="rounded-md p-1.5 text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-50"
            aria-label="Close"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Error */}
        {error && (
          <div className="mx-6 mt-4 rounded-lg border border-red-400/20 bg-red-400/10 p-3 text-sm text-red-400">
            {error}
          </div>
        )}

        {/* Body */}
        <div className="flex-1 overflow-y-auto p-6">
          <StepForm
            onSubmit={handleSubmit}
            onCancel={onClose}
            initialData={initialData}
            submitLabel={isEditMode ? 'Save Changes' : 'Create Step'}
            isSubmitting={isSubmitting}
          />
        </div>
      </div>
    </div>
  )
}
