/* Updated to use new utility classes */
'use client';

import Link from 'next/link';
import { FormEvent, useState } from 'react';

type Errors = { email?: string; password?: string };

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

export default function LoginForm() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [remember, setRemember] = useState(true);
  const [showPassword, setShowPassword] = useState(false);
  const [errors, setErrors] = useState<Errors>({});
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);

  function validate(): Errors {
    const next: Errors = {};
    if (!email.trim()) next.email = 'Email is required.';
    else if (!EMAIL_RE.test(email)) next.email = 'Enter a valid email address.';
    if (!password) next.password = 'Password is required.';
    return next;
  }

  async function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const next = validate();
    setErrors(next);
    if (Object.keys(next).length > 0) return;

    setLoading(true);
    await new Promise((r) => setTimeout(r, 900));
    setLoading(false);
    setSuccess(true);
  }

  if (success) {
    return (
      <div className="text-center space-y-4">
        <div className="text-5xl text-green-500" aria-hidden="true">
          ✓
        </div>
        <h1 className="text-2xl font-semibold">You&apos;re in!</h1>
        <p className="text-gray-300">
          Welcome back. Your audience is waiting for your next stream.
        </p>
        <Link
          href="/"
          className="inline-block w-full py-2 bg-primary-600 text-white rounded hover:bg-primary-700 transition"
        >
          Go to home
        </Link>
      </div>
    );
  }

  return (
    <form className="space-y-6" onSubmit={handleSubmit} noValidate>
      {/* Header */}
      <div className="text-center space-y-1">
        <h1 className="text-xl font-bold">Log in to Live2030</h1>
        <p className="text-sm text-gray-300">Enter your details to continue streaming.</p>
      </div>

      {/* Social login */}
      <div className="flex gap-3">
        <button
          type="button"
          className="flex-1 flex items-center justify-center gap-2 py-2 border border-gray-600 rounded hover:bg-gray-700 transition"
        >
          <span className="text-lg font-bold">G</span> Google
        </button>
        <button
          type="button"
          className="flex-1 flex items-center justify-center gap-2 py-2 border border-gray-600 rounded hover:bg-gray-700 transition"
        >
          <span className="text-lg font-bold"></span> Apple
        </button>
      </div>

      {/* Divider */}
      <div className="relative flex items-center py-2">
        <div className="flex-1 h-px bg-gray-600" />
        <span className="px-2 text-sm text-gray-400">or continue with email</span>
        <div className="flex-1 h-px bg-gray-600" />
      </div>

      {/* Email */}
      <div className="form-field">
        <label htmlFor="login-email">Email</label>
        <input
          id="login-email"
          type="email"
          className="input-base"
          placeholder="you@example.com"
          autoComplete="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          aria-invalid={!!errors.email}
          aria-describedby={errors.email ? 'login-email-error' : undefined}
        />
        {errors.email && (
          <p id="login-email-error" className="error-text">
            {errors.email}
          </p>
        )}
      </div>

      {/* Password */}
      <div className="form-field">
        <div className="flex items-center justify-between">
          <label htmlFor="login-password">Password</label>
          <Link href="#" className="text-sm text-primary-400 hover:underline">
            Forgot password?
          </Link>
        </div>
        <div className="relative">
          <input
            id="login-password"
            type={showPassword ? 'text' : 'password'}
            className="input-base pr-20"
            placeholder="••••••••"
            autoComplete="current-password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            aria-invalid={!!errors.password}
            aria-describedby={errors.password ? 'login-password-error' : undefined}
          />
          <button
            type="button"
            className="absolute inset-y-0 right-3 flex items-center text-sm text-gray-400 hover:text-gray-200"
            onClick={() => setShowPassword((s) => !s)}
            aria-label={showPassword ? 'Hide password' : 'Show password'}
          >
            {showPassword ? 'Hide' : 'Show'}
          </button>
        </div>
        {errors.password && (
          <p id="login-password-error" className="error-text">
            {errors.password}
          </p>
        )}
      </div>

      {/* Remember */}
      <label className="flex items-center space-x-2">
        <input
          type="checkbox"
          className="h-4 w-4 rounded border-gray-600 text-primary-600 focus:ring-primary-500"
          checked={remember}
          onChange={(e) => setRemember(e.target.checked)}
        />
        <span className="text-sm text-gray-200">Keep me logged in</span>
      </label>

      {/* Submit */}
      <button type="submit" disabled={loading} className="btn-primary w-full">
        {loading ? (
          <svg
            className="animate-spin h-5 w-5 text-white"
            xmlns="http://www.w3.org/2000/svg"
            fill="none"
            viewBox="0 0 24 24"
            aria-label="Logging in"
          >
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
            <path
              className="opacity-75"
              fill="currentColor"
              d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"
            />
          </svg>
        ) : (
          'Log in'
        )}
      </button>

      {/* Footer */}
      <p className="text-center text-sm text-gray-400">
        New to Live2030?{' '}
        <Link href="/signup" className="text-primary-400 hover:underline">
          Create an account
        </Link>
      </p>
    </form>
  );
}