'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 { Wand2, Loader2, ChevronRight, CheckCircle2 } from 'lucide-react'
import { getNotebookIcon } from '@/lib/notebook-icon'
import { toast } from 'sonner'
import { useLanguage } from '@/lib/i18n'
import { useAiConsent } from '@/components/legal/ai-consent-provider'
import type { OrganizationPlan, NotebookOrganization } from '@/lib/ai/services'

interface BatchOrganizationDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  onNotesMoved: () => void
}

export function BatchOrganizationDialog({
  open,
  onOpenChange,
  onNotesMoved,
}: BatchOrganizationDialogProps) {
  const { t, language } = useLanguage()
  const { requestAiConsent } = useAiConsent()
  const [plan, setPlan] = useState<OrganizationPlan | null>(null)
  const [loading, setLoading] = useState(false)
  const [applying, setApplying] = useState(false)
  const [selectedNotes, setSelectedNotes] = useState<Set<string>>(new Set())

  const [fetchError, setFetchError] = useState<string | null>(null)

  const fetchOrganizationPlan = async () => {
    setLoading(true)
    setFetchError(null)
    try {
      const consented = await requestAiConsent()
      if (!consented) {
        setLoading(false)
        return
      }

      const response = await fetch('/api/ai/batch-organize', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          language: language || 'en'
        }),
      })

      const data = await response.json()

      if (data.success && data.data) {
        setPlan(data.data)
        const allNoteIds = new Set<string>()
        data.data.notebooks.forEach((nb: NotebookOrganization) => {
          nb.notes.forEach(note => allNoteIds.add(note.noteId))
        })
        setSelectedNotes(allNoteIds)
      } else {
        const msg = data.error || t('ai.batchOrganization.error')
        setFetchError(msg)
        toast.error(msg)
      }
    } catch (error) {
      console.error('Failed to create organization plan:', error)
      const msg = t('ai.batchOrganization.error')
      setFetchError(msg)
      toast.error(msg)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    if (open) {
      fetchOrganizationPlan()
    } else {
      setPlan(null)
      setSelectedNotes(new Set())
      setFetchError(null)
    }
     
  }, [open])

  const handleOpenChange = (isOpen: boolean) => {
    onOpenChange(isOpen)
  }

  const toggleNoteSelection = (noteId: string) => {
    const newSelected = new Set(selectedNotes)
    if (newSelected.has(noteId)) {
      newSelected.delete(noteId)
    } else {
      newSelected.add(noteId)
    }
    setSelectedNotes(newSelected)
  }

  const toggleNotebookSelection = (notebook: NotebookOrganization) => {
    const newSelected = new Set(selectedNotes)
    const allNoteIds = notebook.notes.map(n => n.noteId)

    // Check if all notes in this notebook are already selected
    const allSelected = allNoteIds.every(id => newSelected.has(id))

    if (allSelected) {
      // Deselect all
      allNoteIds.forEach(id => newSelected.delete(id))
    } else {
      // Select all
      allNoteIds.forEach(id => newSelected.add(id))
    }

    setSelectedNotes(newSelected)
  }

  const handleApply = async () => {
    if (!plan || selectedNotes.size === 0) {
      toast.error(t('ai.batchOrganization.noNotesSelected'))
      return
    }

    setApplying(true)
    try {
      const response = await fetch('/api/ai/batch-organize', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          plan,
          selectedNoteIds: Array.from(selectedNotes),
        }),
      })

      const data = await response.json()

      if (data.success) {
        toast.success(t('ai.batchOrganization.success', { count: data.data.movedCount }))
        onNotesMoved()
        onOpenChange(false)
      } else {
        toast.error(data.error || t('ai.batchOrganization.applyFailed'))
      }
    } catch (error) {
      console.error('Failed to apply organization plan:', error)
      toast.error(t('ai.batchOrganization.applyFailed'))
    } finally {
      setApplying(false)
    }
  }

  const getSelectedCountForNotebook = (notebook: NotebookOrganization) => {
    return notebook.notes.filter(n => selectedNotes.has(n.noteId)).length
  }

  const getAllSelectedCount = () => {
    if (!plan) return 0
    return plan.notebooks.reduce(
      (acc, nb) => acc + getSelectedCountForNotebook(nb),
      0
    )
  }

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className="!max-w-5xl max-h-[85vh] overflow-y-auto !w-[95vw]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Wand2 className="h-5 w-5" />
            {t('ai.batchOrganization.title')}
          </DialogTitle>
          <DialogDescription>
            {t('ai.batchOrganization.description')}
          </DialogDescription>
        </DialogHeader>

        {loading ? (
          <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.batchOrganization.analyzing')}
            </p>
          </div>
        ) : fetchError ? (
          <div className="flex flex-col items-center justify-center py-12 gap-4">
            <p className="text-sm text-destructive text-center">{fetchError}</p>
            <Button variant="outline" onClick={fetchOrganizationPlan}>
              {t('general.tryAgain')}
            </Button>
          </div>
        ) : plan ? (
          <div className="space-y-6 py-4">
            {/* Summary */}
            <div className="flex items-center justify-between p-4 bg-muted rounded-lg">
              <div>
                <p className="font-medium">
                  {t('ai.batchOrganization.notesToOrganize', {
                    count: plan.totalNotes,
                  })}
                </p>
                <p className="text-sm text-muted-foreground">
                  {t('ai.batchOrganization.selected', {
                    count: getAllSelectedCount(),
                  })}
                </p>
              </div>
            </div>

            {/* No notebooks available */}
            {plan.notebooks.length === 0 ? (
              <div className="text-center py-8">
                <p className="text-muted-foreground">
                  {plan.unorganizedNotes === plan.totalNotes
                    ? t('ai.batchOrganization.noNotebooks')
                    : t('ai.batchOrganization.noSuggestions')}
                </p>
              </div>
            ) : (
              <>
                {/* Organization plan by notebook */}
                {plan.notebooks.map((notebook) => {
                  const selectedCount = getSelectedCountForNotebook(notebook)
                  const allSelected =
                    selectedCount === notebook.notes.length && selectedCount > 0

                  return (
                    <div
                      key={notebook.notebookId}
                      className="border rounded-lg p-4 space-y-3"
                    >
                      {/* Notebook header */}
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-3">
                          <Checkbox
                            checked={allSelected}
                            onCheckedChange={() => toggleNotebookSelection(notebook)}
                            aria-label={t('ai.batchOrganization.selectAllIn', { notebook: notebook.notebookName })}
                          />
                          <div className="flex items-center gap-2">
                            {(() => {
                              const Icon = getNotebookIcon(notebook.notebookIcon)
                              return <Icon className="h-5 w-5" />
                            })()}
                            <span className="font-semibold">
                              {notebook.notebookName}
                            </span>
                            <span className="text-sm text-muted-foreground">
                              ({selectedCount}/{notebook.notes.length})
                            </span>
                          </div>
                        </div>
                      </div>

                      {/* Notes in this notebook */}
                      <div className="space-y-2 pl-11">
                        {notebook.notes.map((note) => (
                          <div
                            key={note.noteId}
                            className="flex items-start gap-3 p-2 rounded hover:bg-muted/50 cursor-pointer"
                            onClick={() => toggleNoteSelection(note.noteId)}
                          >
                            <Checkbox
                              checked={selectedNotes.has(note.noteId)}
                              onCheckedChange={() => toggleNoteSelection(note.noteId)}
                              aria-label={t('ai.batchOrganization.selectNote', { title: note.title || t('notes.untitled') })}
                            />
                            <div className="flex-1 min-w-0">
                              <p className="text-sm font-medium truncate">
                                {note.title || t('notes.untitled') || 'Untitled'}
                              </p>
                              <p className="text-xs text-muted-foreground line-clamp-2">
                                {note.content}
                              </p>
                              <div className="flex items-center gap-2 mt-1">
                                <span className="text-xs px-2 py-0.5 rounded-full bg-primary/10 text-primary">
                                  {Math.round(note.confidence * 100)}% {t('notebook.confidence')}
                                </span>
                                {note.reason && (
                                  <span className="text-xs text-muted-foreground">
                                    {note.reason}
                                  </span>
                                )}
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  )
                })}

                {/* Unorganized notes warning */}
                {plan.unorganizedNotes > 0 && (
                  <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">
                    <ChevronRight className="h-4 w-4 text-amber-600 dark:text-amber-500 mt-0.5" />
                    <p className="text-sm text-amber-800 dark:text-amber-200">
                      {t('ai.batchOrganization.unorganized', {
                        count: plan.unorganizedNotes,
                      })}
                    </p>
                  </div>
                )}
              </>
            )}
          </div>
        ) : null}

        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={applying}
          >
            {t('general.cancel')}
          </Button>
          <Button
            onClick={handleApply}
            disabled={!plan || selectedNotes.size === 0 || applying}
          >
            {applying ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                {t('ai.batchOrganization.applying')}
              </>
            ) : (
              <>
                <CheckCircle2 className="h-4 w-4 mr-2" />
                {t('ai.batchOrganization.apply', { count: selectedNotes.size })}
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
