"use client";

import { useState } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";

export default function AIMatchPage() {
  const [projectId, setProjectId] = useState("");
  const [loading, setLoading] = useState(false);
  const [matches, setMatches] = useState<any[]>([]);
  const [error, setError] = useState("");

  async function handleMatch() {
    if (!projectId) return;
    setLoading(true);
    try {
      const res = await fetch("/api/ai/match-project", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ project_id: projectId, limit: 10 }),
      });

      if (!res.ok) throw new Error("Ошибка при поиске совпадений");

      const data = await res.json();
      setMatches(data);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <header className="bg-white border-b px-6 py-4 flex items-center justify-between">
        <Link href="/dashboard" className="text-blue-600 hover:text-blue-800">← Назад</Link>
        <h1 className="text-xl font-bold">AI-матчинг</h1>
      </header>

      <main className="container mx-auto px-4 py-8 max-w-3xl">
        <div className="bg-white rounded-xl shadow-sm p-6 mb-6">
          <h2 className="text-2xl font-bold mb-4">Подобрать фрилансеров</h2>

          <input
            value={projectId}
            onChange={(e) => setProjectId(e.target.value)}
            placeholder="ID проекта"
            className="w-full px-4 py-3 border rounded-lg mb-4"
          />

          {error && (
            <div className="mb-4 p-3 bg-red-50 text-red-700 rounded">{error}</div>
          )}

          <Button onClick={handleMatch} disabled={loading}>
            {loading ? "Поиск..." : "Найти совпадения"}
          </Button>
        </div>

        {matches.length > 0 && (
          <div className="space-y-4">
            {matches.map((m, i) => (
              <div key={i} className="bg-white rounded-xl shadow-sm p-6">
                <div className="flex items-center justify-between mb-2">
                  <h3 className="font-semibold">{m.name}</h3>
                  <span className="text-green-600 font-bold">{(m.match_score * 100).toFixed(0)}%</span>
                </div>

                {m.skills_matched.length > 0 && (
                  <p className="text-sm text-gray-500 mb-2">Совпадение навыков: {m.skills_matched.join(", ")}</p>
                )}

                <ul className="space-y-1">
                  {m.reasons.map((r, j) => (
                    <li key={j} className="text-sm text-gray-600">• {r}</li>
                  ))}
                </ul>
              </div>
            ))}
          </div>
        )}
      </main>
    </div>
  );
}
