import { Head, useForm } from '@inertiajs/react';
import { useEffect, useState } from 'react';
import {
    BarChart2,
    CheckCircle,
    ChevronLeft,
    ChevronRight,
    Globe,
    Loader2,
    MessageCircle,
    TrendingUp,
    Users,
    XCircle,
    Zap,
} from 'lucide-react';
import InputError from '@/components/input-error';
import PasswordInput from '@/components/password-input';
import TextLink from '@/components/text-link';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Spinner } from '@/components/ui/spinner';
import RegisterLayout from '@/layouts/register-layout';
import { login } from '@/routes';

const TOTAL_STEPS = 4;

const roles = [
    { value: 'siswa', label: 'Pelajar' },
    { value: 'mahasiswa', label: 'Mahasiswa' },
    { value: 'profesional', label: 'Profesional' },
    { value: 'pengusaha', label: 'Pengusaha / UMKM' },
    { value: 'pensiunan', label: 'Pensiunan' },
    { value: 'umum', label: 'Lainnya' },
];

const referralSources = [
    { value: 'instagram', label: 'Instagram' },
    { value: 'google', label: 'Google / Search' },
    { value: 'youtube', label: 'YouTube' },
    { value: 'teman', label: 'Dari Teman' },
    { value: 'event', label: 'Event / Seminar' },
    { value: 'lainnya', label: 'Lainnya' },
];

const categories = [
    { value: 'digital_marketing', label: 'Digital Marketing', Icon: Globe, color: '#118AB2' },
    { value: 'umkm_bisnis', label: 'UMKM & Bisnis', Icon: TrendingUp, color: '#FFB703' },
    { value: 'koperasi', label: 'Koperasi', Icon: Users, color: '#06D6A0' },
    { value: 'keuangan', label: 'Keuangan', Icon: BarChart2, color: '#E63946' },
    { value: 'public_speaking', label: 'Public Speaking', Icon: MessageCircle, color: '#E63946' },
    { value: 'teknologi', label: 'Teknologi', Icon: Zap, color: '#118AB2' },
];

const stepMeta = [
    { title: 'Buat Akun', desc: 'Isi informasi dasar untuk mulai belajar' },
    { title: 'Tentang Anda', desc: 'Kami ingin mengenal Anda lebih baik' },
    { title: 'Dari Mana Anda Tahu Kami?', desc: 'Bantu kami menjangkau lebih banyak orang' },
    { title: 'Minat Belajar', desc: 'Pilih bidang yang ingin Anda tekuni' },
];

type Props = {
    passwordRules: string;
    googleUser?: {
        name: string;
        email: string;
        google_id: string;
    };
};

export default function Register({ passwordRules, googleUser }: Props) {
    const minPasswordLength = parseInt(passwordRules.match(/minlength:\s*(\d+)/i)?.[1] ?? '8', 10);
    const [step, setStep] = useState(1);
    const [emailStatus, setEmailStatus] = useState<'idle' | 'checking' | 'available' | 'taken'>(
        googleUser ? 'available' : 'idle'
    );

    const { data, setData, post, processing, errors } = useForm({
        name: googleUser?.name || '',
        email: googleUser?.email || '',
        password: '',
        password_confirmation: '',
        phone: '',
        birth_date: '',
        gender: '',
        ui_theme: 'umum',
        referral_source: '',
        category_interest: '',
        google_id: googleUser?.google_id || '',
    });

    useEffect(() => {
        const email = data.email.trim();
        if (!email || !email.includes('@') || !email.includes('.')) {
            setEmailStatus('idle');
            return;
        }
        setEmailStatus('checking');
        const timer = setTimeout(async () => {
            try {
                const res = await fetch(`/register/check-email?email=${encodeURIComponent(email)}`);
                const json = await res.json();
                setEmailStatus(json.available ? 'available' : 'taken');
            } catch {
                setEmailStatus('idle');
            }
        }, 500);
        return () => clearTimeout(timer);
    }, [data.email]);

    const selectedCategories = data.category_interest.split(',').filter(Boolean);

    function toggleCategory(value: string) {
        const updated = selectedCategories.includes(value)
            ? selectedCategories.filter((c) => c !== value)
            : [...selectedCategories, value];
        setData('category_interest', updated.join(','));
    }

    function canProceed() {
        if (step === 1) {
            if (googleUser) {
                return data.name.trim().length > 0 && data.email.trim().length > 0;
            }
            return (
                data.name.trim().length > 0 &&
                data.email.trim().length > 0 &&
                data.password.length >= minPasswordLength &&
                data.password === data.password_confirmation &&
                emailStatus === 'available'
            );
        }
        if (step === 2) return data.gender !== '';
        if (step === 3) return data.referral_source !== '';
        return true;
    }

    function handleSubmit() {
        post('/register', {
            onError: (errs) => {
                if (errs.name || errs.email || errs.password || errs.password_confirmation) setStep(1);
                else if (errs.ui_theme || errs.gender || errs.phone || errs.birth_date) setStep(2);
            },
        });
    }

    const isDark = step > 1;
    const { title, desc } = stepMeta[step - 1];

    const pillIdle = isDark
        ? { borderColor: 'rgba(255,255,255,0.2)', color: 'rgba(255,255,255,0.75)' }
        : { borderColor: 'rgba(0,0,0,0.15)', color: '#444' };
    const pillActive = { backgroundColor: '#118AB2', borderColor: '#118AB2', color: '#fff' };

    /* ── Progress bar (shared, styled per theme) ── */
    const progress = (
        <div className="mb-6">
            <div className="mb-2 flex items-center justify-between text-xs" style={{ color: isDark ? 'rgba(255,255,255,0.45)' : '#555' }}>
                <span>Langkah {step} dari {TOTAL_STEPS}</span>
                <span style={{ color: '#118AB2' }}>{Math.round((step / TOTAL_STEPS) * 100)}%</span>
            </div>
            <div className="h-1 w-full overflow-hidden rounded-full" style={{ backgroundColor: isDark ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.08)' }}>
                <div
                    className="h-full rounded-full transition-all duration-500"
                    style={{ width: `${(step / TOTAL_STEPS) * 100}%`, backgroundColor: '#118AB2' }}
                />
            </div>
        </div>
    );

    /* ── Step heading ── */
    const heading = (
        <div className="mb-7">
            <h2 className="text-xl font-bold" style={{ color: isDark ? '#fff' : '#1A1A1A' }}>
                {title}
            </h2>
            <p className="mt-1 text-sm" style={{ color: isDark ? 'rgba(255,255,255,0.5)' : '#666' }}>
                {desc}
            </p>
        </div>
    );

    /* ── Navigation ── */
    const nav = (
        <div className="mt-8 flex gap-3">
            {step > 1 && (
                <button
                    type="button"
                    onClick={() => setStep(step - 1)}
                    disabled={processing}
                    className="flex h-11 items-center gap-1.5 rounded-full border px-5 text-sm font-medium transition-all"
                    style={{ borderColor: 'rgba(255,255,255,0.25)', color: 'rgba(255,255,255,0.75)' }}
                >
                    <ChevronLeft className="h-4 w-4" />
                    Kembali
                </button>
            )}
            {step < TOTAL_STEPS ? (
                <button
                    type="button"
                    disabled={!canProceed()}
                    onClick={() => setStep(step + 1)}
                    className="flex h-11 flex-1 items-center justify-center gap-1.5 rounded-full text-sm font-semibold text-white transition-all disabled:opacity-40"
                    style={{ backgroundColor: '#118AB2' }}
                >
                    Lanjut
                    <ChevronRight className="h-4 w-4" />
                </button>
            ) : (
                <button
                    type="button"
                    disabled={processing}
                    onClick={handleSubmit}
                    data-test="register-user-button"
                    className="flex h-11 flex-1 items-center justify-center gap-2 rounded-full text-sm font-semibold text-white transition-all disabled:opacity-40"
                    style={{ backgroundColor: '#118AB2' }}
                >
                    {processing && <Spinner />}
                    Buat Akun
                </button>
            )}
        </div>
    );

    /* ── Login link ── */
    const loginLink = (
        <p className="mt-5 text-center text-sm" style={{ color: isDark ? 'rgba(255,255,255,0.35)' : '#666' }}>
            Sudah punya akun?{' '}
            <TextLink href={login()} className="font-semibold" style={{ color: isDark ? 'rgba(255,255,255,0.7)' : undefined }}>
                Masuk
            </TextLink>
        </p>
    );

    return (
        <>
            <Head title="Daftar" />

            {/* ── STEP 1: inside white card ── */}
            {step === 1 && (
                <div
                    data-scheme="light"
                    className="animate-in fade-in duration-300 rounded-3xl bg-white p-8"
                    style={{ colorScheme: 'light', boxShadow: '0 32px 80px rgba(0,0,0,0.5)' }}
                >
                    {progress}
                    {heading}

                    {!googleUser && (
                        <>
                            <div className="flex flex-col gap-3 mb-4">
                                <Button
                                    variant="outline"
                                    type="button"
                                    className="w-full h-11 rounded-xl flex items-center justify-center gap-2 border border-gray-200 bg-white text-gray-700 hover:bg-gray-50 font-medium text-sm transition-all"
                                    onClick={() => window.location.href = '/auth/google'}
                                >
                                    <svg className="h-5 w-5" viewBox="0 0 24 24">
                                        <path
                                            fill="#EA4335"
                                            d="M12 5.04c1.62 0 3.08.56 4.22 1.65l3.15-3.15C17.45 1.76 14.96 1 12 1 7.37 1 3.39 3.65 1.39 7.56l3.8 2.94c.89-2.67 3.39-4.46 6.81-4.46z"
                                        />
                                        <path
                                            fill="#4285F4"
                                            d="M23.49 12.27c0-.81-.07-1.59-.2-2.35H12v4.46h6.46c-.28 1.48-1.12 2.73-2.38 3.58l3.7 2.87c2.16-1.99 3.41-4.92 3.41-8.56z"
                                        />
                                        <path
                                            fill="#FBBC05"
                                            d="M5.19 10.5c-.23-.69-.36-1.43-.36-2.2s.13-1.51.36-2.2L1.39 3.16C.5 4.93 0 6.9 0 9s.5 4.07 1.39 5.84l3.8-2.94-.01-.4z"
                                        />
                                        <path
                                            fill="#34A853"
                                            d="M12 23c3.24 0 5.97-1.08 7.96-2.92l-3.7-2.87c-1.03.69-2.35 1.1-3.9 1.1-3.42 0-5.92-2.28-6.81-5.38l-3.8 2.94C3.39 20.35 7.37 23 12 23z"
                                        />
                                    </svg>
                                    Daftar dengan Google
                                </Button>
                            </div>

                            <div className="relative my-4">
                                <div className="absolute inset-0 flex items-center">
                                    <div className="w-full border-t border-gray-200" />
                                </div>
                                <div className="relative flex justify-center text-xs uppercase">
                                    <span className="bg-white px-2 text-gray-400">atau daftar dengan email</span>
                                </div>
                            </div>
                        </>
                    )}

                    <div className="grid gap-4">
                        <div className="grid gap-1.5">
                            <Label>Nama Lengkap</Label>
                            <Input
                                type="text"
                                autoFocus
                                autoComplete="name"
                                value={data.name}
                                onChange={(e) => setData('name', e.target.value)}
                                placeholder="Nama lengkap Anda"
                                className="h-11 rounded-xl"
                            />
                            <InputError message={errors.name} />
                        </div>

                        <div className="grid gap-1.5">
                            <Label>Alamat Email</Label>
                            <div className="relative">
                                <Input
                                    type="email"
                                    autoComplete="email"
                                    value={data.email}
                                    onChange={(e) => setData('email', e.target.value)}
                                    placeholder="email@contoh.com"
                                    className="h-11 rounded-xl pr-10"
                                    disabled={!!googleUser}
                                    style={
                                        emailStatus === 'taken'
                                            ? { borderColor: '#E63946' }
                                            : emailStatus === 'available'
                                              ? { borderColor: '#06D6A0' }
                                              : {}
                                    }
                                />
                                {emailStatus === 'checking' && <Loader2 className="absolute top-3.5 right-3 h-4 w-4 animate-spin" style={{ color: '#999' }} />}
                                {emailStatus === 'available' && <CheckCircle className="absolute top-3.5 right-3 h-4 w-4" style={{ color: '#06D6A0' }} />}
                                {emailStatus === 'taken' && <XCircle className="absolute top-3.5 right-3 h-4 w-4" style={{ color: '#E63946' }} />}
                            </div>
                            {emailStatus === 'taken' && (
                                <p className="text-xs" style={{ color: '#E63946' }}>
                                    Email ini sudah terdaftar.{' '}
                                    <TextLink href={login()} className="font-semibold underline">Masuk sekarang</TextLink>{' '}
                                    atau gunakan email lain.
                                </p>
                            )}
                            <InputError message={errors.email} />
                        </div>

                        {!googleUser && (
                            <>
                                <div className="grid gap-1.5">
                                    <Label>Kata Sandi</Label>
                                    <PasswordInput
                                        autoComplete="new-password"
                                        value={data.password}
                                        onChange={(e) => setData('password', e.target.value)}
                                        placeholder="Minimal 8 karakter"
                                        passwordrules={passwordRules}
                                        className="h-11 rounded-xl"
                                    />
                                    <InputError message={errors.password} />
                                </div>

                                <div className="grid gap-1.5">
                                    <Label>Konfirmasi Kata Sandi</Label>
                                    <PasswordInput
                                        autoComplete="new-password"
                                        value={data.password_confirmation}
                                        onChange={(e) => setData('password_confirmation', e.target.value)}
                                        placeholder="Ulangi kata sandi"
                                        passwordrules={passwordRules}
                                        className="h-11 rounded-xl"
                                    />
                                    {data.password_confirmation.length > 0 && data.password !== data.password_confirmation && (
                                        <p className="text-xs" style={{ color: '#E63946' }}>Kata sandi tidak cocok</p>
                                    )}
                                    <InputError message={errors.password_confirmation} />
                                </div>
                            </>
                        )}
                    </div>

                    {/* step 1 nav uses light button style */}
                    <div className="mt-6">
                        <Button
                            type="button"
                            disabled={!canProceed()}
                            onClick={() => setStep(2)}
                            className="h-11 w-full rounded-xl font-semibold"
                            style={{ backgroundColor: '#118AB2' }}
                        >
                            Lanjut
                            <ChevronRight className="h-4 w-4" />
                        </Button>
                    </div>

                    <p className="mt-5 text-center text-sm" style={{ color: '#666' }}>
                        Sudah punya akun?{' '}
                        <TextLink href={login()} className="font-semibold">Masuk</TextLink>
                    </p>
                </div>
            )}

            {/* ── STEPS 2-4: no card, dark background ── */}
            {step > 1 && (
                <div key={step} className="animate-in fade-in duration-300">
                    {progress}
                    {heading}

                    {/* Step 2: Tentang Anda */}
                    {step === 2 && (
                        <div className="grid gap-10">
                            <div className="grid gap-3">
                                <p className="text-base font-semibold text-white">Saya adalah...</p>
                                <div className="flex flex-wrap gap-2">
                                    {roles.map(({ value, label }) => (
                                        <button
                                            key={value}
                                            type="button"
                                            onClick={() => setData('ui_theme', value)}
                                            className="rounded-full border px-4 py-2 text-sm font-medium transition-all duration-150"
                                            style={data.ui_theme === value ? pillActive : pillIdle}
                                        >
                                            {label}
                                        </button>
                                    ))}
                                </div>
                            </div>

                            <div className="grid gap-3">
                                <p className="text-base font-semibold text-white">Jenis kelamin saya</p>
                                <div className="flex flex-wrap gap-2">
                                    {[
                                        { value: 'male', label: 'Laki-laki' },
                                        { value: 'female', label: 'Perempuan' },
                                        { value: 'other', label: 'Tidak ingin disebutkan' },
                                    ].map((g) => (
                                        <button
                                            key={g.value}
                                            type="button"
                                            onClick={() => setData('gender', g.value)}
                                            className="rounded-full border px-4 py-2 text-sm font-medium transition-all duration-150"
                                            style={data.gender === g.value ? pillActive : pillIdle}
                                        >
                                            {g.label}
                                        </button>
                                    ))}
                                </div>
                                <InputError message={errors.gender} />
                            </div>

                            <div className="grid gap-3">
                                <div>
                                    <p className="text-base font-semibold text-white">
                                        Nomor HP & tanggal lahir{' '}
                                        <span className="text-sm font-normal" style={{ color: 'rgba(255,255,255,0.4)' }}>
                                            (opsional)
                                        </span>
                                    </p>
                                    <p className="mt-1 text-xs" style={{ color: 'rgba(255,255,255,0.4)' }}>
                                        Data Anda aman dan tidak akan dibagikan kepada siapapun.
                                    </p>
                                </div>
                                <div className="grid grid-cols-2 gap-3">
                                    <Input
                                        type="tel"
                                        autoComplete="tel"
                                        value={data.phone}
                                        onChange={(e) => setData('phone', e.target.value)}
                                        placeholder="08xxxxxxxxxx"
                                        className="h-10 rounded-xl border-0"
                                        style={{ backgroundColor: 'rgba(255,255,255,0.08)', color: 'white' }}
                                    />
                                    <Input
                                        type="date"
                                        value={data.birth_date}
                                        onChange={(e) => setData('birth_date', e.target.value)}
                                        className="h-10 rounded-xl border-0"
                                        style={{ backgroundColor: 'rgba(255,255,255,0.08)', color: 'white' }}
                                    />
                                </div>
                            </div>
                        </div>
                    )}

                    {/* Step 3: Referral */}
                    {step === 3 && (
                        <div className="grid gap-4">
                            <p className="text-sm" style={{ color: 'rgba(255,255,255,0.5)' }}>
                                Jawaban ini membantu kami menjangkau lebih banyak orang.
                            </p>
                            <div className="flex flex-wrap gap-2">
                                {referralSources.map(({ value, label }) => (
                                    <button
                                        key={value}
                                        type="button"
                                        onClick={() => setData('referral_source', value)}
                                        className="rounded-full border px-4 py-2 text-sm font-medium transition-all duration-150"
                                        style={data.referral_source === value ? pillActive : pillIdle}
                                    >
                                        {label}
                                    </button>
                                ))}
                            </div>
                        </div>
                    )}

                    {/* Step 4: Kategori */}
                    {step === 4 && (
                        <div className="grid gap-4">
                            <p className="text-sm" style={{ color: 'rgba(255,255,255,0.5)' }}>
                                Pilih satu atau lebih yang menarik minat Anda
                            </p>
                            <div className="flex flex-wrap gap-2">
                                {categories.map(({ value, label, Icon, color }) => {
                                    const isSelected = selectedCategories.includes(value);
                                    return (
                                        <button
                                            key={value}
                                            type="button"
                                            onClick={() => toggleCategory(value)}
                                            className="flex items-center gap-2 rounded-full border px-4 py-2 text-sm font-medium transition-all duration-150"
                                            style={
                                                isSelected
                                                    ? { backgroundColor: '#118AB2', borderColor: '#118AB2', color: '#fff' }
                                                    : { borderColor: 'rgba(255,255,255,0.2)', color: 'rgba(255,255,255,0.75)' }
                                            }
                                        >
                                            <Icon className="h-3.5 w-3.5 shrink-0" style={{ color: isSelected ? '#fff' : color }} />
                                            {label}
                                        </button>
                                    );
                                })}
                            </div>
                        </div>
                    )}

                    {nav}
                    {loginLink}
                </div>
            )}
        </>
    );
}

Register.layout = RegisterLayout;
