import { useCallback, useState } from 'react';
import { toast } from 'sonner';
import { ConfirmDestructiveOverlay } from '@/components/confirm-destructive-overlay';
import { softDeleteParticle } from '@/lib/firestore-particles';
import {
  particlePath,
  parseParticlePath,
  toFirestoreDocPath,
  type ParticlePath,
} from '@/lib/particle-path';
import type { Particle } from '@/api/types';
import { useSuspendPlayback } from '@/hooks/use-suspend-playback';

interface DeleteParticleOverlayProps {
  /** Path of the stream the particle lives in — may be nested. */
  streamPath: ParticlePath;
  particle: Particle;
  userId: string;
  onClose: () => void;
}

export function DeleteParticleOverlay({
  streamPath,
  particle,
  userId,
  onClose,
}: DeleteParticleOverlayProps) {
  useSuspendPlayback(true, 'delete-particle');

  const [deleting, setDeleting] = useState(false);

  const handleDelete = useCallback(async () => {
    if (deleting) return;
    setDeleting(true);
    try {
      const { networkId, segments } = parseParticlePath(streamPath);
      const docPath = toFirestoreDocPath(
        particlePath(networkId, [...segments, particle.id]),
      );
      await softDeleteParticle(docPath, userId);
      toast.success('Particle deleted');
      onClose();
    } catch (e) {
      const message =
        e instanceof Error ? e.message : 'Failed to delete particle';
      toast.error(message);
      setDeleting(false);
    }
  }, [deleting, onClose, particle.id, streamPath, userId]);

  return (
    <ConfirmDestructiveOverlay
      title="Delete this particle?"
      description={
        <p>
          This cannot be undone. Other viewers will see a "This particle was
          deleted" message in its place.
        </p>
      }
      confirmLabel="Delete"
      pendingLabel="Deleting…"
      isPending={deleting}
      onConfirm={handleDelete}
      onClose={onClose}
    />
  );
}
