"use client";

import { useState } from 'react';

interface SearchResult {
  title: string;
  url: string;
  description: string;
}

export default function Home() {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<SearchResult[]>([]);

  const handleSearch = async () => {
    if (!query) return;

    const response = await fetch('/api/search', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ query }),
    });

    const data = await response.json();
    console.log('Data from backend:', data);
    setResults(data.results);
  };

  return (
    <div className="flex min-h-screen flex-col items-center bg-zinc-50 p-24 font-sans dark:bg-black">
      <h1 className="mb-8 text-4xl font-bold text-zinc-900 dark:text-zinc-50">
        Search AI Agent
      </h1>
      <div className="flex w-full max-w-lg items-center">
        <input
          type="text"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          className="w-full rounded-l-md border border-zinc-300 bg-white px-4 py-2 text-zinc-900 focus:border-zinc-500 focus:outline-none dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-50"
          placeholder="Search..."
        />
        <button
          onClick={handleSearch}
          className="rounded-r-md bg-zinc-900 px-4 py-2 text-white hover:bg-zinc-700 dark:bg-zinc-50 dark:text-zinc-900 dark:hover:bg-zinc-300"
        >
          Search
        </button>
      </div>
      <div className="mt-8 w-full max-w-lg">
        {results.map((result, index) => (
          <div key={index} className="mb-4 rounded-md border border-zinc-200 p-4 dark:border-zinc-800">
            <a
              href={result.url}
              className="text-xl font-semibold text-zinc-900 hover:underline dark:text-zinc-50"
            >
              {result.title}
            </a>
            <p className="mt-2 text-zinc-600 dark:text-zinc-400">
              {result.description}
            </p>
          </div>
        ))}
      </div>
    </div>
  );
}