import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import '../App.css';

export default function Login() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [rememberMe, setRememberMe] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  // Toast state: array of toasts
  const [toasts, setToasts] = useState([]);

  const navigate = useNavigate();

  // Load attempt count from localStorage on mount
  useEffect(() => {
    const saved = localStorage.getItem('loginAttempts');
    if (saved) {
      const attempts = JSON.parse(saved);
      const now = Date.now();
      const validAttempts = {};
      for (const [key, value] of Object.entries(attempts)) {
        if (now - value.timestamp < 3600000) {
          validAttempts[key] = value;
        }
      }
      localStorage.setItem('loginAttempts', JSON.stringify(validAttempts));
    }
  }, []);

  const getAttemptCount = (email) => {
    const attempts = JSON.parse(localStorage.getItem('loginAttempts') || '{}');
    return attempts[email]?.count || 0;
  };

  const incrementAttempt = (email) => {
    const attempts = JSON.parse(localStorage.getItem('loginAttempts') || '{}');
    const now = Date.now();
    attempts[email] = {
      count: (attempts[email]?.count || 0) + 1,
      timestamp: now,
    };
    localStorage.setItem('loginAttempts', JSON.stringify(attempts));
  };

  const clearAttempts = (email) => {
    const attempts = JSON.parse(localStorage.getItem('loginAttempts') || '{}');
    delete attempts[email];
    localStorage.setItem('loginAttempts', JSON.stringify(attempts));
  };

  // Add toast
// Add toast with 5-second timer
const addToast = (message, type = 'danger') => {
  const id = Date.now();
  const duration = 5000; // 5 seconds

  // Add toast
  setToasts(prev => [
    ...prev,
    { id, message, type, createdAt: Date.now(), duration, progress: 100 }
  ]);

  // Start interval to update progress every 50ms
  const interval = setInterval(() => {
    setToasts(prev => 
      prev.map(toast => 
        toast.id === id 
          ? { 
              ...toast, 
              progress: Math.max(0, toast.progress - (30 / duration) * 100) 
            }
          : toast
      )
    );
  }, 30);

  // Auto-dismiss after duration
  setTimeout(() => {
    clearInterval(interval);
    setToasts(prev => prev.filter(t => t.id !== id));
  }, duration);
};
  // Remove toast by ID
  const removeToast = (id) => {
    setToasts(prev => prev.filter(t => t.id !== id));
  };

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

    if (!email || !password) {
      setError('Please fill in all fields');
      setLoading(false);
      return;
    }

    const attemptCount = getAttemptCount(email);
    if (attemptCount >= 6) {
      addToast(`You've exceeded login attempts for ${email}. Please reset your password.`, 'danger');
      setLoading(false);
      return;
    }

    try {
      // 🔌 REPLACE WITH YOUR LOGIN API
      /*
      const response = await fetch('/api/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password, rememberMe }),
      });
      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.message || 'Invalid credentials');
      }

      // Success: clear attempts, save token, redirect
      clearAttempts(email);
      localStorage.setItem('token', data.token);
      navigate('/dashboard');
      return;
      */

      // 🧪 Simulate: let's say "test@example.com" / "123456" works
      if (email === 'test@example.com' && password === '123456') {
        clearAttempts(email);
        alert('✅ Login successful!');
        navigate('/dashboard');
      } else {
        throw new Error('Invalid email or password');
      }
    } catch (err) {
      incrementAttempt(email);
      const newCount = getAttemptCount(email);

      if (newCount >= 6) {
        addToast(`You've exceeded login attempts for ${email}. Please reset your password.`, 'danger');
        setError('');
      } else {
        setError(`${err.message} (${6 - newCount} attempts left)`);
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      {/* Background & Overlay */}
      <div className="position-absolute top-0 start-0 w-100 h-100" style={{ backgroundImage: 'url(/assets/images/3.png)', backgroundSize: 'cover', backgroundPosition: 'center' }}></div>
      {/* <div className="position-absolute top-0 start-0 w-100 h-100 bg-white opacity-75"></div> */}

      {/* Toast Stack (Right Side) */}
{/* Toast Stack (Right Side) */}
<div className="position-fixed top-4 end-4 d-flex flex-column gap-2" style={{ zIndex: 1050 }}>
  {toasts.map(toast => {
    // Calculate progress percentage (0% to 100%)
    const elapsed = Date.now() - toast.createdAt;
    const progress = Math.max(0, 100 - (elapsed / toast.duration) * 100);

    return (
      <div
        key={toast.id}
        className={`alert alert-${toast.type} p-3 rounded shadow-sm position-relative`}
        style={{
          width: '300px',
          borderLeft: `4px solid ${toast.type === 'danger' ? '#dc3545' : '#ffc107'}`,
          animation: 'slideInRight 0.3s ease-out',
        }}
      >
        <div className="d-flex justify-content-between align-items-start">
          <div className="d-flex align-items-center gap-2">
            <span style={{ fontSize: '1.1rem' }}>
              {toast.type === 'danger' ? '⚠️' : 'ℹ️'}
            </span>
            <p className="mb-0 small">{toast.message}</p>
          </div>
          <button
            type="button"
            className="btn-close"
            onClick={() => removeToast(toast.id)}
            style={{ fontSize: '0.8rem' }}
          ></button>
        </div>

        {/* Timer Progress Bar */}
        <div className="mt-2" style={{ height: '4px', backgroundColor: '#e9ecef', borderRadius: '2px', overflow: 'hidden' }}>
          <div
            className="h-100"
            style={{
              width: `${progress}%`,
              backgroundColor: toast.type === 'danger' ? '#dc3545' : '#ffc107',
              transition: 'width 0.1s linear',
            }}
          ></div>
        </div>
      </div>
    );
  })}
</div>
      {/* Login Card */}
      <div className="position-relative d-flex align-items-center justify-content-center min-vh-100 p-3">
        <div className="card shadow-sm border-0 rounded-4 p-4 w-100" style={{ maxWidth: '420px' }}>
          <div className="text-center mb-3">
            <h4 className="text-info fw-bold">Lolita</h4>
          </div>

          <form onSubmit={handleSubmit} className="text-start">
            <h5 className="mb-2 text-center">Sign in to account</h5>
            <p className="text-muted mb-4 small text-center">Enter your email & password to login</p>

            <div className="mb-3">
              <label className="form-label small">Email Address</label>
              <input
                type="email"
                className="form-control"
                style={{ borderColor: '#e0e0e0', backgroundColor: '#f0f8fa' }}
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="Enter email"
                required
                disabled={loading}
              />
            </div>

            <div className="mb-4">
              <label className="form-label small">Password</label>
              <div className="input-group">
                <input
                  type={showPassword ? 'text' : 'password'}
                  className="form-control"
                  style={{ borderColor: '#e0e0e0', backgroundColor: '#f0f8fa' }}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="••••••••"
                  required
                  disabled={loading}
                />
                <button
                  type="button"
                  className="btn btn-outline-secondary btn-sm"
                  onClick={() => setShowPassword(!showPassword)}
                  disabled={loading}
                >
                  {showPassword ? 'hide' : 'show'}
                </button>
              </div>
            </div>

            {error && <div className="alert alert-danger small p-2 mb-3">{error}</div>}

            <div className="d-flex justify-content-between align-items-center mb-4">
              <div className="form-check">
                <input
                  type="checkbox"
                  className="form-check-input"
                  id="rememberMe"
                  checked={rememberMe}
                  onChange={(e) => setRememberMe(e.target.checked)}
                  disabled={loading}
                />
                <label className="form-check-label small" htmlFor="rememberMe">
                  Remember me
                </label>
              </div>
              <Link to="/reset-password" className="text-decoration-none small" style={{ color: '#ff5757' }}>
                Forgot password?
              </Link>
            </div>

            <button
              type="submit"
              className="btn w-100 py-2 fw-medium"
              style={{
                backgroundColor: '#00b4d8',
                borderColor: '#00b4d8',
                color: 'white',
              }}
              disabled={loading}
            >
              {loading ? 'Signing in...' : 'Log in'}
            </button>
          </form>
        </div>
      </div>

      {/* Slide-in Animation */}
      <style jsx>{`
        @keyframes slideInRight {
          from { transform: translateX(100%); opacity: 0; }
          to { transform: translateX(0); opacity: 1; }
        }
      `}</style>
    </>
  );
}