'use client'

import { useState, useEffect } from 'react'
import { useTranslations } from 'next-intl'
import { useAuth } from '@/hooks/useAuth'
import { useRouter } from 'next/navigation'
import { Header } from '@/components/layout/Header'
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 { FullScreenLoading } from '@/components/ui/full-screen-loading'
import {
  ArrowLeft,
  Save,
  Tag,
  X
} from 'lucide-react'

export default function NewPromptPage() {
  const { user, loading } = useAuth()
  const router = useRouter()
  const t = useTranslations('studio')
  const tCommon = useTranslations('common')

  const [promptName, setPromptName] = useState('')
  const [promptDescription, setPromptDescription] = useState('')
  const [promptContent, setPromptContent] = useState('')
  const [tags, setTags] = useState<string[]>([])
  const [newTag, setNewTag] = useState('')
  const [isSaving, setIsSaving] = useState(false)
  const [availableTags, setAvailableTags] = useState<string[]>([])

  useEffect(() => {
    if (!loading && !user) {
      router.push('/signin')
      return
    }

    if (!user) return

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

    fetchAvailableTags()
  }, [user, loading, router])



  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 handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      e.preventDefault()
      handleAddTag()
    }
  }

  const handleSave = async () => {
    if (!user || !promptName.trim() || !promptContent.trim()) {
      return
    }

    setIsSaving(true)
    try {
      const response = await fetch('/api/prompts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: promptName.trim(),
          description: promptDescription.trim() || null,
          content: promptContent.trim(),
          tags,
          userId: user.id
        })
      })

      if (response.ok) {
        const newPrompt = await response.json()
        router.push(`/studio/${newPrompt.id}`)
      } else {
        console.error('Failed to create prompt')
      }
    } catch (error) {
      console.error('Failed to create prompt:', error)
    } finally {
      setIsSaving(false)
    }
  }

  if (loading) {
    return <FullScreenLoading isVisible={true} message={t('loadingStudio')} />
  }

  if (!user) {
    return null
  }

  return (
    <div className="min-h-screen">
      <Header />

      <div className="border-b">
        <div className="max-w-4xl mx-auto px-4 py-4">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div className="flex flex-col sm:flex-row sm:items-center gap-3 sm:gap-4">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => router.back()}
                className="flex items-center space-x-2 self-start"
              >
                <ArrowLeft className="h-4 w-4" />
                <span className="hidden sm:inline">{t('backToList')}</span>
                <span className="sm:hidden">Back</span>
              </Button>
              <div>
                <h1 className="text-xl sm:text-2xl font-bold text-foreground">{t('newPrompt')}</h1>
                <p className="text-sm text-muted-foreground">Create a new AI prompt</p>
              </div>
            </div>

            <div className="flex items-center gap-2 order-first sm:order-last">
              <Button
                variant="outline"
                size="sm"
                onClick={() => router.back()}
                disabled={isSaving}
                className="flex-1 sm:flex-none h-10"
              >
                {tCommon('cancel')}
              </Button>

              <Button
                size="sm"
                onClick={handleSave}
                disabled={isSaving || !promptName.trim()}
                className="flex items-center space-x-2 flex-1 sm:flex-none h-10"
              >
                {isSaving ? (
                  <LoadingSpinner size="sm" className="mr-2" />
                ) : (
                  <Save className="h-4 w-4 mr-2" />
                )}
                {tCommon('save')}
              </Button>
            </div>
          </div>
        </div>
      </div>

      <div className="max-w-4xl mx-auto px-4 py-6 sm:py-8">
        <div className="space-y-4 sm:space-y-6">
          {/* Basic Information */}
          <div className="bg-card rounded-lg border border-border p-4 sm:p-6">
            <h2 className="text-base sm:text-lg font-semibold text-foreground mb-4">Basic Information</h2>

            <div className="space-y-4">
              <div>
                <Label htmlFor="promptName">{t('promptName')} *</Label>
                <Input
                  id="promptName"
                  value={promptName}
                  onChange={(e) => setPromptName(e.target.value)}
                  placeholder={t('enterPromptName')}
                  className="mt-1"
                  required
                />
              </div>

              <div>
                <Label htmlFor="promptDescription">{t('promptDescription')}</Label>
                <Input
                  id="promptDescription"
                  value={promptDescription}
                  onChange={(e) => setPromptDescription(e.target.value)}
                  placeholder={t('enterPromptDescription')}
                  className="mt-1"
                />
              </div>
            </div>
          </div>

          {/* Tags */}
          <div className="bg-card rounded-lg border border-border p-4 sm:p-6">
            <h2 className="text-base sm:text-lg font-semibold text-foreground mb-4">{t('tags')}</h2>

            <div className="space-y-4">
              <div className="flex flex-col sm:flex-row gap-2">
                <Input
                  value={newTag}
                  onChange={(e) => setNewTag(e.target.value)}
                  onKeyDown={handleKeyDown}
                  placeholder={t('addTag')}
                  className="flex-1 h-10"
                />
                <Button
                  type="button"
                  onClick={handleAddTag}
                  disabled={!newTag.trim() || tags.includes(newTag.trim())}
                  className="h-10 sm:w-auto w-full"
                >
                  <Tag className="h-4 w-4 mr-2" />
                  <span className="hidden sm:inline">{t('addTag')}</span>
                  <span className="sm:hidden">Add</span>
                </Button>
              </div>

              {tags.length > 0 && (
                <div className="flex flex-wrap gap-2">
                  {tags.map((tag) => (
                    <span
                      key={tag}
                      className="inline-flex items-center px-3 py-1 text-sm font-medium bg-primary text-primary-foreground rounded-full"
                    >
                      {tag}
                      <button
                        type="button"
                        onClick={() => handleRemoveTag(tag)}
                        className="ml-2 hover:text-primary-foreground/80"
                      >
                        <X className="h-3 w-3" />
                      </button>
                    </span>
                  ))}
                </div>
              )}

              {/* Available Tags */}
              {availableTags.length > 0 && (
                <div className="mt-4">
                  <p className="text-sm text-muted-foreground mb-2">Quick add from existing tags:</p>
                  <div className="flex flex-wrap gap-1.5 sm:gap-2">
                    {availableTags
                      .filter(tag => !tags.includes(tag))
                      .slice(0, 8)
                      .map((tag) => (
                        <button
                          key={tag}
                          type="button"
                          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>

          {/* Prompt Content */}
          <div className="bg-card rounded-lg border border-border p-4 sm:p-6">
            <h2 className="text-base sm:text-lg font-semibold text-foreground mb-4">{t('promptContent')}</h2>

            <div>
              <Label htmlFor="promptContent">Content</Label>
              <Textarea
                id="promptContent"
                value={promptContent}
                onChange={(e) => setPromptContent(e.target.value)}
                placeholder="Enter your prompt here..."
                className="mt-1 min-h-[200px] sm:min-h-[300px] font-mono text-sm"
              />
              <p className="text-xs text-muted-foreground mt-2">
                Write your prompt instructions here. You can use variables like {'{variable}'} for dynamic content.
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}