import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Eye, EyeOff, Loader2, Check, X } from 'lucide-react';
import { SocialLoginButtons } from '../components/SocialLoginButtons';

export default function Register() {
  const navigate = useNavigate();
  const [showPassword, setShowPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    email: '',
    password: '',
    confirmPassword: '',
    acceptTerms: false,
  });

  // Password validation
  const passwordChecks = {
    length: formData.password.length >= 8,
    uppercase: /[A-Z]/.test(formData.password),
    lowercase: /[a-z]/.test(formData.password),
    number: /[0-9]/.test(formData.password),
    special: /[!@#$%^&*(),.?":{}|<>]/.test(formData.password),
    match: formData.password === formData.confirmPassword && formData.password.length > 0,
  };

  const isPasswordValid = Object.values(passwordChecks).every(Boolean);

  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!isPasswordValid) {
      setError('Por favor corrige los errores en la contrasena');
      return;
    }

    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch('/api/v1/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: formData.email,
          password: formData.password,
          firstName: formData.firstName,
          lastName: formData.lastName,
          acceptTerms: formData.acceptTerms,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || data.errors?.[0]?.message || 'Error al registrar');
      }

      setSuccess(true);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error desconocido');
    } finally {
      setIsLoading(false);
    }
  };

  if (success) {
    return (
      <div className="text-center">
        <div className="w-16 h-16 rounded-full bg-green-900/30 flex items-center justify-center mx-auto mb-4">
          <Check className="w-8 h-8 text-green-400" />
        </div>
        <h2 className="text-2xl font-bold text-white mb-2">Cuenta Creada</h2>
        <p className="text-gray-400 mb-6">
          Hemos enviado un email de verificacion a <span className="text-white">{formData.email}</span>.
          Por favor revisa tu bandeja de entrada y haz clic en el enlace para activar tu cuenta.
        </p>
        <Link to="/login" className="btn btn-primary">
          Ir a Iniciar Sesion
        </Link>
      </div>
    );
  }

  return (
    <div>
      <h2 className="text-2xl font-bold text-white mb-2">Crear Cuenta</h2>
      <p className="text-gray-400 mb-6">
        Unete a OrbiQuant y comienza a invertir
      </p>

      {error && (
        <div className="mb-4 p-3 rounded-lg bg-red-900/30 border border-red-800 text-red-400 text-sm">
          {error}
        </div>
      )}

      {/* Social Login Buttons */}
      <SocialLoginButtons mode="register" />

      <div className="relative my-6">
        <div className="absolute inset-0 flex items-center">
          <div className="w-full border-t border-gray-700"></div>
        </div>
        <div className="relative flex justify-center text-sm">
          <span className="px-4 bg-gray-900 text-gray-400">o registrate con email</span>
        </div>
      </div>

      <form onSubmit={handleRegister} className="space-y-4">
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="label">Nombre</label>
            <input
              type="text"
              className="input"
              placeholder="Juan"
              value={formData.firstName}
              onChange={(e) => setFormData({ ...formData, firstName: e.target.value })}
              required
            />
          </div>
          <div>
            <label className="label">Apellido</label>
            <input
              type="text"
              className="input"
              placeholder="Perez"
              value={formData.lastName}
              onChange={(e) => setFormData({ ...formData, lastName: e.target.value })}
              required
            />
          </div>
        </div>

        <div>
          <label className="label">Email</label>
          <input
            type="email"
            className="input"
            placeholder="tu@email.com"
            value={formData.email}
            onChange={(e) => setFormData({ ...formData, email: e.target.value })}
            required
          />
        </div>

        <div>
          <label className="label">Contrasena</label>
          <div className="relative">
            <input
              type={showPassword ? 'text' : 'password'}
              className="input pr-10"
              placeholder="********"
              value={formData.password}
              onChange={(e) => setFormData({ ...formData, password: e.target.value })}
              required
            />
            <button
              type="button"
              onClick={() => setShowPassword(!showPassword)}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-white"
            >
              {showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
            </button>
          </div>

          {/* Password requirements */}
          {formData.password.length > 0 && (
            <div className="mt-2 grid grid-cols-2 gap-1 text-xs">
              <PasswordCheck valid={passwordChecks.length} text="8+ caracteres" />
              <PasswordCheck valid={passwordChecks.uppercase} text="Una mayuscula" />
              <PasswordCheck valid={passwordChecks.lowercase} text="Una minuscula" />
              <PasswordCheck valid={passwordChecks.number} text="Un numero" />
              <PasswordCheck valid={passwordChecks.special} text="Un caracter especial" />
            </div>
          )}
        </div>

        <div>
          <label className="label">Confirmar Contrasena</label>
          <input
            type="password"
            className={`input ${
              formData.confirmPassword.length > 0 && !passwordChecks.match
                ? 'border-red-500 focus:border-red-500'
                : ''
            }`}
            placeholder="********"
            value={formData.confirmPassword}
            onChange={(e) => setFormData({ ...formData, confirmPassword: e.target.value })}
            required
          />
          {formData.confirmPassword.length > 0 && !passwordChecks.match && (
            <p className="text-red-400 text-xs mt-1">Las contrasenas no coinciden</p>
          )}
        </div>

        <label className="flex items-start gap-2 text-sm text-gray-400 cursor-pointer">
          <input
            type="checkbox"
            className="mt-1 rounded border-gray-600 bg-gray-700"
            checked={formData.acceptTerms}
            onChange={(e) => setFormData({ ...formData, acceptTerms: e.target.checked })}
            required
          />
          <span>
            Acepto los{' '}
            <a href="#" className="text-primary-400 hover:underline">
              Terminos y Condiciones
            </a>
            {' '}y el{' '}
            <a href="#" className="text-primary-400 hover:underline">
              Aviso de Riesgos
            </a>
          </span>
        </label>

        <button
          type="submit"
          disabled={isLoading || !isPasswordValid || !formData.acceptTerms}
          className="btn btn-primary w-full flex items-center justify-center gap-2"
        >
          {isLoading ? (
            <>
              <Loader2 className="w-5 h-5 animate-spin" />
              Creando cuenta...
            </>
          ) : (
            'Crear Cuenta'
          )}
        </button>
      </form>

      <div className="mt-6 text-center text-sm text-gray-400">
        Ya tienes cuenta?{' '}
        <Link to="/login" className="text-primary-400 hover:underline">
          Inicia Sesion
        </Link>
      </div>
    </div>
  );
}

function PasswordCheck({ valid, text }: { valid: boolean; text: string }) {
  return (
    <div className={`flex items-center gap-1 ${valid ? 'text-green-400' : 'text-gray-500'}`}>
      {valid ? <Check className="w-3 h-3" /> : <X className="w-3 h-3" />}
      {text}
    </div>
  );
}
