import { useState } from 'react';
import { Pressable, Text, TextInput, View } from 'react-native';
import { toast } from 'sonner-native';
import { BottomSheet } from '@/components/BottomSheet';
import { useCreateNetwork } from '@/hooks/use-invitations';
import { toUserMessage } from '@/lib/errors';
import { cn } from '@/lib/utils';

interface CreateNetworkSheetProps {
  open: boolean;
  onClose: () => void;
  /** Called with the new network's id once creation succeeds. */
  onCreated?: (networkId: string) => void;
}

/**
 * Minimal "name your network" sheet. Mirrors desktop's create-network flow in
 * `network-selector.tsx` — single text field, creator becomes admin.
 */
export function CreateNetworkSheet({
  open,
  onClose,
  onCreated,
}: CreateNetworkSheetProps) {
  const [name, setName] = useState('');
  const createNetwork = useCreateNetwork();

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

  const trimmed = name.trim();
  const canCreate = trimmed.length > 0 && !createNetwork.isPending;

  const handleCreate = async () => {
    if (!canCreate) return;
    try {
      const network = await createNetwork.mutateAsync({ name: trimmed });
      onClose();
      onCreated?.(network.id);
    } catch (err) {
      toast.error(toUserMessage(err));
    }
  };

  return (
    <BottomSheet open={open} onClose={onClose} avoidKeyboard maxHeight="50%">
      <View className="px-5 pb-4">
        <Text className="text-white text-lg font-semibold">New network</Text>
        <Text className="text-white/50 text-sm mt-1">
          You’ll be the admin and can invite people next.
        </Text>

        <TextInput
          value={name}
          onChangeText={setName}
          placeholder="Network name"
          placeholderTextColor="rgba(255,255,255,0.4)"
          autoFocus
          autoCapitalize="words"
          returnKeyType="done"
          onSubmitEditing={handleCreate}
          editable={!createNetwork.isPending}
          className="text-white text-base bg-white/10 rounded-xl px-4 py-3 mt-4"
        />

        <Pressable
          onPress={handleCreate}
          disabled={!canCreate}
          className={cn(
            'mt-4 rounded-xl py-3 items-center',
            canCreate ? 'bg-white' : 'bg-white/20',
          )}
        >
          <Text
            className={cn(
              'text-base font-semibold',
              canCreate ? 'text-black' : 'text-white/40',
            )}
          >
            {createNetwork.isPending ? 'Creating…' : 'Create network'}
          </Text>
        </Pressable>
      </View>
    </BottomSheet>
  );
}
