'use client'

import { useState } from 'react'
import { Trash2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { useLanguage } from '@/lib/i18n'
import { emptyTrash } from '@/app/actions/notes'
import { useRouter } from 'next/navigation'
import { toast } from 'sonner'

interface TrashHeaderProps {
  noteCount?: number
}

export function TrashHeader({ noteCount = 0 }: TrashHeaderProps) {
  const { t } = useLanguage()
  const router = useRouter()
  const [showEmptyDialog, setShowEmptyDialog] = useState(false)
  const [isEmptying, setIsEmptying] = useState(false)

  const handleEmptyTrash = async () => {
    setIsEmptying(true)
    try {
      await emptyTrash()
      toast.success(t('trash.emptyTrashSuccess'))
      router.refresh()
    } catch (error) {
      console.error('Error emptying trash:', error)
    } finally {
      setIsEmptying(false)
      setShowEmptyDialog(false)
    }
  }

  return (
    <div className="flex items-center justify-between mb-8">
      <h1 className="text-3xl font-bold">{t('nav.trash')}</h1>
      {noteCount > 0 && (
        <Button
          variant="destructive"
          size="sm"
          onClick={() => setShowEmptyDialog(true)}
          disabled={isEmptying}
        >
          <Trash2 className="h-4 w-4 mr-2" />
          {t('trash.emptyTrash')}
        </Button>
      )}

      <AlertDialog open={showEmptyDialog} onOpenChange={setShowEmptyDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t('trash.emptyTrash')}</AlertDialogTitle>
            <AlertDialogDescription>
              {t('trash.emptyTrashConfirm')}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{t('common.cancel')}</AlertDialogCancel>
            <AlertDialogAction variant="destructive" onClick={handleEmptyTrash}>
              {t('trash.emptyTrash')}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )
}
