import { useState } from 'react';
import { Pressable, Text, TextInput, View } from 'react-native';
import { toast } from 'sonner-native';
import { cn } from '@/lib/utils';
import { toUserMessage } from '@/lib/errors';
import { updateParticleProperties } from '@/lib/firestore-particles';
import { particlePath, toFirestoreDocPath } from '@/lib/particle-path';
import { useSuspendPlayback } from '@/hooks/use-suspend-playback';
import { BottomSheet } from '@/components/BottomSheet';

interface RenameStreamSheetProps {
  open: boolean;
  onClose: () => void;
  networkId: string;
  streamId: string;
  currentName: string;
}

export function RenameStreamSheet({
  open,
  onClose,
  networkId,
  streamId,
  currentName,
}: RenameStreamSheetProps) {
  useSuspendPlayback(open, 'rename-stream');

  const [name, setName] = useState(currentName);
  const [saving, setSaving] = useState(false);

  // Reset the field each time the sheet opens fresh.
  const [prevOpen, setPrevOpen] = useState(open);
  if (open !== prevOpen) {
    setPrevOpen(open);
    if (open) {
      setName(currentName);
      setSaving(false);
    }
  }

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

  const handleSave = async () => {
    if (!canSave) return;
    setSaving(true);
    try {
      const docPath = toFirestoreDocPath(particlePath(networkId, [streamId]));
      await updateParticleProperties<'stream'>(docPath, { name: trimmed });
      onClose();
    } catch (err) {
      toast.error(toUserMessage(err));
      setSaving(false);
    }
  };

  return (
    <BottomSheet open={open} onClose={onClose} avoidKeyboard>
      <View className="flex-row items-center justify-between px-5 pb-3">
        <Pressable onPress={onClose} hitSlop={12}>
          <Text className="text-white/70 text-base">Cancel</Text>
        </Pressable>
        <Text className="text-white text-base font-semibold">Rename</Text>
        <Pressable onPress={handleSave} disabled={!canSave} hitSlop={12}>
          <Text
            className={cn(
              'text-base font-semibold',
              canSave ? 'text-white' : 'text-white/30',
            )}
          >
            {saving ? 'Saving...' : 'Save'}
          </Text>
        </Pressable>
      </View>
      <View className="px-5 pb-6">
        <TextInput
          value={name}
          onChangeText={setName}
          autoFocus
          selectTextOnFocus
          placeholder="Stream name"
          placeholderTextColor="rgba(255,255,255,0.3)"
          className="bg-white/10 rounded-xl px-4 py-3 text-white text-lg"
        />
      </View>
    </BottomSheet>
  );
}
