'use client';

import { useState } from 'react';
import axios from 'axios';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { API_BASE_URL } from "../../../lib/api-config";

export default function LoginPage() {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const router = useRouter();

    const API_URL = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:5000';

    const handleLogin = async (e: React.FormEvent) => {
        e.preventDefault();
        try {
            const res = await axios.post(`${API_BASE_URL}/api/login`, {email, password}, {
                withCredentials: true
            });
            
            if (res) {
              router.push('/dashboard');
            }
        } catch (err) {
            alert("Invalid credentials. Please verify your access");
        }
    };

    return (
        <div className="min-h-screen bg-wtihub-bg flex items-center justify-center px-4">
            <div className="w-full max-w-md bg-wtihub-surface p-8 rounded-2xl border border-wtihub-border shadow-2xl">
               <h1 className="text-3xl font-bold text-wtihub-green mb-2">Welcome Back</h1>
               <p className="text-gray-400 mb-8">Login to manage your digital streams.</p>

               <form onSubmit={handleLogin} className="space-y-6">
                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-2">Email Address</label>
                    <input
                      type="email"
                      required
                      className="w-full bg-wtihub-bg border border-wtihub-border p-3 rounded-lg text-wtihub-text focus:border-wtihub-green outline-none"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-2">Password</label>
                    <input 
                      type="password"
                      required
                      className="w-full bg-wtihub-bg border border-wtihub-border p-3 rounded-lg text-wtihub-text focus:border-wtihub-green outline-none"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                    />
                  </div>
                  <button type="submit" className="w-full btn-wtihub py-4 text-lg cursor-pointer">
                    Initialize Session
                  </button>
               </form>

               <p className="mt-6 text-center text-sm text-gray-500">
                    Already have an account? <Link href="/register" className="text-wtihub-green hover:underline">Register here</Link>
                </p>
            </div>
        </div>
    )
}