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

import type { Id } from '@spoon/backend/convex/_generated/dataModel.js';

import { Field } from '~/components/ui/field';
import { FormSection } from '~/components/ui/form-section';
import { SheetSelect } from '~/components/ui/sheet-select';
import { SwitchRow } from '~/components/ui/switch-row';

type ReasoningEffort = 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';

type ProviderProfile = {
  _id: Id<'aiProviderProfiles'>;
  defaultModel: string;
  enabled: boolean;
  isDefault?: boolean;
  modelOptions?: string[];
  name: string;
  reasoningEffort: ReasoningEffort;
};

export const SpoonAgentSettingsForm = ({
  agent,
  onUpdate,
  profiles,
}: {
  agent?: {
    agentModel: string;
    aiProviderProfileId?: Id<'aiProviderProfiles'>;
    autoDetectCommands?: boolean;
    branchPrefix: string;
    checkCommand?: string;
    enabled?: boolean;
    envFilePath?: string;
    installCommand?: string;
    materializeEnvFileByDefault?: boolean;
    reasoningEffort: ReasoningEffort;
    testCommand?: string;
  };
  onUpdate: (patch: {
    agentModel?: string;
    aiProviderProfileId?: Id<'aiProviderProfiles'>;
    autoDetectCommands?: boolean;
    branchPrefix?: string;
    checkCommand?: string;
    enabled?: boolean;
    envFilePath?: string;
    installCommand?: string;
    materializeEnvFileByDefault?: boolean;
    reasoningEffort?: ReasoningEffort;
    testCommand?: string;
  }) => Promise<void>;
  profiles: ProviderProfile[];
}) => {
  const enabledProfiles = profiles.filter((profile) => profile.enabled);
  const selectedProfile =
    enabledProfiles.find(
      (profile) => profile._id === agent?.aiProviderProfileId,
    ) ??
    enabledProfiles.find((profile) => profile.isDefault) ??
    enabledProfiles[0];
  const models = Array.from(
    new Set(
      selectedProfile
        ? [
            selectedProfile.defaultModel,
            ...(selectedProfile.modelOptions ?? []),
          ].filter(Boolean)
        : [],
    ),
  );
  const currentModel =
    models.find((model) => model === agent?.agentModel) ??
    selectedProfile?.defaultModel ??
    '';

  const save = (patch: Parameters<typeof onUpdate>[0]) =>
    void onUpdate(patch).catch((error: unknown) => {
      console.error(error);
      Alert.alert('Could not save agent settings.');
    });

  return (
    <FormSection
      description='Mobile can configure the runtime, but code editing still happens from the web workspace.'
      title='Agent settings'
    >
      <SwitchRow
        label='Enabled'
        value={agent?.enabled ?? true}
        onValueChange={(enabled) => save({ enabled })}
      />
      <SwitchRow
        label='Auto-detect commands'
        value={agent?.autoDetectCommands ?? true}
        onValueChange={(autoDetectCommands) => save({ autoDetectCommands })}
      />
      <SwitchRow
        label='Materialize env file'
        value={agent?.materializeEnvFileByDefault ?? false}
        onValueChange={(materializeEnvFileByDefault) =>
          save({ materializeEnvFileByDefault })
        }
      />
      <SheetSelect
        disabled={!enabledProfiles.length}
        label='AI provider'
        options={
          enabledProfiles.length
            ? enabledProfiles.map((profile) => ({
                label: profile.isDefault
                  ? `${profile.name} (default)`
                  : profile.name,
                value: profile._id,
              }))
            : [{ label: 'Configure an AI provider in Settings', value: '' }]
        }
        value={selectedProfile?._id ?? ''}
        onChange={(aiProviderProfileId) => {
          const profile = enabledProfiles.find(
            (item) => item._id === aiProviderProfileId,
          );
          if (profile) {
            save({
              agentModel: profile.defaultModel,
              aiProviderProfileId: profile._id,
              reasoningEffort: profile.reasoningEffort,
            });
          }
        }}
      />
      <SheetSelect
        disabled={!models.length}
        label='Model'
        options={
          models.length
            ? models.map((model) => ({ label: model, value: model }))
            : [{ label: 'No models available', value: '' }]
        }
        value={currentModel}
        onChange={(agentModel) => save({ agentModel })}
      />
      <SheetSelect
        label='Reasoning effort'
        options={[
          { label: 'None', value: 'none' },
          { label: 'Minimal', value: 'minimal' },
          { label: 'Low', value: 'low' },
          { label: 'Medium', value: 'medium' },
          { label: 'High', value: 'high' },
          { label: 'XHigh', value: 'xhigh' },
        ]}
        value={
          agent?.reasoningEffort ?? selectedProfile?.reasoningEffort ?? 'medium'
        }
        onChange={(reasoningEffort) => save({ reasoningEffort })}
      />
      {!enabledProfiles.length ? (
        <Text className='text-muted-foreground text-sm leading-5'>
          Configure an AI provider in Settings before queueing agent work.
        </Text>
      ) : null}
      <View className='gap-3'>
        <Field
          label='Branch prefix'
          value={agent?.branchPrefix ?? 'spoon/agent'}
          onChangeText={(branchPrefix) => save({ branchPrefix })}
        />
        <Field
          label='Install command'
          value={agent?.installCommand ?? ''}
          onChangeText={(installCommand) => save({ installCommand })}
        />
        <Field
          label='Check command'
          value={agent?.checkCommand ?? ''}
          onChangeText={(checkCommand) => save({ checkCommand })}
        />
        <Field
          label='Test command'
          value={agent?.testCommand ?? ''}
          onChangeText={(testCommand) => save({ testCommand })}
        />
        <Field
          label='Env file path'
          value={agent?.envFilePath ?? '.env.local'}
          onChangeText={(envFilePath) => save({ envFilePath })}
        />
      </View>
    </FormSection>
  );
};
