'use client'

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { authService } from '@/src/services/api';
import { trackEvent } from '@/src/components/MatomoAnalytics';

export default function AdminLogin() {
  const router = useRouter();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  // Set dark mode by default
  useEffect(() => {
    document.documentElement.classList.add('dark');
  }, []);

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

    try {
      const response = await authService.login(username, password);

      // Store token in localStorage
      localStorage.setItem('authToken', response.token);
      localStorage.setItem('tokenExpiry', String(Date.now() + 24 * 60 * 60 * 1000)); // 24 hours

      // Track successful login
      trackEvent('Admin', 'Login', 'Success');

      // Redirect to admin dashboard using window.location for static export
      window.location.href = '/upadaj/dashboard';
    } catch (err: any) {
      setError('Neispravno korisničko ime ili lozinka');
      console.error('Login error:', err);
      trackEvent('Admin', 'Login', 'Failed');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-[#060a14] py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-md w-full space-y-8">
        <div className="flex flex-col items-center">
          <img
            src="/logo.png"
            alt="Filamenteka"
            className="h-40 w-auto mb-6 drop-shadow-lg"
          />
          <h2
            className="text-center text-3xl font-black text-white tracking-tight"
            style={{ fontFamily: 'var(--font-display)' }}
          >
            Admin Prijava
          </h2>
          <p className="mt-2 text-center text-sm text-white/40">
            Prijavite se za upravljanje filamentima
          </p>
        </div>
        <form className="mt-8 space-y-6" onSubmit={handleLogin}>
          {error && (
            <div className="rounded-xl bg-red-500/10 border border-red-500/20 p-4">
              <p className="text-sm text-red-400">{error}</p>
            </div>
          )}
          <div className="space-y-3">
            <div>
              <label htmlFor="username" className="sr-only">
                Korisničko ime
              </label>
              <input
                id="username"
                name="username"
                type="text"
                autoComplete="username"
                required
                className="appearance-none relative block w-full px-4 py-3 border border-white/[0.08] placeholder-white/30 text-white rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-500/40 sm:text-sm bg-white/[0.04]"
                placeholder="Korisničko ime"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
              />
            </div>
            <div>
              <label htmlFor="password" className="sr-only">
                Lozinka
              </label>
              <input
                id="password"
                name="password"
                type="password"
                autoComplete="current-password"
                required
                className="appearance-none relative block w-full px-4 py-3 border border-white/[0.08] placeholder-white/30 text-white rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-500/40 sm:text-sm bg-white/[0.04]"
                placeholder="Lozinka"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
              />
            </div>
          </div>

          <div>
            <button
              type="submit"
              disabled={loading}
              className="group relative w-full flex justify-center py-3 px-4 border border-transparent text-sm font-semibold rounded-xl text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              style={{ boxShadow: '0 4px 14px rgba(59, 130, 246, 0.3)' }}
            >
              {loading ? 'Prijavljivanje...' : 'Prijavite se'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
