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

import { Card } from '~/components/ui/card';
import { ChipRow } from '~/components/ui/chip-row';
import { formatDateTime, titleize } from '~/utils/format';

type Event = {
  _id: string;
  createdAt: number;
  level: string;
  message: string;
  phase: string;
};

export const WorkspaceEvents = ({ events }: { events: Event[] }) => {
  const [level, setLevel] = useState<'all' | 'info' | 'warn' | 'error'>('all');
  const filtered =
    level === 'all' ? events : events.filter((event) => event.level === level);

  return (
    <Card className='gap-3'>
      <Text className='text-foreground font-semibold'>Events</Text>
      <ChipRow
        options={[
          { label: 'All', value: 'all' },
          { label: 'Info', value: 'info' },
          { label: 'Warn', value: 'warn' },
          { label: 'Error', value: 'error' },
        ]}
        value={level}
        onChange={setLevel}
      />
      {filtered.length ? (
        filtered.map((event) => (
          <View key={event._id} className='border-border border-b pb-2'>
            <Text className='text-muted-foreground text-xs'>
              {formatDateTime(event.createdAt)} · {titleize(event.phase)} ·{' '}
              {titleize(event.level)}
            </Text>
            <Text className='text-foreground mt-1'>{event.message}</Text>
          </View>
        ))
      ) : (
        <Text className='text-muted-foreground text-sm'>No events.</Text>
      )}
    </Card>
  );
};
