"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { createEvaluation } from "@/actions/evaluations";
import { CandidateForm } from "@/components/CandidateForm";

interface NewEvaluationFormProps {
  templates: { id: string; name: string }[];
  initialEvaluatorName: string;
}

export function NewEvaluationForm({ templates, initialEvaluatorName }: NewEvaluationFormProps) {
  const router = useRouter();
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState({
    candidateName: "",
    candidateRole: "",
    candidateTeam: "",
    evaluatorName: initialEvaluatorName,
    evaluationDate: new Date().toISOString().split("T")[0],
    templateId: templates[0]?.id ?? "",
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.templateId) return;
    setSaving(true);
    try {
      const result = await createEvaluation({
        ...form,
        evaluationDate: new Date(form.evaluationDate).toISOString(),
      });
      if (result.success && result.data) {
        router.push(`/evaluations/${result.data.id}`);
      } else if (!result.success) {
        alert(result.error);
      }
    } finally {
      setSaving(false);
    }
  };

  return (
    <div>
      <h1 className="mb-6 font-mono text-lg font-medium text-zinc-800 dark:text-zinc-200">Nouvelle évaluation</h1>
      <form onSubmit={handleSubmit} className="space-y-6">
        <div className="rounded-lg border border-zinc-200 dark:border-zinc-600 bg-white dark:bg-zinc-800 p-4 shadow-sm dark:shadow-none">
          <h2 className="mb-3 font-mono text-xs text-zinc-600 dark:text-zinc-500">Session</h2>
          <CandidateForm
            {...form}
            templates={templates}
            onChange={(field, value) => setForm((f) => ({ ...f, [field]: value }))}
          />
        </div>
        <div className="flex gap-2">
          <button
            type="submit"
            disabled={saving || !form.templateId}
            className="rounded border border-cyan-500/50 bg-cyan-500/20 px-4 py-2 font-mono text-sm text-cyan-600 dark:text-cyan-400 hover:bg-cyan-500/30 disabled:opacity-50"
          >
            {saving ? "..." : "créer →"}
          </button>
          <button
            type="button"
            onClick={() => router.back()}
            className="rounded border border-zinc-300 dark:border-zinc-700 px-4 py-2 font-mono text-sm text-zinc-600 dark:text-zinc-400 hover:bg-zinc-100 dark:hover:bg-zinc-800"
          >
            annuler
          </button>
        </div>
      </form>
    </div>
  );
}
