import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import Card from '@/shared/components/ui/Card';
import Input from '@/shared/components/ui/Input';
import Button from '@/shared/components/ui/Button';
import { useToast } from '@/shared/components/ui/Toast';
import { authService } from '@/shared/services/authService';

// Make sure 'default' is present here:
export default function LoginPage() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const navigate = useNavigate();
  const { addToast } = useToast() || {};

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!email || !password) {
      addToast?.('Please enter both email and password.', 'error');
      return;
    }

    setIsLoading(true);
    try {
      const res = await authService.login(email, password);
      
      if (res?.token) {
        localStorage.setItem('session_token', res.token);
      }

      addToast?.('Welcome back!', 'success');
      
      // ✅ 1. Navigate to root route "/" instead of "/dashboard"
      // navigate('/'); 

      // ✅ 2. Alternatively, perform a quick window reload to let App.jsx fetch me.php with the new session/token
      window.location.href = '/HZ-ProjectHub-v2/frontend/dist/';

    } catch (err) {
      console.error('Login error:', err);
      addToast?.(err.message || 'Invalid email or password.', 'error');
    } finally {
      setIsLoading(false);
    }
  };


  return (
    <div className="min-h-screen w-screen flex items-center justify-center bg-[var(--color-background)] p-4">
      <Card className="w-full max-w-md space-y-6 border border-[var(--color-border)] shadow-2xl">
        <div className="text-center space-y-2">
          <div className="inline-flex h-12 w-12 items-center justify-center rounded-2xl bg-gradient-to-tr from-blue-600 to-indigo-600 font-bold text-white text-xl shadow-lg shadow-blue-500/20">
            HZ
          </div>
          <h2 className="text-2xl font-bold text-white tracking-tight">HZ ProjectHub v2</h2>
          <p className="text-xs text-slate-400">Sign in to access your workspace and projects</p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          <Input
            label="Email Address"
            type="email"
            placeholder="admin@hzprojecthub.com"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
          />

          <Input
            label="Password"
            type="password"
            placeholder="••••••••"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
          />

          <Button type="submit" className="w-full mt-2" isLoading={isLoading}>
            Sign In
          </Button>
        </form>

        <div className="text-center pt-2 border-t border-[var(--color-border)] text-[11px] text-slate-500">
          <span>Enterprise Workspace • Session Managed via PHP</span>
        </div>
      </Card>
    </div>
  );
}