"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";

const registerSchema = z.object({
  email: z.string().email(),
  password: z.string().min(12),
  fullName: z.string().optional(),
});

type FormData = z.infer<typeof registerSchema>;

export default function RegisterPage() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const role = searchParams.get("role") || "freelancer";
  
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const form = useForm<FormData>({ resolver: zodResolver(registerSchema) });

  async function onSubmit(data: FormData) {
    setLoading(true);
    try {
      const res = await fetch("/api/auth/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...data, role }),
      });

      if (!res.ok) throw new Error("Ошибка регистрации");

      router.push("/dashboard");
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50">
      <form onSubmit={form.handleSubmit(onSubmit)} className="w-full max-w-md p-8 rounded-xl shadow-sm bg-white">
        <h1 className="text-2xl font-bold mb-6">Регистрация</h1>

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

        <input {...form.register("email")} placeholder="Email" className="w-full mb-3 px-4 py-2 border rounded" />
        {form.formState.errors.email && (
          <p className="text-sm text-red-500 mb-2">{form.formState.errors.email.message}</p>
        )}

        <input {...form.register("password")} type="password" placeholder="Пароль (мин. 12 символов)" className="w-full mb-3 px-4 py-2 border rounded" />
        {form.formState.errors.password && (
          <p className="text-sm text-red-500 mb-2">{form.formState.errors.password.message}</p>
        )}

        <input {...form.register("fullName")} placeholder="Имя" className="w-full mb-4 px-4 py-2 border rounded" />

        <button type="submit" disabled={loading} className="w-full bg-blue-600 text-white py-3 rounded font-medium">
          {loading ? "Регистрация..." : `Зарегистрироваться как ${role === "client" ? "заказчик" : "фрилансер"}`}
        </button>

        <p className="text-center mt-4 text-sm">
          Уже есть аккаунт?{" "}
          <Link href="/auth/login" className="text-blue-600">Войти</Link>
        </p>
      </form>
    </div>
  );
}
