import { FormEvent, useState } from 'react';
import { sendStructuredChat } from '../api';
import type { ChatMessage, StructuredOutputSchema } from '../types';

interface ExtractionResult {
  summary: string;
  sentiment: 'positive' | 'neutral' | 'negative';
  keywords: string[];
}

const EXTRACTION_SCHEMA: StructuredOutputSchema = {
  name: 'text_extraction',
  strict: true,
  schema: {
    type: 'object',
    additionalProperties: false,
    properties: {
      summary: { type: 'string', description: 'One short sentence summarizing the input.' },
      sentiment: { type: 'string', enum: ['positive', 'neutral', 'negative'] },
      keywords: {
        type: 'array',
        items: { type: 'string' },
        description: 'Three to five important keywords from the input.',
      },
    },
    required: ['summary', 'sentiment', 'keywords'],
  },
};

const SYSTEM_PROMPT: ChatMessage = {
  role: 'system',
  content: 'Extract structured facts from the user text. Return only data matching the JSON schema.',
};

export function ExtractTab() {
  const [text, setText] = useState('Kazzle makes it much faster to turn rough ideas into working apps.');
  const [extracting, setExtracting] = useState(false);
  const [result, setResult] = useState<ExtractionResult | null>(null);
  const [error, setError] = useState<string | null>(null);

  async function onSubmit(event: FormEvent) {
    event.preventDefault();
    const content = text.trim();
    if (!content || extracting) return;

    setExtracting(true);
    setError(null);
    try {
      const extracted = await sendStructuredChat<ExtractionResult>(
        [SYSTEM_PROMPT, { role: 'user', content }],
        EXTRACTION_SCHEMA,
        { max_completion_tokens: 512 },
      );
      setResult(extracted);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setExtracting(false);
    }
  }

  return (
    <div className="tab-body">
      <p className="empty">
        Use structured output when the app needs data, not prose. The server forwards
        OpenAI-style <code>response_format.json_schema</code> and returns parsed JSON.
      </p>

      <form className="stack-form" onSubmit={onSubmit}>
        <textarea
          value={text}
          onChange={event => setText(event.target.value)}
          disabled={extracting}
          data-testid="extract-input"
        />
        <button type="submit" disabled={extracting || !text.trim()} data-testid="extract-submit">
          {extracting ? 'Extracting…' : 'Extract structured data'}
        </button>
      </form>

      {error ? <p className="error" data-testid="error">{error}</p> : null}

      {result ? (
        <section className="structured-result" data-testid="structured-result">
          <p><strong>Summary:</strong> {result.summary}</p>
          <p><strong>Sentiment:</strong> {result.sentiment}</p>
          <p><strong>Keywords:</strong> {result.keywords.join(', ')}</p>
        </section>
      ) : null}
    </div>
  );
}
