'use client';
import IconLockDots from '@/components/icon/icon-lock-dots';
import IconMail from '@/components/icon/icon-mail';
import { useRouter } from 'next/navigation';
import React, { useState } from 'react';
import axios from 'axios';

const ComponentsAuthLoginForm = () => {
    const router = useRouter();

    // ✅ Form state as object
    const [formData, setFormData] = useState({
        email: '',
        password: '',
        subscribe: false,
    });

    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    // ✅ Handle input changes
    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value, type, checked } = e.target;
        setFormData((prev) => ({
            ...prev,
            [name]: type === 'checkbox' ? checked : value,
        }));
    };

    // ✅ Submit form with Axios
    const submitForm = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        setError(null);
        setLoading(true);

        try {
           const res = await axios.post('/api/auth/login',formData);


            // ✅ Assuming backend returns token
            const data = res.data;
            console.log('Login success:', data);

            localStorage.setItem('token', data.token);

            router.push('/');
        } catch (err: any) {
            if (err.response) {
                setError(err.response.data.error || 'Login failed');
            } else {
                setError(err.message);
            }
        } finally {
            setLoading(false);
        }
    };

    return (
        <form className="space-y-5 dark:text-white" onSubmit={submitForm}>
            {error && <p className="text-red-500 text-sm">{error}</p>}

            <div>
                <label htmlFor="email">Email</label>
                <div className="relative text-white-dark">
                    <input
                        id="email"
                        name="email"
                        type="email"
                        placeholder="Enter Email"
                        className="form-input ps-10 placeholder:text-white-dark"
                        value={formData.email}
                        onChange={handleChange}
                        required
                    />
                    <span className="absolute start-4 top-1/2 -translate-y-1/2">
                        <IconMail fill={true} />
                    </span>
                </div>
            </div>

            <div>
                <label htmlFor="password">Password</label>
                <div className="relative text-white-dark">
                    <input
                        id="password"
                        name="password"
                        type="password"
                        placeholder="Enter Password"
                        className="form-input ps-10 placeholder:text-white-dark"
                        value={formData.password}
                        onChange={handleChange}
                        required
                    />
                    <span className="absolute start-4 top-1/2 -translate-y-1/2">
                        <IconLockDots fill={true} />
                    </span>
                </div>
            </div>

            <div>
                <label className="flex cursor-pointer items-center">
                    <input
                        type="checkbox"
                        name="subscribe"
                        checked={formData.subscribe}
                        className="form-checkbox bg-white dark:bg-black"
                        onChange={handleChange}
                    />
                    <span className="text-white-dark">Subscribe to weekly newsletter</span>
                </label>
            </div>

            <button
                type="submit"
                disabled={loading}
                className="btn btn-gradient !mt-6 w-full border-0 uppercase shadow-[0_10px_20px_-10px_rgba(55,121,185,0.44)]"
            >
                {loading ? 'Signing in...' : 'Sign in'}
            </button>
        </form>
    );
};

export default ComponentsAuthLoginForm;
