'use client';
import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import IconLockDots from '@/components/icon/icon-lock-dots';
import IconMail from '@/components/icon/icon-mail';
import IconUser from '@/components/icon/icon-user';

const API_BASE =
  process.env.NEXT_PUBLIC_API_BASE_URL?.replace(/\/$/, '') ||
  'https://api.socialbuddy.co/api/users';

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

  const [name, setName] = useState('');
  const [phonenumber, setPhonenumber] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState<string | null>(null);
  const [msg, setMsg] = useState<string | null>(null);

  const submitForm = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setErr(null);
    setMsg(null);

    if (!name || !email || !password || !phonenumber) {
      setErr('Please fill in all fields.');
      return;
    }

    setLoading(true);
    try {
      const res = await fetch(`${API_BASE}/api/auth/signup`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name,
          email,
          password,
          phonenumber,
        }),
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data?.message || 'Signup failed');

      setMsg('Signup successful!');
      setTimeout(() => router.push('/login'), 1000);
    } catch (e: any) {
      setErr(e?.message || 'Something went wrong.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={submitForm} className="dark:text-white">

      {/* Alerts */}
      {err && (
        <div className="mb-4 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
          {err}
        </div>
      )}
      {msg && (
        <div className="mb-4 rounded-md border border-green-200 bg-green-50 px-3 py-2 text-sm text-green-700">
          {msg}
        </div>
      )}

      <div className="space-y-4">

        {/* Name */}
        <div className="relative">
          <input
            type="text"
            placeholder="Full Name"
            value={name}
            onChange={(e) => setName(e.target.value)}
            className="w-full ps-10 py-3
              bg-[rgba(7,13,30,0.7)]
              border border-white/15 rounded-lg
              text-white placeholder:text-gray-400
              focus:outline-none focus:border-white/30"
          />
          <span className="absolute start-4 top-1/2 -translate-y-1/2 text-white">
            <IconUser fill />
          </span>
        </div>

        {/* Email */}
        <div className="relative">
          <input
            type="email"
            placeholder="Email Address"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className="w-full ps-10 py-3
              bg-[rgba(7,13,30,0.7)]
              border border-white/15 rounded-lg
              text-white placeholder:text-gray-400
              focus:outline-none focus:border-white/30"
          />
          <span className="absolute start-4 top-1/2 -translate-y-1/2 text-white">
            <IconMail fill />
          </span>
        </div>

        {/* Password */}
        <div className="relative">
          <input
            type="password"
            placeholder="Password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            className="w-full ps-10 py-3
              bg-[rgba(7,13,30,0.7)]
              border border-white/15 rounded-lg
              text-white placeholder:text-gray-400
              focus:outline-none focus:border-white/30"
          />
          <span className="absolute start-4 top-1/2 -translate-y-1/2 text-white">
            <IconLockDots fill />
          </span>
        </div>

        {/* Phone */}
        <div className="relative">
          <input
            type="tel"
            placeholder="Phone Number"
            value={phonenumber}
            onChange={(e) => setPhonenumber(e.target.value)}
            className="w-full ps-10 py-3
              bg-[rgba(7,13,30,0.7)]
              border border-white/15 rounded-lg
              text-white placeholder:text-gray-400
              focus:outline-none focus:border-white/30"
          />
          <span className="absolute start-4 top-1/2 -translate-y-1/2 text-white">
            📞
          </span>
        </div>

        {/* Submit */}
        <button
          disabled={loading}
          className="w-full py-3 rounded-xl text-lg font-semibold text-white
            bg-gradient-to-r from-blue-600 to-pink-500
            shadow-lg transition-all hover:opacity-90 hover:scale-[1.02]
            disabled:opacity-60"
        >
          {loading ? 'Creating account…' : 'SIGN UP'}
        </button>

      </div>
    </form>
  );
};

export default ComponentsAuthRegisterForm;
