import { useCallback, useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { KeyHint } from '@/components/key-hint';
import { updateParticleProperties } from '@/lib/firestore-particles';
import { toFirestoreDocPath, type ParticlePath } from '@/lib/particle-path';
import type { Particle } from '@/api/types';
import { useSuspendPlayback } from '@/hooks/use-suspend-playback';

interface RenameStreamOverlayProps {
  streamPath: ParticlePath;
  streamParticle: Particle & { type: 'stream' };
  onClose: () => void;
}

export function RenameStreamOverlay({
  streamPath,
  streamParticle,
  onClose,
}: RenameStreamOverlayProps) {
  useSuspendPlayback(true, 'rename-stream');

  const [name, setName] = useState(streamParticle.properties.name);
  const [saving, setSaving] = useState(false);

  const trimmed = name.trim();
  const canSave =
    !saving && trimmed.length > 0 && trimmed !== streamParticle.properties.name;

  const handleSave = useCallback(async () => {
    if (!canSave) return;
    setSaving(true);
    try {
      const docPath = toFirestoreDocPath(streamPath);
      await updateParticleProperties<'stream'>(docPath, { name: trimmed });
      onClose();
    } finally {
      setSaving(false);
    }
  }, [canSave, streamPath, onClose, trimmed]);

  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        e.preventDefault();
        e.stopPropagation();
        onClose();
      }
    };
    window.addEventListener('keydown', handler, { capture: true });
    return () =>
      window.removeEventListener('keydown', handler, { capture: true });
  }, [onClose]);

  return createPortal(
    <div className="fixed inset-0 z-[100]">
      <div
        className="absolute inset-0 bg-black/60 backdrop-blur-sm"
        onClick={onClose}
      />
      <div className="absolute left-1/2 top-1/2 w-full max-w-sm -translate-x-1/2 -translate-y-1/2 rounded-2xl border border-white/10 bg-white/5 p-6 shadow-2xl backdrop-blur-xl">
        <div className="mb-4 flex items-center justify-between">
          <h2 className="text-sm font-semibold text-white/70">Rename stream</h2>
          <KeyHint
            keys="Esc"
            onClick={onClose}
            title="Close (or press Esc)"
            className="text-xs text-white/30"
          >
            to close
          </KeyHint>
        </div>

        <Input
          type="text"
          autoFocus
          value={name}
          onChange={(e) => setName(e.target.value)}
          onFocus={(e) => e.currentTarget.select()}
          onKeyDown={(e) => {
            if (e.key === 'Enter') {
              e.preventDefault();
              handleSave();
            }
          }}
          placeholder="Stream name"
          className="border-white/10 bg-white/5 text-white placeholder-white/30 focus-visible:border-white/30 focus-visible:ring-0"
        />

        <div className="mt-4 flex items-center justify-end gap-2">
          <Button variant="ghost" size="sm" onClick={onClose}>
            Cancel
          </Button>
          <Button size="sm" onClick={handleSave} disabled={!canSave}>
            Save
          </Button>
        </div>
      </div>
    </div>,
    document.body,
  );
}
