'use client'

import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { LoadingSpinner } from '@/components/ui/loading-spinner'
import { X, Plus, Trash2, FileText, Tag, Type, MessageSquare } from 'lucide-react'

interface BulkPromptItem {
  id: string
  name: string
  description: string
  tags: string
  content: string
}

interface BulkAddPromptModalProps {
  isOpen: boolean
  onClose: () => void
  onSave: (prompts: BulkPromptItem[]) => Promise<void>
  userId: string
}

export function BulkAddPromptModal({ isOpen, onClose, onSave }: BulkAddPromptModalProps) {
  const [prompts, setPrompts] = useState<BulkPromptItem[]>([
    { id: '1', name: '', description: '', tags: '', content: '' }
  ])
  const [isLoading, setIsLoading] = useState(false)
  const [errors, setErrors] = useState<{[key: string]: string}>({})

  const addPrompt = () => {
    const newId = (prompts.length + 1).toString()
    setPrompts(prev => [...prev, { id: newId, name: '', description: '', tags: '', content: '' }])
  }

  const removePrompt = (id: string) => {
    if (prompts.length > 1) {
      setPrompts(prev => prev.filter(p => p.id !== id))
      // Clear errors for removed prompt
      setErrors(prev => {
        const newErrors = { ...prev }
        delete newErrors[`${id}-name`]
        delete newErrors[`${id}-content`]
        return newErrors
      })
    }
  }

  const updatePrompt = (id: string, field: keyof BulkPromptItem, value: string) => {
    setPrompts(prev => prev.map(p => p.id === id ? { ...p, [field]: value } : p))
    // Clear error for this field when user starts typing
    const errorKey = `${id}-${field}`
    if (errors[errorKey]) {
      setErrors(prev => {
        const newErrors = { ...prev }
        delete newErrors[errorKey]
        return newErrors
      })
    }
  }

  const validatePrompts = () => {
    const newErrors: {[key: string]: string} = {}
    let isValid = true

    prompts.forEach(prompt => {
      if (!prompt.name.trim()) {
        newErrors[`${prompt.id}-name`] = 'Name is required'
        isValid = false
      }
      if (!prompt.content.trim()) {
        newErrors[`${prompt.id}-content`] = 'Content is required'
        isValid = false
      }
    })

    setErrors(newErrors)
    return isValid
  }

  const handleSave = async () => {
    if (!validatePrompts()) {
      return
    }

    try {
      setIsLoading(true)
      await onSave(prompts)
      onClose()
      // Reset form
      setPrompts([{ id: '1', name: '', description: '', tags: '', content: '' }])
      setErrors({})
    } catch (error) {
      console.error('Error saving prompts:', error)
    } finally {
      setIsLoading(false)
    }
  }

  const handleClose = () => {
    onClose()
    // Reset form
    setPrompts([{ id: '1', name: '', description: '', tags: '', content: '' }])
    setErrors({})
  }

  if (!isOpen) return null

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-background rounded-xl border border-border max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-border">
          <div className="flex items-center space-x-3">
            <div className="p-2 bg-primary/10 rounded-lg">
              <FileText className="h-5 w-5 text-primary" />
            </div>
            <div>
              <h2 className="text-xl font-semibold text-foreground">Bulk Add Prompts</h2>
              <p className="text-sm text-muted-foreground">Add multiple prompts at once. Use commas to separate tags.</p>
            </div>
          </div>
          <Button variant="ghost" size="sm" onClick={handleClose} disabled={isLoading}>
            <X className="h-4 w-4" />
          </Button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6 space-y-6">
          {prompts.map((prompt, index) => (
            <div key={prompt.id} className="bg-card rounded-lg border border-border p-4 space-y-4">
              {/* Header */}
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                  <span className="text-sm font-medium text-muted-foreground bg-muted px-2 py-1 rounded-full">
                    #{index + 1}
                  </span>
                  <span className="text-sm text-muted-foreground">Prompt</span>
                </div>
                {prompts.length > 1 && (
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => removePrompt(prompt.id)}
                    className="text-destructive hover:text-destructive hover:bg-destructive/10"
                    disabled={isLoading}
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                )}
              </div>

              {/* Form Fields */}
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                {/* Name */}
                <div className="space-y-2">
                  <Label htmlFor={`name-${prompt.id}`} className="flex items-center space-x-2">
                    <Type className="h-4 w-4 text-muted-foreground" />
                    <span>Name *</span>
                  </Label>
                  <Input
                    id={`name-${prompt.id}`}
                    value={prompt.name}
                    onChange={(e) => updatePrompt(prompt.id, 'name', e.target.value)}
                    placeholder="Enter prompt name"
                    className={errors[`${prompt.id}-name`] ? 'border-destructive' : ''}
                    disabled={isLoading}
                  />
                  {errors[`${prompt.id}-name`] && (
                    <p className="text-xs text-destructive">{errors[`${prompt.id}-name`]}</p>
                  )}
                </div>

                {/* Tags */}
                <div className="space-y-2">
                  <Label htmlFor={`tags-${prompt.id}`} className="flex items-center space-x-2">
                    <Tag className="h-4 w-4 text-muted-foreground" />
                    <span>Tags</span>
                  </Label>
                  <Input
                    id={`tags-${prompt.id}`}
                    value={prompt.tags}
                    onChange={(e) => updatePrompt(prompt.id, 'tags', e.target.value)}
                    placeholder="tag1, tag2, tag3"
                    disabled={isLoading}
                  />
                  <p className="text-xs text-muted-foreground">Separate tags with commas</p>
                </div>
              </div>

              {/* Description */}
              <div className="space-y-2">
                <Label htmlFor={`description-${prompt.id}`} className="flex items-center space-x-2">
                  <MessageSquare className="h-4 w-4 text-muted-foreground" />
                  <span>Description</span>
                </Label>
                <Textarea
                  id={`description-${prompt.id}`}
                  value={prompt.description}
                  onChange={(e) => updatePrompt(prompt.id, 'description', e.target.value)}
                  placeholder="Brief description of this prompt"
                  className="min-h-[60px]"
                  disabled={isLoading}
                />
              </div>

              {/* Content */}
              <div className="space-y-2">
                <Label htmlFor={`content-${prompt.id}`} className="flex items-center space-x-2">
                  <FileText className="h-4 w-4 text-muted-foreground" />
                  <span>Prompt Content *</span>
                </Label>
                <Textarea
                  id={`content-${prompt.id}`}
                  value={prompt.content}
                  onChange={(e) => updatePrompt(prompt.id, 'content', e.target.value)}
                  placeholder="Enter your prompt content here..."
                  className={`min-h-[120px] ${errors[`${prompt.id}-content`] ? 'border-destructive' : ''}`}
                  disabled={isLoading}
                />
                {errors[`${prompt.id}-content`] && (
                  <p className="text-xs text-destructive">{errors[`${prompt.id}-content`]}</p>
                )}
              </div>
            </div>
          ))}

          {/* Add More Button */}
          <Button
            variant="outline"
            onClick={addPrompt}
            className="w-full border-dashed border-2 hover:border-primary/50 hover:bg-primary/5 py-8"
            disabled={isLoading}
          >
            <Plus className="h-5 w-5 mr-2" />
            Add Another Prompt
          </Button>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between p-6 border-t border-border bg-muted/30">
          <div className="text-sm text-muted-foreground">
            {prompts.length} prompt{prompts.length !== 1 ? 's' : ''} ready to add
          </div>
          <div className="flex items-center space-x-3">
            <Button variant="outline" onClick={handleClose} disabled={isLoading}>
              Cancel
            </Button>
            <Button onClick={handleSave} disabled={isLoading}>
              {isLoading ? (
                <>
                  <LoadingSpinner size="sm" className="mr-2" />
                  Adding Prompts...
                </>
              ) : (
                <>
                  <Plus className="h-4 w-4 mr-2" />
                  Add {prompts.length} Prompt{prompts.length !== 1 ? 's' : ''}
                </>
              )}
            </Button>
          </div>
        </div>
      </div>
    </div>
  )
}