'use client'

import { useState, useEffect } from 'react'
import { useTranslations } from 'next-intl'
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,
  Save,
  Tag,
  Plus
} from 'lucide-react'

interface Prompt {
  id: string
  name: string
  description: string | null
  content: string
  tags: string[]
  createdAt: string
  updatedAt: string
}

interface EditPromptModalProps {
  prompt: Prompt
  isOpen: boolean
  onClose: () => void
  onSave: (updatedPrompt: Prompt) => void
  userId: string
}

export function EditPromptModal({
  prompt,
  isOpen,
  onClose,
  onSave,
  userId
}: EditPromptModalProps) {
  const t = useTranslations('studio')
  const tCommon = useTranslations('common')

  const [name, setName] = useState(prompt.name)
  const [description, setDescription] = useState(prompt.description || '')
  const [tags, setTags] = useState<string[]>(prompt.tags)
  const [newTag, setNewTag] = useState('')
  const [isSaving, setIsSaving] = useState(false)
  const [availableTags, setAvailableTags] = useState<string[]>([])

  useEffect(() => {
    if (isOpen) {
      setName(prompt.name)
      setDescription(prompt.description || '')
      // 确保tags是字符串数组
      const processedTags = Array.isArray(prompt.tags)
        ? prompt.tags.map((tag: string | { name: string }) => typeof tag === 'string' ? tag : tag.name || '')
        : []
      setTags(processedTags)
      fetchAvailableTags()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpen, prompt])

  const fetchAvailableTags = async () => {
    try {
      const response = await fetch(`/api/tags?userId=${userId}`)
      if (response.ok) {
        const tagsData = await response.json()
        setAvailableTags(tagsData.map((tag: { name: string }) => tag.name))
      }
    } catch (error) {
      console.error('Error fetching tags:', error)
    }
  }

  const handleAddTag = () => {
    if (newTag.trim() && !tags.includes(newTag.trim())) {
      setTags(prev => [...prev, newTag.trim()])
      setNewTag('')
    }
  }

  const handleRemoveTag = (tagToRemove: string) => {
    setTags(prev => prev.filter(tag => tag !== tagToRemove))
  }

  const handleSave = async () => {
    if (!name.trim()) return

    setIsSaving(true)
    try {
      const response = await fetch(`/api/prompts/${prompt.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: name.trim(),
          description: description.trim() || null,
          tags,
          userId
        })
      })

      if (response.ok) {
        const updatedPrompt = await response.json()
        onSave(updatedPrompt)
        onClose()
      }
    } catch (error) {
      console.error('Error saving prompt:', error)
    } finally {
      setIsSaving(false)
    }
  }

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
      handleSave()
    } else if (e.key === 'Escape') {
      onClose()
    }
  }

  if (!isOpen) return null

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/50 backdrop-blur-sm"
        onClick={onClose}
      />

      {/* Modal */}
      <div className="relative bg-card border border-border rounded-lg shadow-lg w-full max-w-md mx-4 max-h-[90vh] overflow-hidden sm:mx-auto">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-border">
          <h2 className="text-lg font-semibold text-foreground">
            {t('editPrompt')}
          </h2>
          <Button
            variant="ghost"
            size="sm"
            onClick={onClose}
            className="h-8 w-8 p-0"
          >
            <X className="h-4 w-4" />
          </Button>
        </div>

        {/* Content */}
        <div className="p-6 space-y-4 overflow-y-auto max-h-[calc(90vh-140px)]">
          {/* Name */}
          <div>
            <Label htmlFor="prompt-name" className="text-sm font-medium">
              {t('promptName')} *
            </Label>
            <Input
              id="prompt-name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              onKeyDown={handleKeyPress}
              placeholder={t('enterPromptName')}
              className="mt-1"
              autoFocus
            />
          </div>

          {/* Description */}
          <div>
            <Label htmlFor="prompt-description" className="text-sm font-medium">
              {t('promptDescription')}
            </Label>
            <Textarea
              id="prompt-description"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              onKeyDown={handleKeyPress}
              placeholder={t('enterPromptDescription')}
              className="mt-1 min-h-[80px] resize-none"
            />
          </div>

          {/* Tags */}
          <div>
            <Label className="text-sm font-medium flex items-center space-x-1">
              <Tag className="h-3 w-3" />
              <span>{t('tags')}</span>
            </Label>

            {/* Current Tags */}
            <div className="mt-2 flex flex-wrap gap-2">
              {tags.map((tag) => (
                <span
                  key={tag}
                  className="inline-flex items-center px-2 py-1 text-xs font-medium bg-primary/10 text-primary rounded-full"
                >
                  {tag}
                  <button
                    onClick={() => handleRemoveTag(tag)}
                    className="ml-1 hover:text-destructive"
                  >
                    <X className="h-3 w-3" />
                  </button>
                </span>
              ))}
            </div>

            {/* Add New Tag */}
            <div className="mt-2 flex items-center space-x-2">
              <Input
                value={newTag}
                onChange={(e) => setNewTag(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') {
                    e.preventDefault()
                    handleAddTag()
                  } else {
                    handleKeyPress(e)
                  }
                }}
                placeholder={t('addTag')}
                className="flex-1"
              />
              <Button
                variant="outline"
                size="sm"
                onClick={handleAddTag}
                disabled={!newTag.trim() || tags.includes(newTag.trim())}
                className="h-9 w-9 p-0"
              >
                <Plus className="h-4 w-4" />
              </Button>
            </div>

            {/* Available Tags */}
            {availableTags.length > 0 && (
              <div className="mt-2">
                <p className="text-xs text-muted-foreground mb-2">Quick add:</p>
                <div className="flex flex-wrap gap-1">
                  {availableTags
                    .filter(tag => !tags.includes(tag))
                    .slice(0, 6)
                    .map((tag) => (
                      <button
                        key={tag}
                        onClick={() => setTags(prev => [...prev, tag])}
                        className="inline-flex items-center px-2 py-1 text-xs bg-muted text-muted-foreground rounded hover:bg-muted/80 transition-colors"
                      >
                        {tag}
                      </button>
                    ))}
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end space-x-2 p-6 border-t border-border">
          <Button
            variant="outline"
            onClick={onClose}
            disabled={isSaving}
          >
            {tCommon('cancel')}
          </Button>
          <Button
            onClick={handleSave}
            disabled={!name.trim() || isSaving}
            className="flex items-center space-x-2"
          >
            {isSaving ? (
              <LoadingSpinner size="sm" />
            ) : (
              <Save className="h-4 w-4" />
            )}
            <span>{tCommon('save')}</span>
          </Button>
        </div>
      </div>
    </div>
  )
}
