"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Input } from "@/components/ui/input";
import { Select } from "@/components/ui/select";
import { Button } from "@/components/ui/button";

export default function AssignForm({ templates, nodes }: { templates: any[]; nodes: any[] }) {
  const [templateId, setTemplateId] = useState("");
  const [nodeId, setNodeId] = useState("");
  const [port, setPort] = useState("8080");
  const [loading, setLoading] = useState(false);
  const router = useRouter();

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    await fetch("/api/instances", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ templateId, nodeId, port: parseInt(port) }),
    });
    setLoading(false);
    router.push("/dashboard/instances");
    router.refresh();
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4 bg-white p-6 rounded-lg border shadow-sm">
      <div>
        <label className="block text-sm font-medium mb-1">Template</label>
        <Select value={templateId} onChange={(e) => setTemplateId(e.target.value)} required>
          <option value="">Choisir un template</option>
          {templates.map((t) => (
            <option key={t.id} value={t.id}>{t.name}</option>
          ))}
        </Select>
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">Nœud (étudiant)</label>
        <Select value={nodeId} onChange={(e) => setNodeId(e.target.value)} required>
          <option value="">Choisir un nœud</option>
          {nodes.map((n) => (
            <option key={n.id} value={n.id}>
              {n.id} {n.student ? `- ${n.student.firstName} ${n.student.lastName}` : ""}
            </option>
          ))}
        </Select>
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">Port</label>
        <Input type="number" value={port} onChange={(e) => setPort(e.target.value)} required />
      </div>
      <Button type="submit" className="w-full" disabled={loading}>
        {loading ? "Attribution..." : "Attribuer"}
      </Button>
    </form>
  );
}
