'use client';

import React, { useState } from 'react';
import { signIn } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';

export default function SignupPage() {
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSignup = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setIsLoading(true);
    setError(null);

    const formData = new FormData(e.currentTarget);
    const name = formData.get('name') as string;
    const email = formData.get('email') as string;
    const password = formData.get('password') as string;
    const confirmPassword = formData.get('confirmPassword') as string;

    if (password !== confirmPassword) {
      setError('Passwords do not match');
      setIsLoading(false);
      return;
    }

    if (password.length < 8) {
      setError('Password must be at least 8 characters');
      setIsLoading(false);
      return;
    }

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

      const data = await response.json();

      if (!response.ok) {
        setError(data.error || 'Failed to create account');
        setIsLoading(false);
        return;
      }

      // Redirect to verification page
      if (data.requiresVerification) {
        router.push(`/auth/verify-email?email=${encodeURIComponent(email)}`);
        return;
      }

      // Fallback: Auto sign in after successful signup
      await signIn('credentials', {
        email,
        password,
        callbackUrl: '/tasks',
      });
    } catch (err) {
      setError('Something went wrong. Please try again.');
      setIsLoading(false);
    }
  };

  const handleGoogleSignIn = () => {
    setIsLoading(true);
    signIn('google', { callbackUrl: '/tasks' });
  };

  return (
    <div className="weekly-auth-container">
      <div className="weekly-auth-card">
        {/* Logo */}
        <div className="weekly-auth-logo">
          My Weekly ToDo&apos;s
        </div>

        {/* Tagline */}
        <p className="weekly-auth-tagline">
          Start organizing your week beautifully.
        </p>

        {/* Error Message */}
        {error && (
          <div className="weekly-auth-error">
            {error}
          </div>
        )}

        <p className="weekly-auth-recommended">
          Recommended: Sign up with email
        </p>

        {/* Signup Form */}
        <form onSubmit={handleSignup} className="weekly-auth-form">
          <div className="weekly-auth-field">
            <input
              type="text"
              name="name"
              placeholder="Name"
              required
              autoComplete="name"
              className="weekly-auth-input"
            />
          </div>

          <div className="weekly-auth-field">
            <input
              type="email"
              name="email"
              placeholder="Email"
              required
              autoComplete="email"
              className="weekly-auth-input"
            />
          </div>

          <div className="weekly-auth-field">
            <input
              type="password"
              name="password"
              placeholder="Password"
              required
              minLength={8}
              autoComplete="new-password"
              className="weekly-auth-input"
            />
          </div>

          <div className="weekly-auth-field">
            <input
              type="password"
              name="confirmPassword"
              placeholder="Confirm Password"
              required
              minLength={8}
              autoComplete="new-password"
              className="weekly-auth-input"
            />
          </div>

          <button
            type="submit"
            disabled={isLoading}
            className="weekly-auth-button primary"
          >
            {isLoading ? 'Creating account...' : 'Create Account'}
          </button>
        </form>

        {/* Divider */}
        <div className="weekly-auth-divider">
          <span>or trust US Big Tech</span>
        </div>

        {/* Google Sign Up */}
        <button
          type="button"
          onClick={handleGoogleSignIn}
          disabled={isLoading}
          className="weekly-auth-button google"
        >
          <svg className="google-icon" viewBox="0 0 24 24" width="18" height="18">
            <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
            <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
            <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
            <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4 1.66l3-3C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
          </svg>
          Sign up with Google
        </button>

        {/* Apple Sign Up */}
        <button
          type="button"
          onClick={() => { setIsLoading(true); signIn('apple', { callbackUrl: '/tasks' }); }}
          disabled={isLoading}
          className="weekly-auth-button apple"
          style={{ marginTop: '0.75rem', backgroundColor: '#000', color: '#fff' }}
        >
          <svg className="apple-icon" viewBox="0 0 24 24" width="18" height="18" fill="currentColor">
            <path d="M16.365 21.492c-1.385 1.144-2.825 1.114-4.237.491-1.384-.622-2.735-.622-4.116 0-1.472.684-2.825.684-4.116-.279-5.1-4.144-6.31-11.458-2.67-15.002 1.442-1.383 3.08-1.745 4.503-1.745 1.471 0 2.883.682 3.86.682.95 0 2.61-.741 4.364-.741 1.748 0 3.35.532 4.417 1.838-3.647 1.956-3.08 6.906.653 8.358-.89 2.134-1.928 4.624-2.66 6.398zm-4.745-16.79c-.208-2.223 1.72-4.301 3.974-4.702.355 2.37-2.016 4.331-3.974 4.702z" />
          </svg>
          Sign up with Apple
        </button>

        {/* Microsoft Sign Up */}
        <button
          type="button"
          onClick={() => { setIsLoading(true); signIn('azure-ad', { callbackUrl: '/tasks' }); }}
          disabled={isLoading}
          className="weekly-auth-button"
          style={{ marginTop: '0.75rem', backgroundColor: '#0078D4', color: '#fff', border: '1px solid #0078D4' }}
        >
          <svg className="microsoft-icon" viewBox="0 0 21 21" width="18" height="18" fill="currentColor">
            <path d="M10 0H0v10h10V0zM21 0H11v10h10V0zM10 11H0v10h10V11zM21 11H11v10h10V11z" />
          </svg>
          Sign up with Microsoft
        </button>

        {/* Links */}
        <div className="weekly-auth-links">
          <span className="weekly-auth-text">Already have an account?</span>
          <Link href="/auth/login" className="weekly-auth-link">
            Log in
          </Link>
        </div>
      </div>

      {/* Footer */}
      <footer className="weekly-auth-footer">
        <p>Simple. Beautiful. Yours.</p>
      </footer>
    </div>
  );
}