import { Text, View } from 'react-native';
import * as Clipboard from 'expo-clipboard';

import { Button } from '~/components/ui/button';
import { Card } from '~/components/ui/card';
import { DiffPreview } from './diff-preview';

type Artifact = {
  _id: string;
  content: string;
  contentType: string;
  kind: string;
  title: string;
};

export const WorkspaceArtifacts = ({
  artifacts,
  mode,
}: {
  artifacts: Artifact[];
  mode: 'diffs' | 'artifacts';
}) => {
  const diffArtifacts = artifacts.filter(
    (artifact) =>
      artifact.contentType === 'text/x-diff' || artifact.kind === 'diff',
  );
  const visible =
    mode === 'diffs'
      ? diffArtifacts
      : artifacts.filter((artifact) => !diffArtifacts.includes(artifact));

  return (
    <Card className='gap-3'>
      <Text className='text-foreground font-semibold'>
        {mode === 'diffs' ? 'Diffs' : 'Artifacts'}
      </Text>
      {visible.length ? (
        visible.map((artifact) => (
          <View key={artifact._id} className='gap-2'>
            <Text className='text-muted-foreground text-sm'>
              {artifact.title}
            </Text>
            {mode === 'diffs' ? (
              <DiffPreview content={artifact.content} />
            ) : (
              <>
                <Text className='bg-muted text-foreground rounded-md p-3 font-mono text-xs leading-5'>
                  {artifact.content.slice(0, 2_000)}
                </Text>
                <Button
                  variant='outline'
                  onPress={() =>
                    void Clipboard.setStringAsync(artifact.content)
                  }
                >
                  Copy artifact
                </Button>
              </>
            )}
          </View>
        ))
      ) : (
        <Text className='text-muted-foreground text-sm'>
          {mode === 'diffs'
            ? 'Diff artifacts will appear here when the worker records them.'
            : 'No non-diff artifacts recorded.'}
        </Text>
      )}
    </Card>
  );
};
