"use client"

import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { seriesGenerator, GeneratedSeries, SeriesConfig } from "@/services/series-generator"
import { jasonProcessor } from "@/services/jason-processor"
import { Plus, Play, Pause, Trash2, Download, Share, Settings, Sparkles, Image as ImageIcon } from "lucide-react"

interface SeriesManagerProps {
  onSeriesSelect?: (series: GeneratedSeries) => void
  onImageGenerate?: (seriesId: string) => void
}

export function SeriesManager({ onSeriesSelect, onImageGenerate }: SeriesManagerProps) {
  const [series, setSeries] = useState<GeneratedSeries[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [selectedSeries, setSelectedSeries] = useState<GeneratedSeries | null>(null)
  const [isGenerating, setIsGenerating] = useState(false)
  const [newSeriesTitle, setNewSeriesTitle] = useState("")
  const [newSeriesDescription, setNewSeriesDescription] = useState("")
  const [newSeriesCount, setNewSeriesCount] = useState(5)
  const [newSeriesStyle, setNewSeriesStyle] = useState("realistic")

  useEffect(() => {
    loadSeries()
  }, [])

  const loadSeries = () => {
    const savedSeries = seriesGenerator.getAllSeries()
    setSeries(savedSeries)
  }

  const createNewSeries = async () => {
    if (!newSeriesTitle || !newSeriesDescription) {
      return
    }

    setIsLoading(true)
    
    try {
      const config: SeriesConfig = {
        id: `config-${Date.now()}`,
        title: newSeriesTitle,
        description: newSeriesDescription,
        imageCount: newSeriesCount,
        style: newSeriesStyle,
        prompts: [], // Will be populated later
      }

      const newSeries = await seriesGenerator.createSeries(
        "A new series based on the concept",
        config
      )

      setSeries(prev => [newSeries, ...prev])
      setSelectedSeries(newSeries)
      
      // Reset form
      setNewSeriesTitle("")
      setNewSeriesDescription("")
      setNewSeriesCount(5)
      setNewSeriesStyle("realistic")
      
    } catch (error) {
      console.error('Failed to create series:', error)
    } finally {
      setIsLoading(false)
    }
  }

  const generateImagesForSeries = async (seriesId: string) => {
    setIsGenerating(true)
    
    try {
      await onImageGenerate?.(seriesId)
      
      // Simulate image generation
      setTimeout(() => {
        const generatedSeries = seriesGenerator.getSeries(seriesId)
        if (generatedSeries) {
          setSeries(prev => prev.map(s => s.id === seriesId ? generatedSeries : s))
        }
        setIsGenerating(false)
      }, 3000) // Simulate generation time
      
    } catch (error) {
      console.error('Failed to generate images:', error)
      setIsGenerating(false)
    }
  }

  const deleteSeries = (seriesId: string) => {
    seriesGenerator.deleteSeries(seriesId)
    setSeries(prev => prev.filter(s => s.id !== seriesId))
    if (selectedSeries?.id === seriesId) {
      setSelectedSeries(null)
    }
  }

  const exportSeries = (series: GeneratedSeries) => {
    const exportData = {
      config: series.config,
      images: series.images,
      exportDate: new Date().toISOString(),
    }

    const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${series.config.title.replace(/\s+/g, '_')}_series.json`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }

  const shareSeries = (series: GeneratedSeries) => {
    const shareData = {
      title: series.config.title,
      description: series.config.description,
      imageCount: series.config.imageCount,
      style: series.config.style,
      prompts: series.config.prompts,
    }

    if (navigator.share) {
      navigator.share({
        title: shareData.title,
        text: `${shareData.description} - ${shareData.imageCount} images in ${shareData.style} style`,
        url: window.location.href,
      })
    } else {
      // Fallback: copy to clipboard
      const shareText = `${shareData.title}\n${shareData.description}\n${shareData.imageCount} images in ${shareData.style} style\n\nPrompts:\n${shareData.prompts.join('\n')}`
      navigator.clipboard.writeText(shareText)
    }
  }

  const commonStyles = [
    "realistic", "anime", "cartoon", "fantasy", 
    "cyberpunk", "artistic", "painterly", "photorealistic"
  ]

  return (
    <div className="space-y-6">
      {/* Create New Series */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Plus className="h-5 w-5" />
            Create New Series
          </CardTitle>
          <CardDescription>
            Configure your image series with up to 30 images
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid md:grid-cols-2 gap-4">
            <div>
              <label className="text-sm font-medium mb-2 block">
                Series Title
              </label>
              <Input
                placeholder="Enter series title..."
                value={newSeriesTitle}
                onChange={(e) => setNewSeriesTitle(e.target.value)}
              />
            </div>
            <div>
              <label className="text-sm font-medium mb-2 block">
                Image Count
              </label>
              <Input
                type="number"
                min="1"
                max="30"
                value={newSeriesCount}
                onChange={(e) => setNewSeriesCount(parseInt(e.target.value))}
              />
            </div>
          </div>
          
          <div>
            <label className="text-sm font-medium mb-2 block">
              Description
            </label>
            <Input
              placeholder="Describe your series concept..."
              value={newSeriesDescription}
              onChange={(e) => setNewSeriesDescription(e.target.value)}
            />
          </div>

          <div>
            <label className="text-sm font-medium mb-2 block">
              Art Style
            </label>
            <div className="flex flex-wrap gap-2">
              {commonStyles.map(s => (
                <button
                  key={s}
                  className={`px-3 py-1 rounded-full text-sm transition-colors ${
                    newSeriesStyle === s 
                      ? "bg-primary text-primary-foreground" 
                      : "bg-muted hover:bg-muted/80"
                  }`}
                  onClick={() => setNewSeriesStyle(s)}
                >
                  {s}
                </button>
              ))}
            </div>
          </div>

          <Button 
            onClick={createNewSeries} 
            className="btn-primary"
            disabled={isLoading || !newSeriesTitle || !newSeriesDescription}
          >
            <Sparkles className="mr-2 h-4 w-4" />
            {isLoading ? "Creating..." : "Create Series"}
          </Button>
        </CardContent>
      </Card>

      {/* Series List */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <ImageIcon className="h-5 w-5" />
            My Series
          </CardTitle>
          <CardDescription>
            Manage your image series projects
          </CardDescription>
        </CardHeader>
        <CardContent>
          {series.length === 0 ? (
            <div className="text-center py-8 text-muted-foreground">
              <ImageIcon className="h-12 w-12 mx-auto mb-4 opacity-50" />
              <p>No series created yet</p>
              <p className="text-sm">Create your first series to get started</p>
            </div>
          ) : (
            <div className="grid md:grid-cols-1 lg:grid-cols-2 gap-4">
              {series.map((s) => (
                <Card 
                  key={s.id} 
                  className={`cursor-pointer transition-all hover:shadow-lg ${
                    selectedSeries?.id === s.id ? 'ring-2 ring-primary' : ''
                  }`}
                  onClick={() => setSelectedSeries(s)}
                >
                  <CardContent className="p-4">
                    <div className="flex justify-between items-start mb-3">
                      <div>
                        <h3 className="font-medium">{s.config.title}</h3>
                        <p className="text-sm text-muted-foreground">
                          {s.config.imageCount} images • {s.config.style} style
                        </p>
                      </div>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={(e) => {
                          e.stopPropagation()
                          deleteSeries(s.id)
                        }}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                    
                    <p className="text-sm mb-3 line-clamp-2">
                      {s.config.description}
                    </p>
                    
                    <div className="flex justify-between items-center">
                      <div className="text-xs text-muted-foreground">
                        {s.images.length > 0 
                          ? `${s.images.length}/${s.config.imageCount} images generated`
                          : 'Not generated'
                        }
                      </div>
                      
                      <div className="flex gap-1">
                        {s.images.length === 0 && (
                          <Button
                            size="sm"
                            onClick={(e) => {
                              e.stopPropagation()
                              generateImagesForSeries(s.id)
                            }}
                            disabled={isGenerating}
                          >
                            {isGenerating ? (
                              <div className="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent" />
                            ) : (
                              <Play className="h-4 w-4" />
                            )}
                          </Button>
                        )}
                        
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={(e) => {
                            e.stopPropagation()
                            exportSeries(s)
                          }}
                        >
                          <Download className="h-3 w-3" />
                        </Button>
                        
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={(e) => {
                            e.stopPropagation()
                            shareSeries(s)
                          }}
                        >
                          <Share className="h-3 w-3" />
                        </Button>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Selected Series Details */}
      {selectedSeries && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              <span>{selectedSeries.config.title}</span>
              <Button variant="outline" size="sm">
                <Settings className="h-4 w-4" />
              </Button>
            </CardTitle>
            <CardDescription>
              {selectedSeries.config.description}
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid md:grid-cols-3 gap-4 text-sm">
              <div>
                <span className="text-muted-foreground">Images:</span>
                <span className="ml-2 font-medium">
                  {selectedSeries.images.length}/{selectedSeries.config.imageCount}
                </span>
              </div>
              <div>
                <span className="text-muted-foreground">Style:</span>
                <span className="ml-2 font-medium">{selectedSeries.config.style}</span>
              </div>
              <div>
                <span className="text-muted-foreground">Created:</span>
                <span className="ml-2 font-medium">
                  {new Date(selectedSeries.createdAt).toLocaleDateString()}
                </span>
              </div>
            </div>

            {/* Progress */}
            <div>
              <div className="flex justify-between text-sm mb-2">
                <span>Generation Progress</span>
                <span>{Math.round((selectedSeries.images.length / selectedSeries.config.imageCount) * 100)}%</span>
              </div>
              <div className="w-full bg-muted rounded-full h-2">
                <div 
                  className="bg-primary h-2 rounded-full transition-all duration-300"
                  style={{ 
                    width: `${(selectedSeries.images.length / selectedSeries.config.imageCount) * 100}%` 
                  }}
                />
              </div>
            </div>

            {/* Action Buttons */}
            <div className="flex gap-2">
              {selectedSeries.images.length < selectedSeries.config.imageCount && (
                <Button
                  onClick={() => generateImagesForSeries(selectedSeries.id)}
                  disabled={isGenerating}
                  className="btn-primary"
                >
                  {isGenerating ? (
                    <>
                      <div className="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent mr-2" />
                      Generating...
                    </>
                  ) : (
                    <>
                      <Play className="mr-2 h-4 w-4" />
                      Continue Generation
                    </>
                  )}
                </Button>
              )}
              
              <Button variant="outline" onClick={() => onSeriesSelect?.(selectedSeries)}>
                View Details
              </Button>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  )
}