"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 { jasonProcessor, CharacterConsistency, ItemConsistency, SeriesConsistency } from "@/services/jason-processor"
import { seriesGenerator } from "@/services/series-generator"
import { Users, Package, Palette, Settings, Eye, Edit, Trash2, Plus, CheckCircle, AlertCircle } from "lucide-react"

interface ConsistencyTrackerProps {
  seriesId?: string
  onConsistencyUpdate?: (consistency: SeriesConsistency) => void
}

export function ConsistencyTracker({ seriesId, onConsistencyUpdate }: ConsistencyTrackerProps) {
  const [consistencyProfile, setConsistencyProfile] = useState<SeriesConsistency | null>(null)
  const [characters, setCharacters] = useState<CharacterConsistency[]>([])
  const [items, setItems] = useState<ItemConsistency[]>([])
  const [activeTab, setActiveTab] = useState<'characters' | 'items' | 'colors'>('characters')
  const [isEditing, setIsEditing] = useState(false)
  const [editForm, setEditForm] = useState<{
    type: 'character' | 'item'
    data: Partial<CharacterConsistency> | Partial<ItemConsistency>
    index: number
  } | null>(null)

  useEffect(() => {
    if (seriesId) {
      loadConsistencyProfile(seriesId)
    }
  }, [seriesId])

  const loadConsistencyProfile = (seriesId: string) => {
    const series = seriesGenerator.getSeries(seriesId)
    if (series && series.images.length > 0) {
      const jasonPrompts = series.images.map(image => 
        jasonProcessor.parseJasonPrompt(image.jasonPrompt || "")
      ).filter(Boolean) as any[]

      if (jasonPrompts.length > 0) {
        const profile = jasonProcessor.extractConsistencyProfiles(jasonPrompts)
        setConsistencyProfile(profile)
        setCharacters(profile.characters)
        setItems(profile.items)
      }
    }
  }

  const addCharacter = () => {
    const newCharacter: CharacterConsistency = {
      name: "New Character",
      description: "Character description",
      features: {
        hair: "unknown",
        eyes: "unknown",
        clothing: "unknown",
        accessories: [],
        expression: "neutral",
      },
      consistency: {
        mustMaintain: ["name", "style"],
        canVary: ["pose", "expression", "position"],
        priority: "high",
      },
    }
    setCharacters(prev => [...prev, newCharacter])
    setEditForm({ type: 'character', data: newCharacter, index: characters.length })
    setIsEditing(true)
  }

  const addItem = () => {
    const newItem: ItemConsistency = {
      name: "New Item",
      description: "Item description",
      features: {
        color: "unknown",
        material: "unknown",
        size: "unknown",
      },
      consistency: {
        mustMaintain: ["name", "style"],
        canVary: ["position", "lighting", "size"],
        priority: "medium",
      },
    }
    setItems(prev => [...prev, newItem])
    setEditForm({ type: 'item', data: newItem, index: items.length })
    setIsEditing(true)
  }

  const updateCharacter = (index: number, updatedCharacter: CharacterConsistency) => {
    const newCharacters = [...characters]
    newCharacters[index] = updatedCharacter
    setCharacters(newCharacters)
  }

  const updateItem = (index: number, updatedItem: ItemConsistency) => {
    const newItems = [...items]
    newItems[index] = updatedItem
    setItems(newItems)
  }

  const removeCharacter = (index: number) => {
    setCharacters(prev => prev.filter((_, i) => i !== index))
  }

  const removeItem = (index: number) => {
    setItems(prev => prev.filter((_, i) => i !== index))
  }

  const updateConsistencyProfile = () => {
    if (characters.length > 0 || items.length > 0) {
      const profile: SeriesConsistency = {
        characters,
        items,
        colorPalette: consistencyProfile?.colorPalette || [],
        style: consistencyProfile?.style || "realistic",
        mood: consistencyProfile?.mood || "neutral",
        narrativeProgression: consistencyProfile?.narrativeProgression || {
          start: "Beginning",
          middle: "Middle",
          end: "End",
        },
      }
      setConsistencyProfile(profile)
      onConsistencyUpdate?.(profile)
    }
  }

  const saveEdit = () => {
    if (!editForm) return

    if (editForm.type === 'character') {
      updateCharacter(editForm.index, editForm.data as CharacterConsistency)
    } else {
      updateItem(editForm.index, editForm.data as ItemConsistency)
    }

    setIsEditing(false)
    setEditForm(null)
    updateConsistencyProfile()
  }

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'high': return 'text-red-600 bg-red-50'
      case 'medium': return 'text-yellow-600 bg-yellow-50'
      case 'low': return 'text-green-600 bg-green-50'
      default: return 'text-gray-600 bg-gray-50'
    }
  }

  const getPriorityIcon = (priority: string) => {
    switch (priority) {
      case 'high': return <AlertCircle className="h-3 w-3" />
      case 'medium': return <AlertCircle className="h-3 w-3" />
      case 'low': return <CheckCircle className="h-3 w-3" />
      default: return <CheckCircle className="h-3 w-3" />
    }
  }

  return (
    <div className="space-y-6">
      {/* Overview */}
      {consistencyProfile && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Settings className="h-5 w-5" />
              Consistency Overview
            </CardTitle>
            <CardDescription>
              Track character and item consistency across your image series
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid md:grid-cols-4 gap-4">
              <div className="text-center p-4 bg-muted rounded-lg">
                <Users className="h-8 w-8 mx-auto mb-2 text-primary" />
                <div className="text-2xl font-bold">{characters.length}</div>
                <div className="text-sm text-muted-foreground">Characters</div>
              </div>
              <div className="text-center p-4 bg-muted rounded-lg">
                <Package className="h-8 w-8 mx-auto mb-2 text-accent" />
                <div className="text-2xl font-bold">{items.length}</div>
                <div className="text-sm text-muted-foreground">Items</div>
              </div>
              <div className="text-center p-4 bg-muted rounded-lg">
                <Palette className="h-8 w-8 mx-auto mb-2 text-green-600" />
                <div className="text-2xl font-bold">{consistencyProfile.colorPalette.length}</div>
                <div className="text-sm text-muted-foreground">Colors</div>
              </div>
              <div className="text-center p-4 bg-muted rounded-lg">
                <Eye className="h-8 w-8 mx-auto mb-2 text-blue-600" />
                <div className="text-2xl font-bold">
                  {Math.round((characters.length + items.length) * 0.8)}%
                </div>
                <div className="text-sm text-muted-foreground">Consistency</div>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Tab Navigation */}
      <Card>
        <CardHeader>
          <CardTitle>Consistency Management</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex gap-2 mb-6">
            <Button
              variant={activeTab === 'characters' ? 'default' : 'outline'}
              onClick={() => setActiveTab('characters')}
            >
              <Users className="mr-2 h-4 w-4" />
              Characters
            </Button>
            <Button
              variant={activeTab === 'items' ? 'default' : 'outline'}
              onClick={() => setActiveTab('items')}
            >
              <Package className="mr-2 h-4 w-4" />
              Items
            </Button>
            <Button
              variant={activeTab === 'colors' ? 'default' : 'outline'}
              onClick={() => setActiveTab('colors')}
            >
              <Palette className="mr-2 h-4 w-4" />
              Colors
            </Button>
          </div>

          {/* Characters Tab */}
          {activeTab === 'characters' && (
            <div className="space-y-4">
              <div className="flex justify-between items-center">
                <h3 className="font-medium">Character Profiles</h3>
                <Button onClick={addCharacter} size="sm">
                  <Plus className="mr-2 h-4 w-4" />
                  Add Character
                </Button>
              </div>
              
              {characters.length === 0 ? (
                <div className="text-center py-8 text-muted-foreground">
                  <Users className="h-12 w-12 mx-auto mb-4 opacity-50" />
                  <p>No characters defined</p>
                  <p className="text-sm">Add characters to maintain consistency</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {characters.map((character, index) => (
                    <Card key={index} className="p-4">
                      <div className="flex justify-between items-start">
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-2">
                            <h4 className="font-medium">{character.name}</h4>
                            <span className={`px-2 py-1 rounded-full text-xs ${getPriorityColor(character.consistency.priority)}`}>
                              {getPriorityIcon(character.consistency.priority)}
                              {character.consistency.priority} priority
                            </span>
                          </div>
                          <p className="text-sm text-muted-foreground mb-3">
                            {character.description}
                          </p>
                          
                          <div className="grid md:grid-cols-2 gap-4 text-sm">
                            <div>
                              <span className="text-muted-foreground">Appearance:</span>
                              <div className="mt-1">
                                <div>Hair: {character.features.hair}</div>
                                <div>Eyes: {character.features.eyes}</div>
                                <div>Clothing: {character.features.clothing}</div>
                              </div>
                            </div>
                            <div>
                              <span className="text-muted-foreground">Consistency:</span>
                              <div className="mt-1">
                                <div>Must maintain: {character.consistency.mustMaintain.join(', ')}</div>
                                <div>Can vary: {character.consistency.canVary.join(', ')}</div>
                              </div>
                            </div>
                          </div>
                        </div>
                        
                        <div className="flex gap-1 ml-4">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => setEditForm({ type: 'character', data: character, index })}
                          >
                            <Edit className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => removeCharacter(index)}
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </div>
                    </Card>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Items Tab */}
          {activeTab === 'items' && (
            <div className="space-y-4">
              <div className="flex justify-between items-center">
                <h3 className="font-medium">Item Profiles</h3>
                <Button onClick={addItem} size="sm">
                  <Plus className="mr-2 h-4 w-4" />
                  Add Item
                </Button>
              </div>
              
              {items.length === 0 ? (
                <div className="text-center py-8 text-muted-foreground">
                  <Package className="h-12 w-12 mx-auto mb-4 opacity-50" />
                  <p>No items defined</p>
                  <p className="text-sm">Add items to maintain consistency</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {items.map((item, index) => (
                    <Card key={index} className="p-4">
                      <div className="flex justify-between items-start">
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-2">
                            <h4 className="font-medium">{item.name}</h4>
                            <span className={`px-2 py-1 rounded-full text-xs ${getPriorityColor(item.consistency.priority)}`}>
                              {getPriorityIcon(item.consistency.priority)}
                              {item.consistency.priority} priority
                            </span>
                          </div>
                          <p className="text-sm text-muted-foreground mb-3">
                            {item.description}
                          </p>
                          
                          <div className="grid md:grid-cols-2 gap-4 text-sm">
                            <div>
                              <span className="text-muted-foreground">Appearance:</span>
                              <div className="mt-1">
                                <div>Color: {item.features.color}</div>
                                <div>Material: {item.features.material}</div>
                                <div>Size: {item.features.size}</div>
                              </div>
                            </div>
                            <div>
                              <span className="text-muted-foreground">Consistency:</span>
                              <div className="mt-1">
                                <div>Must maintain: {item.consistency.mustMaintain.join(', ')}</div>
                                <div>Can vary: {item.consistency.canVary.join(', ')}</div>
                              </div>
                            </div>
                          </div>
                        </div>
                        
                        <div className="flex gap-1 ml-4">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => setEditForm({ type: 'item', data: item, index })}
                          >
                            <Edit className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => removeItem(index)}
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </div>
                    </Card>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Colors Tab */}
          {activeTab === 'colors' && (
            <div className="space-y-4">
              <h3 className="font-medium">Color Palette</h3>
              
              {consistencyProfile?.colorPalette ? (
                <div className="flex flex-wrap gap-2">
                  {consistencyProfile.colorPalette.map((color, index) => (
                    <div
                      key={index}
                      className="w-12 h-12 rounded-lg border-2 border-gray-200 flex items-center justify-center text-xs font-medium text-white"
                      style={{ backgroundColor: color }}
                    >
                      {color}
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-center py-8 text-muted-foreground">
                  <Palette className="h-12 w-12 mx-auto mb-4 opacity-50" />
                  <p>No color palette defined</p>
                  <p className="text-sm">Colors will be extracted from your prompts</p>
                </div>
              )}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Edit Modal */}
      {isEditing && editForm && (
        <Card>
          <CardHeader>
            <CardTitle>
              {editForm.type === 'character' ? 'Edit Character' : 'Edit Item'}
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <label className="text-sm font-medium mb-2 block">Name</label>
              <Input
                value={(editForm.data as any).name || ''}
                onChange={(e) => setEditForm({
                  ...editForm,
                  data: { ...editForm.data, name: e.target.value }
                })}
              />
            </div>
            
            <div>
              <label className="text-sm font-medium mb-2 block">Description</label>
              <Input
                value={(editForm.data as any).description || ''}
                onChange={(e) => setEditForm({
                  ...editForm,
                  data: { ...editForm.data, description: e.target.value }
                })}
              />
            </div>

            {editForm.type === 'character' && (
              <div className="grid md:grid-cols-2 gap-4">
                <div>
                  <label className="text-sm font-medium mb-2 block">Hair</label>
                  <Input
                    value={(editForm.data as CharacterConsistency).features.hair || ''}
                    onChange={(e) => setEditForm({
                      ...editForm,
                      data: {
                        ...editForm.data,
                        features: {
                          ...editForm.data.features,
                          hair: e.target.value
                        }
                      }
                    })}
                  />
                </div>
                <div>
                  <label className="text-sm font-medium mb-2 block">Eyes</label>
                  <Input
                    value={(editForm.data as CharacterConsistency).features.eyes || ''}
                    onChange={(e) => setEditForm({
                      ...editForm,
                      data: {
                        ...editForm.data,
                        features: {
                          ...editForm.data.features,
                          eyes: e.target.value
                        }
                      }
                    })}
                  />
                </div>
              </div>
            )}

            {editForm.type === 'item' && (
              <div className="grid md:grid-cols-3 gap-4">
                <div>
                  <label className="text-sm font-medium mb-2 block">Color</label>
                  <Input
                    value={(editForm.data as ItemConsistency).features.color || ''}
                    onChange={(e) => setEditForm({
                      ...editForm,
                      data: {
                        ...editForm.data,
                        features: {
                          ...editForm.data.features,
                          color: e.target.value
                        }
                      }
                    })}
                  />
                </div>
                <div>
                  <label className="text-sm font-medium mb-2 block">Material</label>
                  <Input
                    value={(editForm.data as ItemConsistency).features.material || ''}
                    onChange={(e) => setEditForm({
                      ...editForm,
                      data: {
                        ...editForm.data,
                        features: {
                          ...editForm.data.features,
                          material: e.target.value
                        }
                      }
                    })}
                  />
                </div>
                <div>
                  <label className="text-sm font-medium mb-2 block">Size</label>
                  <Input
                    value={(editForm.data as ItemConsistency).features.size || ''}
                    onChange={(e) => setEditForm({
                      ...editForm,
                      data: {
                        ...editForm.data,
                        features: {
                          ...editForm.data.features,
                          size: e.target.value
                        }
                      }
                    })}
                  />
                </div>
              </div>
            )}

            <div className="flex gap-2">
              <Button onClick={saveEdit}>Save</Button>
              <Button variant="outline" onClick={() => setIsEditing(false)}>Cancel</Button>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Actions */}
      <div className="flex justify-end">
        <Button onClick={updateConsistencyProfile} className="btn-primary">
          Update Consistency Profile
        </Button>
      </div>
    </div>
  )
}