import { useState } from 'react'
import { X } from 'lucide-react'
import { cn } from '@/lib/utils'
import { StepForm } from './StepForm'
import { StepLibraryBrowser } from './StepLibraryBrowser'
import type { Step, StepCreate } from '@/types/step'

export interface CustomStepDraft {
  title: string
  step_type: 'decision' | 'action' | 'solution'
  content: {
    instructions: string
    help_text?: string
    commands?: Array<{
      label: string
      command: string
      command_type?: string
    }>
  }
  category_id?: string
  tags?: string[]
}

interface CustomStepModalProps {
  isOpen: boolean
  onClose: () => void
  onInsertStep: (step: Step | CustomStepDraft, isFromLibrary: boolean) => void
}

type Tab = 'create' | 'browse'

export function CustomStepModal({ isOpen, onClose, onInsertStep }: CustomStepModalProps) {
  const [activeTab, setActiveTab] = useState<Tab>('create')
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)

  if (!isOpen) return null

  const handleFormSubmit = async (data: StepCreate) => {
    setIsSubmitting(true)
    setError(null)

    try {
      // Always create a draft - saving to library is handled by PostStepActionModal
      const draft: CustomStepDraft = {
        title: data.title,
        step_type: data.step_type,
        content: data.content,
        category_id: data.category_id,
        tags: data.tags
      }
      onInsertStep(draft, false) // false = not from library (user typed it)
    } catch (err) {
      console.error('Failed to create step:', err)
      setError('Failed to create step. Please try again.')
      setIsSubmitting(false)
    }
  }

  const handleBrowserInsert = (step: Step) => {
    onInsertStep(step, true) // true = from library (already saved)
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm">
      <div className="relative flex h-[90vh] w-full max-w-4xl flex-col rounded-lg border border-border bg-card shadow-lg">
        {/* Header */}
        <div className="flex items-center justify-between border-b border-border p-4">
          <h2 className="text-lg font-semibold">Add Custom Step</h2>
          <button
            onClick={onClose}
            className="rounded-md p-1 hover:bg-accent"
            aria-label="Close"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Tabs */}
        <div className="flex border-b border-border">
          <button
            onClick={() => setActiveTab('create')}
            className={cn(
              'flex-1 px-4 py-3 text-sm font-medium transition-colors',
              activeTab === 'create'
                ? 'border-b-2 border-primary bg-primary/5 text-primary'
                : 'text-muted-foreground hover:bg-muted/50 hover:text-foreground'
            )}
          >
            Type My Own
          </button>
          <button
            onClick={() => setActiveTab('browse')}
            className={cn(
              'flex-1 px-4 py-3 text-sm font-medium transition-colors',
              activeTab === 'browse'
                ? 'border-b-2 border-primary bg-primary/5 text-primary'
                : 'text-muted-foreground hover:bg-muted/50 hover:text-foreground'
            )}
          >
            Browse Library
          </button>
        </div>

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

        {/* Tab Content */}
        <div className="flex-1 overflow-hidden">
          {activeTab === 'create' ? (
            <div className="h-full overflow-y-auto p-6">
              <StepForm
                onSubmit={handleFormSubmit}
                onCancel={onClose}
              />
            </div>
          ) : (
            <StepLibraryBrowser
              onInsert={handleBrowserInsert}
              showCreateButton={false}
            />
          )}
        </div>

        {/* Loading Overlay */}
        {isSubmitting && (
          <div className="absolute inset-0 flex items-center justify-center bg-background/80 backdrop-blur-sm">
            <div className="flex flex-col items-center gap-3">
              <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
              <p className="text-sm text-muted-foreground">Creating step...</p>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
