'use client'

import { useState, useEffect } from 'react'
import { Button } from './ui/button'
import { Input } from './ui/input'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from './ui/dialog'
import { Tag, X, Plus, Palette, AlertCircle, Sparkles } from 'lucide-react'
import { LABEL_COLORS, LabelColorName } from '@/lib/types'
import { cn } from '@/lib/utils'
import { useNotebooks } from '@/context/notebooks-context'
import { useLanguage } from '@/lib/i18n'

interface LabelManagerProps {
  existingLabels: string[]
  notebookId?: string | null
  onUpdate: (labels: string[]) => void
}

export function LabelManager({ existingLabels, notebookId, onUpdate }: LabelManagerProps) {
  const { labels, loading, addLabel, updateLabel, deleteLabel, getLabelColor } = useNotebooks()
  const { t } = useLanguage()
  const [open, setOpen] = useState(false)
  const [newLabel, setNewLabel] = useState('')
  const [selectedLabels, setSelectedLabels] = useState<string[]>(existingLabels)
  const [editingColor, setEditingColor] = useState<string | null>(null)
  const [errorMessage, setErrorMessage] = useState<string | null>(null)

  useEffect(() => {
    setSelectedLabels(existingLabels)
  }, [existingLabels])

  const handleAddLabel = async () => {
    const trimmed = newLabel.trim()
    setErrorMessage(null)

    if (trimmed && !selectedLabels.includes(trimmed)) {
      try {
        const existingLabel = labels.find(l => l.name === trimmed)
        const color = existingLabel?.color || (Object.keys(LABEL_COLORS) as LabelColorName[])[Math.floor(Math.random() * Object.keys(LABEL_COLORS).length)]

        await addLabel(trimmed, color)
        const updated = [...selectedLabels, trimmed]
        setSelectedLabels(updated)
        setNewLabel('')
      } catch (error) {
        console.error('Failed to add label:', error)
        const errorMsg = error instanceof Error ? error.message : 'Failed to add label'
        setErrorMessage(errorMsg)
      }
    }
  }

  const handleRemoveLabel = (label: string) => {
    setSelectedLabels(selectedLabels.filter(l => l !== label))
  }

  const handleSelectExisting = (label: string) => {
    if (!selectedLabels.includes(label)) {
      setSelectedLabels([...selectedLabels, label])
    } else {
      setSelectedLabels(selectedLabels.filter(l => l !== label))
    }
  }

  const handleChangeColor = async (label: string, color: LabelColorName) => {
    const labelObj = labels.find(l => l.name === label)
    if (labelObj) {
      try {
        await updateLabel(labelObj.id, { color })
        setEditingColor(null)
      } catch (error) {
        console.error('Failed to update label color:', error)
      }
    }
  }

  const handleSave = () => {
    onUpdate(selectedLabels)
    setOpen(false)
  }

  const handleCancel = () => {
    setSelectedLabels(existingLabels)
    setEditingColor(null)
    setOpen(false)
  }

  return (
    <Dialog open={open} onOpenChange={(isOpen) => {
      if (!isOpen) {
        handleCancel()
      } else {
        setOpen(true)
      }
    }}>
      <DialogTrigger asChild>
        <Button variant="ghost" size="sm">
          <Tag className="h-4 w-4 mr-2" />
          {t('labels.title')}
        </Button>
      </DialogTrigger>
      <DialogContent
        className="max-w-md"
        onInteractOutside={(event) => {
          const target = event.target as HTMLElement;
          const isSonnerElement =
            target.closest('[data-sonner-toast]') ||
            target.closest('[data-sonner-toaster]') ||
            target.closest('[data-icon]') ||
            target.closest('[data-content]') ||
            target.closest('[data-description]') ||
            target.closest('[data-title]') ||
            target.closest('[data-button]');
          if (isSonnerElement) {
            event.preventDefault();
            return;
          }
          if (target.getAttribute('data-sonner-toaster') !== null) {
            event.preventDefault();
            return;
          }
        }}
      >
        <DialogHeader>
          <DialogTitle>{t('labels.manageLabels')}</DialogTitle>
          <DialogDescription>
            {t('labels.manageLabelsDescription')}
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-4">
          {errorMessage && (
            <div className="flex items-start gap-2 p-3 bg-amber-50 dark:bg-amber-950/20 rounded-lg border border-amber-200 dark:border-amber-900">
              <AlertCircle className="h-4 w-4 text-amber-600 dark:text-amber-500 mt-0.5 flex-shrink-0" />
              <p className="text-sm text-amber-800 dark:text-amber-200">{errorMessage}</p>
            </div>
          )}

          <div className="flex gap-2">
            <Input
              placeholder={t('labels.newLabelPlaceholder')}
              value={newLabel}
              onChange={(e) => {
                setNewLabel(e.target.value)
                setErrorMessage(null)
              }}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  e.preventDefault()
                  handleAddLabel()
                }
              }}
            />
            <Button onClick={handleAddLabel} size="sm">
              <Plus className="h-4 w-4" />
            </Button>
          </div>

          {selectedLabels.length > 0 && (
            <div>
              <h4 className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-2">{t('labels.selectedLabels')}</h4>
              <div className="flex flex-wrap gap-2">
                {selectedLabels.map((label) => {
                  const labelObj = labels.find(l => l.name === label)
                  const colorClasses = labelObj ? LABEL_COLORS[labelObj.color] : LABEL_COLORS.gray
                  const isEditing = editingColor === label
                  const isAI = labelObj?.type === 'ai'

                  return (
                    <div key={label} className="relative">
                      {isEditing && labelObj ? (
                        <div className="absolute z-10 top-8 left-0 bg-popover border rounded-lg shadow-lg p-2">
                          <div className="grid grid-cols-3 gap-2">
                            {(Object.keys(LABEL_COLORS) as LabelColorName[]).map((color) => {
                              const classes = LABEL_COLORS[color]
                              return (
                                <button
                                  key={color}
                                  className={cn(
                                    'h-8 w-8 rounded-full border-2 transition-transform hover:scale-110',
                                    classes.bg,
                                    labelObj.color === color ? 'border-foreground dark:border-foreground' : 'border-border'
                                  )}
                                  onClick={() => handleChangeColor(label, color)}
                                  title={color}
                                />
                              )
                            })}
                          </div>
                        </div>
                      ) : null}
                      <span
                        className={cn(
                          'inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-[9px] font-bold uppercase tracking-wider cursor-pointer',
                          isAI
                            ? 'bg-brand-accent/5 border-brand-accent/20 text-brand-accent'
                            : `${colorClasses.bg} ${colorClasses.text} ${colorClasses.border}`
                        )}
                        onClick={() => setEditingColor(isEditing ? null : label)}
                      >
                        {isAI && <Sparkles className="h-3 w-3" />}
                        <Palette className="h-3 w-3" />
                        {label}
                        <span
                          role="button"
                          tabIndex={0}
                          onClick={(e) => {
                            e.stopPropagation()
                            handleRemoveLabel(label)
                          }}
                          className="ml-1 hover:text-red-500 transition-colors cursor-pointer"
                        >
                          <X className="h-3 w-3" />
                        </span>
                      </span>
                    </div>
                  )
                })}
              </div>
            </div>
          )}

          {!loading && labels.length > 0 && (
            <div>
              <h4 className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-2">{t('labels.allLabels')}</h4>
              <div className="flex flex-wrap gap-2">
                {labels
                  .filter(label => !selectedLabels.includes(label.name))
                  .map((label) => {
                    const colorClasses = LABEL_COLORS[label.color]
                    const isAI = label.type === 'ai'

                    return (
                      <button
                        key={label.id}
                        className={cn(
                          'inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-[9px] font-bold uppercase tracking-wider cursor-pointer transition-all hover:opacity-80',
                          isAI
                            ? 'bg-brand-accent/5 border-brand-accent/20 text-brand-accent'
                            : `${colorClasses.bg} ${colorClasses.text} ${colorClasses.border}`
                        )}
                        onClick={() => handleSelectExisting(label.name)}
                      >
                        {isAI && <Sparkles className="h-3 w-3" />}
                        {label.name}
                      </button>
                    )
                  })}
              </div>
            </div>
          )}
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={handleCancel}>
            {t('general.cancel')}
          </Button>
          <Button onClick={handleSave}>{t('general.save')}</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
