"use client";

import { useState, useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { useAuth } from '@/context/AuthContext';
import { validatePersonnummer, lookupSwedishCity, validateAddress, lookupSwedishAddress, validateSwedishMobile, normalizeSwedishMobile } from '@/lib/validation';
import { FcGoogle } from 'react-icons/fc';
import '@/styles/Auth.css';

export default function RegisterPage() {
    const router = useRouter();
    const { login, isAuthenticated, loading: authLoading } = useAuth();
    const [formData, setFormData] = useState({
        name: '',
        username: '',
        email: '',
        password: '',
        confirmPassword: '',
        personnummer: '',
        mobile: '46',
        address: '',
        zip_code: '',
        city: '',
        country: 'Sverige',
        newsletter: false,
        terms: false,
    });
    const [error, setError] = useState('');
    const [successMessage, setSuccessMessage] = useState('');
    const [loading, setLoading] = useState(false);
    const [showTermsModal, setShowTermsModal] = useState(false);

    const processingGoogleAuth = useRef(false);

    useEffect(() => {
        if (!authLoading && isAuthenticated) {
            router.push('/me');
            return;
        }

        if (processingGoogleAuth.current) return;

        // Handle successful Google Redirect
        const params = new URLSearchParams(window.location.search);
        const token = params.get('token');
        const userData = params.get('user');
        if (token && userData) {
            processingGoogleAuth.current = true;
            try {
                login(token, JSON.parse(userData), true);
                window.history.replaceState({}, document.title, window.location.pathname);
                router.push('/me');
            } catch (e) {
                console.error("Failed to parse Google user data", e);
                processingGoogleAuth.current = false;
            }
        }
    }, [isAuthenticated, authLoading, router, login]);

    // Auto-fetch city when zip code is 5 digits
    useEffect(() => {
        const fetchCity = async () => {
            if (formData.zip_code.length === 5) {
                const city = await lookupSwedishCity(formData.zip_code);
                if (city) {
                    setFormData(prev => ({ ...prev, city }));
                }
            }
        };
        fetchCity();
    }, [formData.zip_code]);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setError('');

        if (formData.password !== formData.confirmPassword) {
            setError('Lösenorden matchar inte');
            return;
        }

        // Swedish Validations
        if (!validatePersonnummer(formData.personnummer)) {
            setError('Personnummer är ogiltigt. Kontrollera att datumet är korrekt och att formatet är ÅÅÅÅMMDD-XXXX.');
            return;
        }

        if (!validateAddress(formData.address)) {
            setError('Adressen måste innehålla både gatunamn och nummer.');
            return;
        }

        // Verify physical address exists (External API)
        try {
            const addressExists = await lookupSwedishAddress(formData.address, formData.zip_code, formData.city);
            if (!addressExists) {
                setError('Adressen verkar inte existera. Vänligen kontrollera stavning och adressnummer.');
                setLoading(false);
                return;
            }
        } catch (err) {
            console.error('Frontend address verification error:', err);
            // Fail open on network errors to avoid blocking users
        }

        if (!validateSwedishMobile(formData.mobile)) {
            setError('Mobilnummeret är ogiltigt. Det måste vara ett svenskt mobilnummer (t.ex. 070-123 45 67).');
            return;
        }

        const normalizedMobile = normalizeSwedishMobile(formData.mobile);

        const zipRegex = /^\d{5}$/;
        if (!zipRegex.test(formData.zip_code)) {
            setError('Postnummer måste bestå av 5 siffror');
            return;
        }

        if (!formData.terms) {
            setError('Du måste godkänna användarvillkoren');
            return;
        }

        setLoading(true);

        try {
            const res = await fetch('/api/auth/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    name: formData.name,
                    username: formData.username,
                    email: formData.email,
                    password: formData.password,
                    newsletter: formData.newsletter,
                    personnummer: formData.personnummer,
                    mobile: normalizedMobile,
                    address: formData.address,
                    zip_code: formData.zip_code,
                    city: formData.city,
                    country: formData.country,
                }),
            });

            const data = await res.json();

            if (!res.ok) {
                throw new Error(data.error || 'Registreringen misslyckades');
            }

            // Don't auto-login if account needs verification
            setSuccessMessage(data.message || 'Kontot har skapats! Kontrollera din e-post för att verifiera din adress.');
            setLoading(false);

            // Optional: Redirect to login after a few seconds or just show the message
            setTimeout(() => {
                router.push('/login');
            }, 5000);
        } catch (err: unknown) {
            if (err instanceof Error) {
                setError(err.message);
            } else {
                setError('Ett oväntat fel uppstod');
            }
            setLoading(false);
        }
    };

    const handleGoogleLogin = async () => {
        try {
            const res = await fetch('/api/auth/google/url');
            const data = await res.json();
            if (data.url) {
                window.location.href = data.url;
            } else {
                setError('Kunde inte starta Google-inloggning');
            }
        } catch {
            setError('Ett fel uppstod vid Google-inloggning');
        }
    };

    if (authLoading || isAuthenticated) {
        return null;
    }

    return (
        <div className="auth-page-container">
            <div className="profile-card card-md">
                <h2 className="auth-title">Skapa konto</h2>

                {successMessage && (
                    <div className="auth-success">
                        {successMessage}
                    </div>
                )}

                <p className="auth-subtitle">
                    Fyll i dina uppgifter nedan för att bli medlem
                </p>

                <form className="auth-form" onSubmit={handleSubmit}>
                    <div className="form-group">
                        <label className="form-label">Fullständigt namn</label>
                        <input
                            type="text"
                            required
                            className="form-input"
                            value={formData.name}
                            onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                        />
                    </div>

                    <div className="form-group">
                        <label className="form-label">Användarnamn</label>
                        <input
                            type="text"
                            required
                            className="form-input"
                            value={formData.username}
                            onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                        />
                    </div>

                    <div className="form-group">
                        <label className="form-label">E-postadress</label>
                        <input
                            type="email"
                            required
                            className="form-input"
                            value={formData.email}
                            onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                        />
                    </div>

                    <div className="form-group">
                        <label className="form-label">Lösenord</label>
                        <input
                            type="password"
                            required
                            className="form-input"
                            value={formData.password}
                            onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                        />
                    </div>

                    <div className="form-group">
                        <label className="form-label">Bekräfta lösenord</label>
                        <input
                            type="password"
                            required
                            className="form-input"
                            value={formData.confirmPassword}
                            onChange={(e) => setFormData({ ...formData, confirmPassword: e.target.value })}
                        />
                    </div>

                    <div className="profile-form-row">
                        <div className="form-group">
                            <label className="form-label">Personnummer</label>
                            <input
                                type="text"
                                required
                                className="form-input"
                                placeholder="ÅÅÅÅMMDD-XXXX"
                                maxLength={13}
                                value={formData.personnummer}
                                onChange={(e) => {
                                    let val = e.target.value.replace(/\D/g, '');
                                    if (val.length > 8) {
                                        val = val.slice(0, 8) + '-' + val.slice(8, 12);
                                    }
                                    setFormData({ ...formData, personnummer: val });
                                }}
                            />
                        </div>
                        <div className="form-group">
                            <label className="form-label">Mobilnummer</label>
                            <input
                                type="text"
                                required
                                className="form-input"
                                placeholder="070-123 45 67"
                                value={formData.mobile}
                                onChange={(e) => setFormData({ ...formData, mobile: e.target.value })}
                            />
                        </div>
                    </div>

                    <div className="form-group">
                        <label className="form-label">Adress (Gata & Nummer)</label>
                        <input
                            type="text"
                            required
                            className="form-input"
                            placeholder="Ex: Kungsgatan 1"
                            value={formData.address}
                            onChange={(e) => setFormData({ ...formData, address: e.target.value })}
                        />
                    </div>

                    <div className="profile-form-row">
                        <div className="form-group">
                            <label className="form-label">Postnummer</label>
                            <input
                                type="text"
                                required
                                className="form-input"
                                placeholder="12345"
                                maxLength={5}
                                value={formData.zip_code}
                                onChange={(e) => setFormData({ ...formData, zip_code: e.target.value.replace(/\D/g, '') })}
                            />
                        </div>
                        <div className="form-group">
                            <label className="form-label">Ort</label>
                            <input
                                type="text"
                                required
                                className="form-input"
                                placeholder="Ex. Solna"
                                value={formData.city}
                                onChange={(e) => setFormData({ ...formData, city: e.target.value })}
                            />
                        </div>
                    </div>

                    <div className="form-group">
                        <label className="form-label">Land</label>
                        <select
                            className="form-input form-select-raw"
                            value={formData.country}
                            onChange={(e) => setFormData({ ...formData, country: e.target.value })}
                        >
                            <option value="Sverige">Sverige</option>
                        </select>
                    </div>

                    <div className="form-checkbox-group" onClick={() => setFormData({ ...formData, newsletter: !formData.newsletter })}>
                        <input
                            type="checkbox"
                            className="form-checkbox"
                            checked={formData.newsletter}
                            onChange={() => { }} // Handled by group click
                        />
                        <span>Jag vill få nyheter och uppdateringar</span>
                    </div>

                    <div className="form-checkbox-group">
                        <input
                            type="checkbox"
                            className="form-checkbox"
                            checked={formData.terms}
                            onChange={(e) => setFormData({ ...formData, terms: e.target.checked })}
                        />
                        <span>
                            Jag godkänner{' '}
                            <button
                                type="button"
                                className="auth-link btn-link-raw"
                                onClick={() => setShowTermsModal(true)}
                            >
                                användarvillkoren
                            </button>
                        </span>
                    </div>

                    {error && (
                        <div className="auth-error">
                            {error}
                        </div>
                    )}

                    <div className="auth-button-container mt-8">
                        <button
                            type="submit"
                            disabled={loading}
                            className="auth-button"
                        >
                            {loading ? 'Skapar konto...' : 'Skapa konto'}
                        </button>

                        <button
                            type="button"
                            onClick={handleGoogleLogin}
                            className="auth-button google"
                        >
                            <FcGoogle size={20} />
                            Fortsätt med Google
                        </button>

                        <div className="auth-divider">ELLER</div>

                        <Link href="/login" className="auth-button secondary">
                            Logga in
                        </Link>
                    </div>
                </form>
            </div>

            {showTermsModal && (
                <div className="modal-overlay" onClick={() => setShowTermsModal(false)}>
                    <div className="modal-content" onClick={(e) => e.stopPropagation()}>
                        <button className="modal-close" onClick={() => setShowTermsModal(false)}>&times;</button>
                        <h3 className="modal-title">Användarvillkor</h3>
                        <div className="modal-body">
                            <p>Välkommen till Nordic Storium. Genom att använda vår tjänst godkänner du följande villkor:</p>

                            <h4>1. Allmänt</h4>
                            <p>Nordic Storium tillhandahåller premium skandinaviska möbler. Vi förbehåller oss rätten att ändra villkoren när som helst.</p>

                            <h4>2. Integritetspolicy</h4>
                            <p>Vi hanterar dina personuppgifter med största försiktighet i enlighet med GDPR. Vi säljer aldrig dina uppgifter till tredje part.</p>

                            <h4>3. Beställningar</h4>
                            <p>Alla beställningar är bindande. Vi förbehåller oss rätten att annullera ordrar vid felaktig lagerstatus eller prisinformation.</p>

                            <h4>4. Leverans</h4>
                            <p>Vi strävar efter att leverera dina varor så snabbt som möjligt, normalt inom 3-5 arbetsdagar i Sverige.</p>

                            <button
                                className="auth-button"
                                onClick={() => {
                                    setFormData({ ...formData, terms: true });
                                    setShowTermsModal(false);
                                }}
                            >
                                Jag förstår och godkänner
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
