'use client';

import { useState, useEffect, useRef } from 'react';
import { supabase } from '@/lib/supabase';
import { useRouter } from 'next/navigation';
import 'leaflet/dist/leaflet.css';

export default function Login() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [showPassword, setShowPassword] = useState(false);
  const router = useRouter();
  const mapRef = useRef(null);
  const mapInstanceRef = useRef(null);

  useEffect(() => {
    let active = true;

    // Dynamically load Leaflet for the background map
    import('leaflet').then((L) => {
      if (!active) return;

      if (!mapInstanceRef.current && mapRef.current) {
        // Initialize map centered on Pontianak
        const map = L.map(mapRef.current, {
          center: [-0.0227, 109.3340],
          zoom: 13,
          zoomControl: false,
          dragging: false,
          scrollWheelZoom: false,
          doubleClickZoom: false,
          boxZoom: false,
          keyboard: false,
          attributionControl: false
        });
        
        // Use CartoDB Positron for a clean, light background
        L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', {
          maxZoom: 19,
          subdomains: 'abcd'
        }).addTo(map);

        mapInstanceRef.current = map;

        // Force resize recalculation to ensure tiles render immediately
        setTimeout(() => {
          if (active && mapInstanceRef.current) {
            mapInstanceRef.current.invalidateSize();
          }
        }, 150);
      }
    });

    return () => {
      active = false;
      if (mapInstanceRef.current) {
        mapInstanceRef.current.remove();
        mapInstanceRef.current = null;
      }
    };
  }, []);

  const handleLogin = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    const { data, error: authError } = await supabase.auth.signInWithPassword({
      email,
      password,
    });

    if (authError) {
      setError(authError.message);
      setLoading(false);
      return;
    }

    // Check if they need password rotation
    const { data: profile } = await supabase
      .from('profiles')
      .select('password_changed')
      .eq('id', data.user.id)
      .single();

    if (profile && profile.password_changed === false) {
      router.push('/change-password');
    } else {
      router.push('/');
    }
  };

  return (
    <div style={{
      position: 'relative',
      minHeight: '100vh',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      fontFamily: '"Inter", sans-serif',
      overflow: 'hidden'
    }}>
      {/* Return to Dashboard Button */}
      <button
        onClick={() => router.push('/')}
        style={{
          position: 'absolute',
          top: '24px',
          left: '24px',
          zIndex: 10,
          background: 'rgba(255, 255, 255, 0.85)',
          backdropFilter: 'blur(8px)',
          WebkitBackdropFilter: 'blur(8px)',
          border: '1px solid rgba(255, 255, 255, 0.6)',
          borderRadius: '14px',
          padding: '10px 18px',
          display: 'flex',
          alignItems: 'center',
          gap: '8px',
          color: '#1e293b',
          fontWeight: '600',
          fontSize: '0.9rem',
          cursor: 'pointer',
          boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.15)',
          transition: 'all 0.2s',
          outline: 'none'
        }}
        onMouseOver={(e) => {
          e.currentTarget.style.transform = 'translateY(-2px)';
          e.currentTarget.style.background = 'rgba(255, 255, 255, 0.95)';
        }}
        onMouseOut={(e) => {
          e.currentTarget.style.transform = 'translateY(0)';
          e.currentTarget.style.background = 'rgba(255, 255, 255, 0.85)';
        }}
      >
        <i className="fas fa-arrow-left" style={{ color: 'var(--primary, #3b82f6)' }}></i>
        <span>Kembali ke Dasbor</span>
      </button>

      {/* Dynamic Leaflet Background */}
      <div 
        ref={mapRef} 
        style={{
          position: 'absolute',
          top: 0, left: 0, right: 0, bottom: 0,
          width: '100%',
          height: '100%',
          zIndex: 1,
          filter: 'brightness(0.95)'
        }} 
      />

      {/* Glassmorphism Dark/Blur Overlay */}
      <div style={{
        position: 'absolute',
        top: 0, left: 0, right: 0, bottom: 0,
        zIndex: 2,
        background: 'rgba(15, 23, 42, 0.45)', // Slightly reduced opacity for a clearer view of the map
        backdropFilter: 'blur(4px)', // Reduced from 10px
        WebkitBackdropFilter: 'blur(4px)'
      }} />

      {/* Login Card */}
      <div style={{
        background: 'rgba(255, 255, 255, 0.85)',
        backdropFilter: 'blur(8px)', // Reduced from 20px
        WebkitBackdropFilter: 'blur(8px)',
        padding: '40px',
        borderRadius: '24px',
        boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.5)',
        width: '100%',
        maxWidth: '400px',
        textAlign: 'center',
        border: '1px solid rgba(255, 255, 255, 0.6)',
        zIndex: 10
      }}>
        <div style={{
          background: 'var(--primary, #3b82f6)',
          width: '60px', height: '60px',
          borderRadius: '50%',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'white', fontSize: '24px',
          margin: '0 auto 20px auto',
          boxShadow: '0 10px 15px -3px rgba(59, 130, 246, 0.5)'
        }}>
          <i className="fas fa-hands-holding-circle"></i>
        </div>
        <h2 style={{ margin: '0 0 8px 0', color: '#1e293b', fontSize: '1.8rem', fontWeight: '800' }}>Sinergi Umat</h2>
        <p style={{ margin: '0 0 24px 0', color: '#64748b', fontSize: '0.95rem' }}>Portal Manajemen Bantuan & Geotagging</p>

        {error && (
          <div style={{ background: '#fee2e2', color: '#ef4444', padding: '10px', borderRadius: '8px', marginBottom: '16px', fontSize: '0.85rem', fontWeight: '500' }}>
            <i className="fas fa-exclamation-circle" style={{ marginRight: '5px' }}></i> {error}
          </div>
        )}

        <form onSubmit={handleLogin} style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
          <div style={{ textAlign: 'left' }}>
            <label style={{ display: 'block', fontSize: '0.85rem', color: '#475569', marginBottom: '6px', fontWeight: '600' }}>Email</label>
            <input 
              type="email" 
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              style={{
                width: '100%', padding: '12px 16px', borderRadius: '12px',
                border: '1px solid #cbd5e1', background: 'white',
                outline: 'none', transition: 'all 0.2s', color: '#1e293b',
                boxShadow: 'inset 0 2px 4px 0 rgba(0, 0, 0, 0.05)'
              }}
              onFocus={(e) => e.target.style.borderColor = 'var(--primary, #3b82f6)'}
              onBlur={(e) => e.target.style.borderColor = '#cbd5e1'}
              required 
            />
          </div>
          <div style={{ textAlign: 'left' }}>
            <label style={{ display: 'block', fontSize: '0.85rem', color: '#475569', marginBottom: '6px', fontWeight: '600' }}>Kata Sandi</label>
            <div style={{ position: 'relative' }}>
              <input 
                type={showPassword ? 'text' : 'password'} 
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                style={{
                  width: '100%', padding: '12px 44px 12px 16px', borderRadius: '12px',
                  border: '1px solid #cbd5e1', background: 'white',
                  outline: 'none', transition: 'all 0.2s', color: '#1e293b',
                  boxShadow: 'inset 0 2px 4px 0 rgba(0, 0, 0, 0.05)'
                }}
                onFocus={(e) => e.target.style.borderColor = 'var(--primary, #3b82f6)'}
                onBlur={(e) => e.target.style.borderColor = '#cbd5e1'}
                required 
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                style={{
                  position: 'absolute',
                  right: '14px',
                  top: '50%',
                  transform: 'translateY(-50%)',
                  background: 'none',
                  border: 'none',
                  color: '#94a3b8',
                  cursor: 'pointer',
                  padding: '4px',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: '1rem',
                  outline: 'none'
                }}
                title={showPassword ? 'Sembunyikan Kata Sandi' : 'Tampilkan Kata Sandi'}
              >
                <i className={showPassword ? 'fas fa-eye-slash' : 'fas fa-eye'}></i>
              </button>
            </div>
          </div>
          <button 
            type="submit" 
            disabled={loading}
            style={{
              width: '100%', padding: '14px', borderRadius: '12px',
              background: 'var(--primary, #3b82f6)', color: 'white',
              border: 'none', fontWeight: '600', fontSize: '1rem',
              cursor: loading ? 'not-allowed' : 'pointer',
              marginTop: '8px', transition: 'all 0.2s',
              opacity: loading ? 0.8 : 1,
              boxShadow: loading ? 'none' : '0 4px 6px -1px rgba(59, 130, 246, 0.5)'
            }}
            onMouseOver={(e) => { if(!loading) e.target.style.transform = 'translateY(-2px)' }}
            onMouseOut={(e) => { if(!loading) e.target.style.transform = 'translateY(0)' }}
          >
            {loading ? <><i className="fas fa-spinner fa-spin"></i> Memverifikasi...</> : 'Masuk ke Dasbor'}
          </button>
        </form>
      </div>
    </div>
  );
}
