import { useMemo, 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';
import { Textarea } from '~/components/ui/textarea';
import { parseEnvText } from '~/utils/env';

export const SpoonSecretsPanel = ({
  adding,
  importing,
  onAddSecret,
  onImportSecrets,
  onRemoveSecret,
  removingId,
  secrets,
}: {
  adding: boolean;
  importing: boolean;
  onAddSecret: (name: string, value: string) => Promise<void>;
  onImportSecrets: (
    secrets: { name: string; value: string }[],
  ) => Promise<void>;
  onRemoveSecret: (secretId: string) => Promise<void>;
  removingId?: string;
  secrets: { _id: string; name: string; valuePreview?: string }[];
}) => {
  const [name, setName] = useState('');
  const [value, setValue] = useState('');
  const [envText, setEnvText] = useState('');
  const parsed = useMemo(() => parseEnvText(envText), [envText]);
  const preview = parsed.slice(0, 25);

  const add = async () => {
    if (!name.trim() || !value.trim()) return;
    try {
      await onAddSecret(name.trim(), value);
      setName('');
      setValue('');
    } catch (error) {
      console.error(error);
      Alert.alert('Could not save secret.');
    }
  };

  const importAll = async () => {
    if (!parsed.length) return;
    try {
      await onImportSecrets(parsed);
      setEnvText('');
      Alert.alert('Secrets imported', `${parsed.length} secrets were saved.`);
    } catch (error) {
      console.error(error);
      Alert.alert(
        'Could not import every secret',
        error instanceof Error
          ? error.message
          : 'Some secrets may have been saved. Review the list and try again.',
      );
    }
  };

  return (
    <FormSection
      description='Secret values are encrypted and never shown after saving.'
      title='Secrets'
    >
      {secrets.map((secret) => (
        <View
          key={secret._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'>{secret.name}</Text>
            <Text className='text-muted-foreground text-xs'>
              {secret.valuePreview ?? 'configured'}
            </Text>
          </View>
          <ConfirmButton
            confirmLabel='Remove'
            destructive
            disabled={removingId === secret._id}
            message={`Remove ${secret.name} from this Spoon?`}
            title='Remove secret'
            onConfirm={() => void onRemoveSecret(secret._id)}
          >
            {removingId === secret._id ? 'Removing...' : 'Remove'}
          </ConfirmButton>
        </View>
      ))}
      <View className='gap-3'>
        <Text className='text-foreground font-semibold'>Add one secret</Text>
        <Field label='Name' value={name} onChangeText={setName} />
        <Field
          label='Value'
          secureTextEntry
          value={value}
          onChangeText={setValue}
        />
        <Button
          disabled={adding || !name.trim() || !value.trim()}
          onPress={add}
        >
          {adding ? 'Adding...' : 'Add secret'}
        </Button>
      </View>
      <View className='gap-3'>
        <Text className='text-foreground font-semibold'>Import .env</Text>
        <Textarea
          label='.env contents'
          placeholder='AUTH_SECRET=...'
          value={envText}
          onChangeText={setEnvText}
        />
        <Text className='text-muted-foreground text-sm'>
          {parsed.length
            ? `${parsed.length} valid secrets found: ${preview
                .map((secret) => secret.name)
                .join(', ')}${parsed.length > preview.length ? ', ...' : ''}`
            : 'Paste .env contents to preview secret names.'}
        </Text>
        <View className='flex-row gap-3'>
          <Button
            disabled={importing || !parsed.length}
            onPress={() => void importAll()}
          >
            {importing ? 'Importing...' : 'Import secrets'}
          </Button>
          <Button variant='outline' onPress={() => setEnvText('')}>
            Clear
          </Button>
        </View>
      </View>
    </FormSection>
  );
};
