import { useState, type FormEvent } from 'react';
import { Link } from 'react-router-dom';
import { useRegister } from '../hooks/useAuth';

export default function RegisterPage() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);
  const [validationErrors, setValidationErrors] = useState<{ username?: string; password?: string }>({});
  const register = useRegister();

  const validate = (): boolean => {
    const errors: { username?: string; password?: string } = {};
    if (username.length < 1) errors.username = 'Username is required';
    if (password.length < 6) errors.password = 'Password must be at least 6 characters';
    setValidationErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const handleSubmit = (e: FormEvent) => {
    e.preventDefault();
    setError(null);
    if (!validate()) return;
    register.mutate(
      { username, password },
      {
        onSuccess: () => setSuccess(true),
        onError: (err) => setError(err instanceof Error ? err.message : 'Registration failed'),
      },
    );
  };

  if (success) {
    return (
      <div className="min-h-screen flex items-center justify-center px-4">
        <div className="w-full max-w-sm space-y-6 text-center animate-slide-up">
          <div className="glass-sm bg-emerald-500/10 border-emerald-500/20 px-4 py-3 text-sm text-emerald-300">
            Account created successfully!
          </div>
          <Link
            to="/login"
            className="inline-block btn-primary px-6 py-2.5 text-sm font-medium"
          >
            <span>Go to Login</span>
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center px-4 relative overflow-hidden">
      <div className="absolute top-1/4 right-1/4 w-96 h-96 bg-emerald-500/10 rounded-full blur-[120px] animate-glow-pulse" />
      <div className="absolute bottom-1/3 left-1/3 w-80 h-80 bg-blue-500/10 rounded-full blur-[100px] animate-glow-pulse" style={{ animationDelay: '1.5s' }} />

      <div className="w-full max-w-sm space-y-8 animate-slide-up">
        <div className="text-center">
          <h1 className="text-3xl font-bold text-gradient">Signal Dashboard</h1>
          <p className="mt-2 text-sm text-gray-400">Create a new account</p>
        </div>

        <form onSubmit={handleSubmit} className="glass p-6 space-y-5">
          {error && (
            <div className="glass-sm bg-red-500/10 border-red-500/20 px-4 py-3 text-sm text-red-300">
              {error}
            </div>
          )}

          <div>
            <label htmlFor="username" className="block text-sm font-medium text-gray-300 mb-1.5">
              Username
            </label>
            <input
              id="username"
              type="text"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              className="w-full input-glass px-3 py-2.5 text-sm"
              placeholder="Enter username"
            />
            {validationErrors.username && (
              <p className="mt-1 text-xs text-red-400">{validationErrors.username}</p>
            )}
          </div>

          <div>
            <label htmlFor="password" className="block text-sm font-medium text-gray-300 mb-1.5">
              Password
            </label>
            <input
              id="password"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="w-full input-glass px-3 py-2.5 text-sm"
              placeholder="Min 6 characters"
            />
            {validationErrors.password && (
              <p className="mt-1 text-xs text-red-400">{validationErrors.password}</p>
            )}
          </div>

          <button
            type="submit"
            disabled={register.isPending}
            className="w-full btn-primary px-4 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <span>{register.isPending ? 'Creating account…' : 'Create account'}</span>
          </button>
        </form>

        <p className="text-center text-sm text-gray-400">
          Already have an account?{' '}
          <Link to="/login" className="text-blue-400 hover:text-blue-300 transition-colors duration-200">
            Sign in
          </Link>
        </p>
      </div>
    </div>
  );
}
