import { useState } from 'react';
import { Alert, Text, View } from 'react-native';

import { Button } from '~/components/ui/button';
import { ConfirmButton } from '~/components/ui/confirm-button';
import { Field } from '~/components/ui/field';
import { FormSection } from '~/components/ui/form-section';

export const SpoonRemotesPanel = ({
  adding,
  onAddRemote,
  onRemoveRemote,
  remotes,
  removingId,
}: {
  adding: boolean;
  onAddRemote: (label: string, url: string) => Promise<void>;
  onRemoveRemote: (remoteId: string) => Promise<void>;
  remotes: { _id: string; label: string; url: string }[];
  removingId?: string;
}) => {
  const [label, setLabel] = useState('');
  const [url, setUrl] = useState('');

  const add = async () => {
    if (!label.trim() || !url.trim()) return;
    try {
      await onAddRemote(label.trim(), url.trim());
      setLabel('');
      setUrl('');
    } catch (error) {
      console.error(error);
      Alert.alert('Could not add remote.');
    }
  };

  return (
    <FormSection title='Additional remotes'>
      {remotes.map((remote) => (
        <View
          key={remote._id}
          className='border-border flex-row items-center justify-between gap-3 border-b py-2'
        >
          <View className='min-w-0 flex-1'>
            <Text className='text-foreground font-medium'>{remote.label}</Text>
            <Text className='text-muted-foreground text-xs'>{remote.url}</Text>
          </View>
          <ConfirmButton
            confirmLabel='Remove'
            destructive
            disabled={removingId === remote._id}
            message={`Remove ${remote.label} from this Spoon?`}
            title='Remove remote'
            onConfirm={() => void onRemoveRemote(remote._id)}
          >
            {removingId === remote._id ? 'Removing...' : 'Remove'}
          </ConfirmButton>
        </View>
      ))}
      <Field label='Label' value={label} onChangeText={setLabel} />
      <Field keyboardType='url' label='URL' value={url} onChangeText={setUrl} />
      <Button disabled={adding || !label.trim() || !url.trim()} onPress={add}>
        {adding ? 'Adding...' : 'Add remote'}
      </Button>
    </FormSection>
  );
};
