"use client";

import React, { useState } from "react";
import { useRouter } from "next/navigation";

const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const API_BASE = process.env.NEXT_PUBLIC_API_BASE_URL;

const RegPage = () => {
  const router = useRouter();

  const [firstName, setFirstName] = useState("");  // имя
  const [lastName, setLastName] = useState("");    // фамилия
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [rememberMe, setRememberMe] = useState(false);
  const [checkboxError, setCheckboxError] = useState(false);
  const [authError, setAuthError] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);

  const isEmailValid = emailRegex.test(email);
  const isFormValid =
    isEmailValid &&
    password.length > 0 &&
    firstName.trim().length > 0 &&
    lastName.trim().length > 0;

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!rememberMe) {
      setCheckboxError(true);
      return;
    }
    setCheckboxError(false);

    if (!isFormValid || !API_BASE) return;

    try {
      setAuthError("");
      setIsSubmitting(true);

      const res = await fetch(`${API_BASE}/auth/register`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify({
          email,
          password,
          first_name: firstName,
          last_name: lastName,
          // остальные поля можно не отправлять, если не обязательные
        }),
      });

      if (!res.ok) {
        let msg = "Ошибка регистрации";
        try {
          const data = await res.json();
          if (data.error) msg = data.error;
        } catch {
          const text = await res.text();
          if (text) msg = text;
        }
        setAuthError(msg);
        setIsSubmitting(false);
        return;
      }

      const data = await res.json();
      console.log("Регистрация успешна, ответ API:", data);
      router.push("/regCode");
    } catch (err) {
      setAuthError(err.message || "Ошибка сети");
      setIsSubmitting(false);
    }
  };

  return (
    <div className="min-h-screen w-full bg-[#90D2F9] flex items-center justify-center px-4">
      <div className="w-full max-w-md bg-white/10 rounded-2xl p-6 sm:p-8 shadow-lg relative">
        {(checkboxError || authError) && (
          <div
            className="absolute -top-10 left-0 w-full bg-red-500 text-white text-xs sm:text-sm font-montserrat px-3 py-2 rounded-t-2xl flex items-center justify-center shadow-md"
            role="alert"
          >
            {checkboxError
              ? "Вы не согласны с условиями использования"
              : authError}
          </div>
        )}

        <div className="flex items-center justify-between mb-4">
          <button
            type="button"
            onClick={() => router.back()}
            className="text-[#ebebeb] text-sm font-montserrat hover:underline"
          >
            Назад
          </button>
          <span className="flex-1 text-center font-montserrat text-white font-extrabold text-2xl">
            Регистрация
          </span>
          <span className="w-[48px]" />
        </div>

        <form onSubmit={handleSubmit} className="mt-2 space-y-4">
          {/* Имя */}
          <div className="space-y-1">
            <label className="block font-montserrat font-extrabold text-xs text-white">
              Имя
            </label>
            <input
              type="text"
              value={firstName}
              onChange={(e) => setFirstName(e.target.value)}
              className="w-full rounded-full bg-white px-4 py-2 text-sm font-montserrat text-black outline-none focus:ring-2 focus:ring-blue-200"
            />
            {firstName.trim().length === 0 && (
              <p className="text-[11px] text-red-600 font-montserrat">
                Введите имя
              </p>
            )}
          </div>

          {/* Фамилия */}
          <div className="space-y-1">
            <label className="block font-montserrat font-extrabold text-xs text-white">
              Фамилия
            </label>
            <input
              type="text"
              value={lastName}
              onChange={(e) => setLastName(e.target.value)}
              className="w-full rounded-full bg-white px-4 py-2 text-sm font-montserrat text-black outline-none focus:ring-2 focus:ring-blue-200"
            />
            {lastName.trim().length === 0 && (
              <p className="text-[11px] text-red-600 font-montserrat">
                Введите фамилию
              </p>
            )}
          </div>

          {/* Почта */}
          <div className="space-y-1">
            <label className="block font-montserrat font-extrabold text-xs text-white">
              Почта
            </label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="w-full rounded-full bg-white px-4 py-2 text-sm font-montserrat text-black outline-none focus:ring-2 focus:ring-blue-200"
            />
            {!isEmailValid && email.length > 0 && (
              <p className="text-[11px] text-red-600 font-montserrat">
                Введите корректный email
              </p>
            )}
          </div>

          {/* Пароль */}
          <div className="space-y-1">
            <label className="block font-montserrat font-extrabold text-xs text-white">
              Пароль
            </label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="w-full rounded-full bg-white px-4 py-2 text-sm font-montserrat text-black outline-none focus:ring-2 focus:ring-blue-200"
            />
          </div>

          {/* Чекбокс */}
          <div className="flex items-start space-x-2">
            <button
              type="button"
              onClick={() => {
                setRememberMe((prev) => !prev);
                if (!rememberMe) setCheckboxError(false);
              }}
              className={`w-5 h-5 rounded-full border border-white flex items-center justify-center ${
                rememberMe ? "bg-white" : "bg-transparent"
              }`}
            >
              {rememberMe && (
                <span className="h-2 w-2 rounded-full bg-[#90D2F9]" />
              )}
            </button>
            <p className="font-montserrat text-[10px] leading-[12px] text-white">
              Подтверждаю, что я прочитал условия использования данного
              приложения
            </p>
          </div>

          {/* Кнопка Регистрация */}
          <button
            type="submit"
            disabled={!isFormValid || isSubmitting}
            className={`mt-4 w-full rounded-full py-2 text-center font-montserrat font-extrabold text-sm transition-colors
              ${
                isFormValid && !isSubmitting
                  ? "bg-green-500 text-white hover:bg-green-600"
                  : "bg-white text-[#C4C4C4] cursor-not-allowed"
              }`}
          >
            {isSubmitting ? "Отправка..." : "Регистрация"}
          </button>
        </form>
      </div>
    </div>
  );
};

export default RegPage;
