'use client';

import React, { useState } from 'react';
import { Trash2, Loader2 } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { toast } from 'sonner';
import { logger } from '@claw/core/lib/logger';
import CyberConfirm from './CyberConfirm';
import Button from './ui/Button';
import { useTranslations } from '@/components/Providers/TranslationsProvider';

export default function DeleteAllTracesButton() {
  const router = useRouter();
  const { t } = useTranslations();
  const [isDeleting, setIsDeleting] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);

  const handleDeleteAll = async () => {
    setIsDeleting(true);
    setShowConfirm(false);
    try {
      const response = await fetch('/api/trace?traceId=all', {
        method: 'DELETE',
      });

      if (response.ok) {
        toast.success('Neural archive purged successfully');
        router.refresh();
      } else {
        const error = await response.json();
        toast.error(`Failed to purge traces: ${error.error}`);
      }
    } catch (error) {
      logger.error('Delete all traces error:', error);
      toast.error('Failed to purge traces.');
    } finally {
      setIsDeleting(false);
    }
  };

  return (
    <>
      <CyberConfirm
        isOpen={showConfirm}
        title={t('ARCHIVE_PURGE')}
        message={t('PURGE_MESSAGE')}
        variant="danger"
        confirmText={isDeleting ? t('PURGING') : t('CONFIRM_PURGE')}
        onConfirm={handleDeleteAll}
        onCancel={() => setShowConfirm(false)}
      />
      <Button
        variant="outline"
        size="sm"
        disabled={isDeleting}
        onClick={() => setShowConfirm(true)}
        className="border-red-500/30 text-red-500 hover:bg-red-500/10"
        icon={isDeleting ? <Loader2 size={14} className="animate-spin" /> : <Trash2 size={14} />}
        title={t('PURGE_ALL')}
      >
        {t('PURGE_ALL_BUTTON')}
      </Button>
    </>
  );
}
