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

const ComponentsAuthLoginForm = () => {
    const router = useRouter();
    const searchParams = useSearchParams();
    const nextUrl = searchParams.get('next') || '/';

    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');

    const [loading, setLoading] = useState(false);
    const [err, setErr] = useState<string | null>(null);
    const [msg, setMsg] = useState<string | null>(null);

    const submitForm = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        setErr(null);
        setMsg(null);

        if (!email || !password) {
            setErr('Please enter email and password.');
            return;
        }

        setLoading(true);
        try {
            // ✅ Call your Next.js API (same origin), which sets d4a_uid, d4a_session, d4a_exp cookies
            const res = await fetch('https://ebay.backend.data4autos.com/api/auth/login', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                // credentials not required for same-origin, but harmless:
                credentials: 'same-origin',
                body: JSON.stringify({ email, password }),
            });

            const contentType = res.headers.get('content-type') || '';
            const data = contentType.includes('application/json') ? await res.json() : await res.text();
            console.log("data data", data)
            try {
                console.log('data:', data.store);
                sessionStorage.setItem('USERID', data.userid);
                sessionStorage.setItem('EBAYSTOREID', data.store.urlPath);
                localStorage.setItem('data4auto_uid', data.userid);
                localStorage.setItem('d4a_email', data.email);
                data?.payment?.stripeSessionId && localStorage.setItem('payment_session', data?.payment?.stripeSessionId);

                console.log('set sessionStorage USERID');
            } catch {
                console.log('no sessionStorage');
            }

            if (!res.ok) {
                throw new Error((typeof data === 'object' && (data?.message || data?.error)) || `Login failed (${res.status})`);
            }

            // (DEV ONLY) quick check that cookies were set:
            if (process.env.NODE_ENV !== 'production') {
                try {
                    const who = await fetch('/api/debug/whoami', { cache: 'no-store' }).then((r) => r.json());
                    console.log('whoami:', who);

                } catch { }
            }

            setMsg('Login successful!');
            setTimeout(() => router.push(nextUrl), 500);
        } catch (e: any) {
            setErr(e?.message || 'Something went wrong. Please try again.');
        } finally {
            setLoading(false);
        }
    };

    return (
        <form className="space-y-5 dark:text-white" onSubmit={submitForm}>
            {/* Alerts */}
            {err && <div className="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">{err}</div>}
            {msg && <div className="rounded-md border border-green-200 bg-green-50 px-3 py-2 text-sm text-green-700">{msg}</div>}

            {/* Email */}
            <div>
                <label htmlFor="Email">Email</label>
                <div className="relative text-white-dark">
                    <input
                        id="Email"
                        type="email"
                        placeholder="Enter Email"
                        className="form-input ps-10 placeholder:text-white-dark"
                        value={email}
                        onChange={(e) => setEmail(e.target.value)}
                        autoComplete="email"
                    />
                    <span className="absolute start-4 top-1/2 -translate-y-1/2">
                        <IconMail fill={true} />
                    </span>
                </div>
            </div>

            {/* Password */}
            <div>
                <label htmlFor="Password">Password</label>
                <div className="relative text-white-dark">
                    <input
                        id="Password"
                        type="password"
                        placeholder="Enter Password"
                        className="form-input ps-10 placeholder:text-white-dark"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        autoComplete="current-password"
                    />
                    <span className="absolute start-4 top-1/2 -translate-y-1/2">
                        <IconLockDots fill={true} />
                    </span>
                </div>
            </div>

            {/* Optional newsletter */}
            <div>
                <label className="flex cursor-pointer items-center">
                    <input type="checkbox" className="form-checkbox bg-white dark:bg-black" />
                    <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(67,97,238,0.44)] disabled:cursor-not-allowed disabled:opacity-70"
            >
                {loading ? 'Signing in…' : 'Sign in'}
            </button> */}
          <button
            type="submit"
            disabled={loading}
            className="btn w-full border-0 uppercase shadow-[0_10px_20px_-10px_rgba(25,212,251,0.44)] disabled:cursor-not-allowed disabled:opacity-70 !mt-6 bg-[linear-gradient(135deg,#0EA5E9_0%,#19D4FB_50%,#67E8F9_100%)] text-white hover:bg-[linear-gradient(135deg,#67E8F9_0%,#19D4FB_50%,#0EA5E9_100%)]"
            >
                {loading ? 'Signing in…' : 'Sign in'}
            </button>
        </form>
    );
};

export default ComponentsAuthLoginForm;
