'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { requestOTP, verifyOTP, getMe } from '../../lib/api';

export default function LoginPage() {
  const router = useRouter();
  const [email, setEmail] = useState('');
  const [code, setCode] = useState('');
  const [step, setStep] = useState('email'); // 'email' or 'code'
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [checkingSession, setCheckingSession] = useState(true);

  // Check if already logged in
  useEffect(() => {
    const token = localStorage.getItem('adminToken');
    if (token) {
      // Verify token is still valid
      getMe().then(({ user }) => {
        if (user.role === 'admin') {
          window.location.href = '/admin/dashboard';
        } else {
          localStorage.removeItem('adminToken');
          setCheckingSession(false);
        }
      }).catch(() => {
        localStorage.removeItem('adminToken');
        setCheckingSession(false);
      });
    } else {
      setCheckingSession(false);
    }
  }, []);

  const handleRequestOTP = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);

    try {
      const result = await requestOTP(email);
      setStep('code');
      // Для админов код приходит в ответе (временно)
      if (result._code) {
        setCode(result._code);
      }
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleVerifyOTP = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);

    try {
      console.log('[LOGIN] Verifying OTP...');
      const result = await verifyOTP(email, code);
      console.log('[LOGIN] Verify result:', result);

      const { token, user } = result;

      if (!token) {
        console.log('[LOGIN] No token in response!');
        setError('No token received');
        return;
      }

      console.log('[LOGIN] Token received, saving...');
      localStorage.setItem('adminToken', token);

      console.log('[LOGIN] User role:', user?.role);

      if (user?.role !== 'admin') {
        localStorage.removeItem('adminToken');
        setError('Access denied. Admin only.');
        setStep('email');
        return;
      }

      localStorage.setItem('adminUser', JSON.stringify(user));
      console.log('[LOGIN] Redirecting to dashboard...');
      window.location.href = '/admin/dashboard';
    } catch (err) {
      console.log('[LOGIN] Error:', err);
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  if (checkingSession) {
    return (
      <div style={styles.container}>
        <div style={styles.card}>
          <p style={{ textAlign: 'center', color: 'var(--text-muted)' }}>Loading...</p>
        </div>
      </div>
    );
  }

  return (
    <div style={styles.container}>
      <div style={styles.card}>
        <h1 style={styles.logo}>WellNuo</h1>
        <p style={styles.subtitle}>Admin Panel</p>

        {error && <div style={styles.error}>{error}</div>}

        {step === 'email' ? (
          <form onSubmit={handleRequestOTP}>
            <label style={styles.label}>Email</label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="admin@wellnuo.com"
              style={styles.input}
              required
              autoFocus
            />
            <button type="submit" style={styles.button} disabled={loading}>
              {loading ? 'Sending...' : 'Send Code'}
            </button>
          </form>
        ) : (
          <form onSubmit={handleVerifyOTP}>
            <p style={styles.info}>Code sent to <strong>{email}</strong></p>
            <label style={styles.label}>Verification Code</label>
            <input
              type="text"
              value={code}
              onChange={(e) => setCode(e.target.value)}
              placeholder="123456"
              style={styles.input}
              maxLength={6}
              required
              autoFocus
            />
            <button type="submit" style={styles.button} disabled={loading}>
              {loading ? 'Verifying...' : 'Sign In'}
            </button>
            <button
              type="button"
              onClick={() => { setStep('email'); setCode(''); }}
              style={styles.linkButton}
            >
              Use different email
            </button>
          </form>
        )}
      </div>
    </div>
  );
}

const styles = {
  container: {
    minHeight: '100vh',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    padding: '20px',
    background: 'var(--surface)',
  },
  card: {
    background: 'white',
    borderRadius: '12px',
    padding: '40px',
    width: '100%',
    maxWidth: '400px',
    boxShadow: '0 4px 20px rgba(0,0,0,0.08)',
  },
  logo: {
    fontSize: '28px',
    fontWeight: '700',
    color: 'var(--primary)',
    textAlign: 'center',
    marginBottom: '4px',
  },
  subtitle: {
    fontSize: '14px',
    color: 'var(--text-muted)',
    textAlign: 'center',
    marginBottom: '32px',
  },
  label: {
    display: 'block',
    fontSize: '14px',
    fontWeight: '500',
    color: 'var(--text-secondary)',
    marginBottom: '8px',
  },
  input: {
    width: '100%',
    padding: '12px 16px',
    fontSize: '16px',
    border: '1px solid var(--border)',
    borderRadius: '8px',
    marginBottom: '16px',
    outline: 'none',
    transition: 'border-color 0.2s',
  },
  button: {
    width: '100%',
    padding: '14px',
    fontSize: '16px',
    fontWeight: '600',
    color: 'white',
    background: 'var(--primary)',
    border: 'none',
    borderRadius: '8px',
    cursor: 'pointer',
    transition: 'background 0.2s',
  },
  linkButton: {
    width: '100%',
    padding: '12px',
    fontSize: '14px',
    color: 'var(--primary)',
    background: 'transparent',
    border: 'none',
    marginTop: '8px',
  },
  error: {
    background: '#FEE2E2',
    color: 'var(--error)',
    padding: '12px',
    borderRadius: '8px',
    fontSize: '14px',
    marginBottom: '16px',
  },
  info: {
    fontSize: '14px',
    color: 'var(--text-secondary)',
    marginBottom: '16px',
  },
};
