'use client';

import { useState } from 'react';
import { Terminal } from 'lucide-react';
import { toast } from 'sonner';

import { Button, Input } from '@spoon/ui';

export const CommandPanel = ({
  jobId,
  disabled,
}: {
  jobId: string;
  disabled: boolean;
}) => {
  const [command, setCommand] = useState('');
  const [running, setRunning] = useState(false);

  const run = async () => {
    setRunning(true);
    try {
      const response = await fetch(`/api/agent-jobs/${jobId}/command`, {
        method: 'POST',
        body: JSON.stringify({ command }),
      });
      if (!response.ok) throw new Error(await response.text());
      toast.success('Command completed.');
      setCommand('');
    } catch (error) {
      console.error(error);
      toast.error('Command failed.');
    } finally {
      setRunning(false);
    }
  };

  return (
    <div className='border-border flex items-center gap-2 border-t p-3'>
      <Terminal className='text-muted-foreground size-4' />
      <Input
        value={command}
        placeholder='bun test, pnpm lint, npm run typecheck...'
        disabled={disabled || running}
        onChange={(event) => setCommand(event.target.value)}
      />
      <Button
        type='button'
        variant='outline'
        disabled={disabled || running || !command.trim()}
        onClick={run}
      >
        {running ? 'Running...' : 'Run'}
      </Button>
    </div>
  );
};
