import React, { useState, FormEvent } from 'react';
import { apiService } from '../services/api';
import { analyticsService } from '../services/analyticsService';
import { SutStatus, User } from '../types';
import { Alert, Button, Input } from './ui';

interface LoginProps {
  onLogin: (user: User) => void;
}

const Login: React.FC<LoginProps> = ({ onLogin }) => {
  const [mode, setMode] = useState<'login' | 'signup'>('login');
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [email, setEmail] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [rememberMe, setRememberMe] = useState(true);
  const [error, setError] = useState('');
  const [status, setStatus] = useState<SutStatus | null>(null);
  const [loading, setLoading] = useState(false);

  React.useEffect(() => {
    apiService
      .getSutStatus()
      .then((response) => setStatus(response))
      .catch(() => setStatus(null));
  }, []);

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);

    try {
      console.log('Login: Starting login attempt for mode:', mode);
      const response =
        mode === 'signup'
          ? await apiService.signup({ username, password, email: email || undefined })
          : await apiService.login({ username, password });
      
      console.log('Login: API response received:', response);
      
      // Track authentication event
      if (mode === 'signup') {
        analyticsService.trackSignup(username);
      } else {
        analyticsService.trackLogin(username);
      }
      
      // Call onLogin to update app state
      onLogin(response.user);
      console.log('Login: onLogin callback completed, navigating to dashboard');
      
      // Navigate to dashboard using window.location to ensure navigation happens
      // This bypasses React Router and forces a hard navigation
      const baseUrl = window.location.pathname.includes('/login') ? window.location.origin : window.location.href;
      console.log('Login: Setting window.location to /dashboard');
      window.location.href = baseUrl + '/dashboard';
    } catch (err: any) {
      console.error('Login: Error during login/signup:', err);
      setLoading(false);
      const backendError = err.response?.data?.error;
      if (mode === 'signup' && backendError === 'Username already exists') {
        setError('Username already exists. Please choose a different username.');
      } else {
        setError(backendError || (mode === 'signup' ? 'Signup failed. Please try again.' : 'Invalid credentials. Please try again.'));
      }
    }
    // Note: Not calling setLoading(false) here - page will reload due to window.location.href
  };

  const formatUtc = (value: string | null | undefined): string => {
    if (!value) {
      return 'Unavailable';
    }

    const parsed = new Date(value);
    if (Number.isNaN(parsed.getTime())) {
      return value;
    }

    return parsed.toLocaleString();
  };

  return (
    <div className="w-full max-w-md">
      <div className="card-parchment shadow-epic border border-gold-dark/30">
        <h1 className="text-3xl md:text-4xl text-center text-text-primary mb-2">Enter the Fellowship</h1>
        <p className="text-center text-pending mb-6 italic">One does not simply walk into Middle-earth without credentials.</p>

        <div className="mb-5 flex justify-center gap-2">
          <Button
            type="button"
            variant={mode === 'login' ? 'epic' : 'secondary'}
            onClick={() => setMode('login')}
            className="min-w-[120px]"
          >
            Login
          </Button>
          <Button
            type="button"
            variant={mode === 'signup' ? 'epic' : 'secondary'}
            onClick={() => setMode('signup')}
            className="min-w-[120px]"
          >
            Sign up
          </Button>
        </div>

        {error && (
          <Alert variant="error" title="The Gate Remains Closed" className="mb-4">
            {error}
          </Alert>
        )}

        <form onSubmit={handleSubmit} className="space-y-4" noValidate>
          <Input
            id="username"
            label="Username"
            value={username}
            onChange={(event) => setUsername(event.target.value)}
            required
            placeholder="e.g., frodo_baggins"
            autoComplete="username"
          />

          {mode === 'signup' && (
            <Input
              id="email"
              label="Email (optional)"
              value={email}
              onChange={(event) => setEmail(event.target.value)}
              placeholder="traveler@example.com"
              autoComplete="email"
            />
          )}

          <div>
            <Input
              id="password"
              label="Password"
              type={showPassword ? 'text' : 'password'}
              value={password}
              onChange={(event) => setPassword(event.target.value)}
              required
              placeholder="Enter your password"
              autoComplete="current-password"
            />
            {mode === 'signup' && (
              <p className="mt-2 text-xs text-text-secondary">
                Password requirements: minimum 8 characters and at least 1 number.
              </p>
            )}
            <button
              type="button"
              className="mt-2 text-sm text-forest hover:text-forest-light"
              onClick={() => setShowPassword((current) => !current)}
            >
              {showPassword ? 'Hide password' : 'Show password'}
            </button>
          </div>

          <label className="flex items-center gap-2 text-sm text-text-primary">
            <input
              type="checkbox"
              checked={rememberMe}
              onChange={(event) => setRememberMe(event.target.checked)}
              className="h-4 w-4 accent-gold"
            />
            Keep me in the Fellowship on this device
          </label>

          <Button type="submit" variant="epic" className="w-full" isLoading={loading}>
            {loading ? 'Opening the Gates...' : mode === 'signup' ? 'Create account' : 'Enter Middle-earth'}
          </Button>
        </form>

        <div className="mt-6 pt-4 border-t border-gold-dark/30 text-sm text-text-primary space-y-2">
          <p>
            Default password: <strong>fellowship123</strong>
          </p>
          <p className="mt-1 text-text-secondary">
            Try: frodo_baggins, samwise_gamgee, aragorn, legolas, gimli, gandalf
          </p>
          <p className="text-xs text-text-secondary">
            Last SUT restart (instance): <strong>{formatUtc(status?.instance_boot_time_utc)}</strong>
          </p>
        </div>
      </div>
    </div>
  );
};

export default Login;
