'use client'

import { useState, useEffect } from 'react'
import { Button } from './ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from './ui/dialog'
import { Checkbox } from './ui/checkbox'
import { Tag, Loader2, Sparkles, CheckCircle2 } from 'lucide-react'
import { toast } from 'sonner'
import { useLanguage } from '@/lib/i18n'
import type { AutoLabelSuggestion, SuggestedLabel } from '@/lib/ai/services'

interface AutoLabelSuggestionDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  notebookId: string | null
  onLabelsCreated: () => void
}

export function AutoLabelSuggestionDialog({
  open,
  onOpenChange,
  notebookId,
  onLabelsCreated,
}: AutoLabelSuggestionDialogProps) {
  const { t } = useLanguage()
  const [suggestions, setSuggestions] = useState<AutoLabelSuggestion | null>(null)
  const [loading, setLoading] = useState(false)
  const [creating, setCreating] = useState(false)
  const [selectedLabels, setSelectedLabels] = useState<Set<string>>(new Set())

  // Fetch suggestions when dialog opens with a notebook
  useEffect(() => {
    if (open && notebookId) {
      fetchSuggestions()
    } else {
      // Reset state when closing
      setSuggestions(null)
      setSelectedLabels(new Set())
    }
  }, [open, notebookId])

  const fetchSuggestions = async () => {
    if (!notebookId) return

    setLoading(true)
    try {
      const response = await fetch('/api/ai/auto-labels', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          notebookId,
          language: document.documentElement.lang || 'en',
        }),
      })

      const data = await response.json()

      if (data.success && data.data) {
        setSuggestions(data.data)
        // Select all labels by default
        const allLabelNames = new Set<string>(data.data.suggestedLabels.map((l: SuggestedLabel) => l.name as string))
        setSelectedLabels(allLabelNames)
      } else {
        // No suggestions is not an error - just close the dialog
        if (data.message) {
        }
        onOpenChange(false)
      }
    } catch (error) {
      console.error('Failed to fetch label suggestions:', error)
      toast.error(t('ai.autoLabels.error'))
      onOpenChange(false)
    } finally {
      setLoading(false)
    }
  }

  const toggleLabelSelection = (labelName: string) => {
    const newSelected = new Set(selectedLabels)
    if (newSelected.has(labelName)) {
      newSelected.delete(labelName)
    } else {
      newSelected.add(labelName)
    }
    setSelectedLabels(newSelected)
  }

  const handleCreateLabels = async () => {
    if (!suggestions || selectedLabels.size === 0) {
      toast.error(t('ai.autoLabels.noLabelsSelected'))
      return
    }

    setCreating(true)
    try {
      const response = await fetch('/api/ai/auto-labels', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          suggestions,
          selectedLabels: Array.from(selectedLabels),
        }),
      })

      const data = await response.json()

      if (data.success) {
        toast.success(t('ai.autoLabels.created', { count: data.data.createdCount }))
        onLabelsCreated()
        onOpenChange(false)
      } else {
        toast.error(data.error || t('ai.autoLabels.error'))
      }
    } catch (error) {
      console.error('Failed to create labels:', error)
      toast.error(t('ai.autoLabels.error'))
    } finally {
      setCreating(false)
    }
  }

  if (loading) {
    return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle className="sr-only">{t('ai.autoLabels.analyzing')}</DialogTitle>
          </DialogHeader>
          <div className="flex flex-col items-center justify-center py-12">
            <Loader2 className="h-8 w-8 animate-spin text-primary" />
            <p className="mt-4 text-sm text-muted-foreground">
              {t('ai.autoLabels.analyzing')}
            </p>
          </div>
        </DialogContent>
      </Dialog>
    )
  }

  if (!suggestions) {
    return null
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Sparkles className="h-5 w-5 text-amber-500" />
            {t('ai.autoLabels.title')}
          </DialogTitle>
          <DialogDescription>
            {t('ai.autoLabels.description', {
              notebook: suggestions.notebookName,
              count: suggestions.totalNotes,
            })}
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-3 py-4">
          {suggestions.suggestedLabels.map((label) => (
            <div
              key={label.name}
              className="flex items-start gap-3 p-3 rounded-lg border hover:bg-muted/50 cursor-pointer"
              onClick={() => toggleLabelSelection(label.name)}
            >
              <Checkbox
                checked={selectedLabels.has(label.name)}
                onCheckedChange={() => toggleLabelSelection(label.name)}
                aria-label={`Select label: ${label.name}`}
              />
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  <Tag className="h-4 w-4 text-muted-foreground" />
                  <span className="font-medium">{label.name}</span>
                </div>
                <div className="flex items-center gap-3 mt-1">
                  <span className="text-xs text-muted-foreground">
                    {t('ai.autoLabels.notesCount', { count: label.count })}
                  </span>
                  <span className="text-xs px-2 py-0.5 rounded-full bg-primary/10 text-primary">
                    {Math.round(label.confidence * 100)}% {t('notebook.confidence')}
                  </span>
                </div>
              </div>
            </div>
          ))}
        </div>

        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={creating}
          >
            {t('general.cancel')}
          </Button>
          <Button
            onClick={handleCreateLabels}
            disabled={selectedLabels.size === 0 || creating}
          >
            {creating ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                {t('ai.autoLabels.creating')}
              </>
            ) : (
              <>
                <CheckCircle2 className="h-4 w-4 mr-2" />
                {t('ai.autoLabels.create')}
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
