'use client';

import { useState, FormEvent, useEffect } from 'react';
import { useAuth } from '@/lib/auth';
import { API_URL } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';

const LoginPage = () => {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');
    const auth = useAuth();
    const [isLoggedIn, setIsLoggedIn] = useState(false); 

    useEffect(() => {
      console.log("API URL from env:", process.env.NEXT_PUBLIC_API_URL);
      console.log("Test var from env:", process.env.NEXT_PUBLIC_TEST_VAR);
  }, []);
  
    const handleSubmit = async (e: FormEvent) => {
      e.preventDefault();
      setError('');
      try {
          const formData = new URLSearchParams();
          formData.append('username', email);
          formData.append('password', password);
  
          const response = await fetch(`${API_URL}/auth/login`, {
              method: 'POST',
              headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
              body: formData,
          });
  
          if (!response.ok) {
              const errorData = await response.json();
              throw new Error(errorData.detail || 'Login failed');
          }
          
          const { id_token, uid } = await response.json();
          
          const userDetails = { uid, email, role: 'user' }; 
          auth.login(id_token, userDetails);
          setIsLoggedIn(true);
      } catch (err: any) {
        setError(err.message);
      }
    };
    
    if (isLoggedIn || auth.isAuthenticated) {
        // In a real app, this would be a redirect to '/'
        return <p>Redirecting...</p>;
    }
  
    return (
      <div className="flex items-center justify-center min-h-screen bg-gray-100">
        <Card className="w-full max-w-sm">
          <CardHeader>
            <CardTitle>Login</CardTitle>
          </CardHeader>
          <CardContent>
            {/* The form is now a div to prevent Server Action errors */}
            <div className="space-y-4">
              <div className="space-y-2">
                <label htmlFor="email">Email</label>
                <Input id="email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
              </div>
              <div className="space-y-2">
                <label htmlFor="password">Password</label>
                <Input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} required />
              </div>
              {error && <p className="text-sm text-red-500">{error}</p>}
              <Button onClick={handleSubmit} className="w-full">Login</Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  };

  export default LoginPage;