import Field from '@/components/Field';
import PasswordStrengthMeter from '@/components/PasswordStrengthMeter';
import Seo from '@/components/Seo';
import SocialAuthButtons from '@/components/SocialAuthButtons';
import { generateStrongPassword, isPasswordStrong } from '@/lib/password';
import { cn } from '@/lib/utils';
import { Link, useForm } from '@inertiajs/react';
import { motion } from 'framer-motion';
import {
    ArrowRight,
    CheckCircle2,
    Database,
    Lock,
    Mail,
    Moon,
    Shield,
    Sun,
    User,
    Wand2,
    X,
} from 'lucide-react';
import { FormEventHandler, useEffect, useState } from 'react';

const ease = [0.16, 1, 0.3, 1] as const;

const steps = [
    { num: 1, label: 'Account' },
    { num: 2, label: 'Organisation' },
    { num: 3, label: 'Subdomain' },
    { num: 4, label: 'Plan' },
    { num: 5, label: 'Payment' },
    { num: 6, label: 'Done' },
];

const benefits = [
    'Full Professional plan access, free for 30 days',
    'Dedicated database — your data isolated from day one',
    'IFRS-compliant chart of accounts, seeded automatically',
    'No credit card required to start',
];

const testimonial = {
    quote: 'We were processing payroll on spreadsheets and managing loan repayments through WhatsApp groups. Upepo Finance changed everything in under two weeks.',
    name: 'Ibrahim Mwangi',
    title: 'Operations Director',
    org: 'Maziwa Credit Union, Nairobi',
};

export default function GetStarted() {
    const [isDark, setIsDark] = useState(false);

    const { data, setData, post, processing, errors, reset } = useForm({
        name: '',
        email: '',
        password: '',
        password_confirmation: '',
    });

    useEffect(() => {
        const stored = localStorage.getItem('uf-theme');
        const dark = stored === 'dark';
        setIsDark(dark);
        document.documentElement.classList.toggle('dark', dark);
    }, []);

    const toggleDark = () => {
        const next = !isDark;
        setIsDark(next);
        document.documentElement.classList.toggle('dark', next);
        localStorage.setItem('uf-theme', next ? 'dark' : 'light');
    };

    const submit: FormEventHandler = (e) => {
        e.preventDefault();
        post(route('register'), {
            onFinish: () => reset('password', 'password_confirmation'),
        });
    };

    const generatePassword = () => {
        const generated = generateStrongPassword();
        setData((current) => ({
            ...current,
            password: generated,
            password_confirmation: generated,
        }));
    };

    const passwordsMismatch =
        data.password_confirmation.length > 0 &&
        data.password !== data.password_confirmation;

    const canSubmit = isPasswordStrong(data.password) && !passwordsMismatch;

    return (
        <div className="pf-page-bg text-foreground min-h-screen">
            <Seo
                title="Get Started"
                description="Start your free 30-day trial of Upepo Finance. No credit card required — set up your MFI in minutes."
            />

            {/* Floating: theme toggle + exit */}
            <div className="fixed top-4 right-4 z-50 flex items-center gap-2">
                <button
                    onClick={toggleDark}
                    aria-label="Toggle theme"
                    className="border-border/60 bg-card/80 text-muted-foreground hover:bg-secondary hover:text-foreground flex h-9 w-9 cursor-pointer items-center justify-center rounded-xl border backdrop-blur-sm transition-colors"
                >
                    {isDark ? (
                        <Sun className="h-4 w-4" />
                    ) : (
                        <Moon className="h-4 w-4" />
                    )}
                </button>
                <Link
                    href="/"
                    className="border-border/60 bg-card/80 text-muted-foreground hover:bg-secondary hover:text-foreground flex h-9 items-center gap-1.5 rounded-xl border px-3 text-sm backdrop-blur-sm transition-colors"
                >
                    <X className="h-3.5 w-3.5" />
                    <span className="hidden sm:inline">Exit</span>
                </Link>
            </div>

            <div className="flex min-h-dvh flex-col lg:flex-row">
                {/* ── Left panel — dark forest ──────────────────────────── */}
                <motion.div
                    initial={{ opacity: 0, x: -30 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ duration: 0.7, ease }}
                    className="bg-panel relative flex flex-col justify-between overflow-hidden px-8 py-12 lg:w-[45%] lg:px-12 lg:py-16"
                >
                    <div className="pointer-events-none absolute inset-0">
                        <div
                            className="pf-blob pf-blob-1 absolute -bottom-24 -left-24 h-80 w-80 opacity-20"
                            style={{
                                background:
                                    'radial-gradient(circle, hsl(var(--primary)), transparent 70%)',
                            }}
                        />
                        <div
                            className="pf-blob pf-blob-2 absolute -top-12 right-0 h-56 w-56 opacity-10"
                            style={{
                                background:
                                    'radial-gradient(circle, hsl(var(--accent)), transparent 70%)',
                            }}
                        />
                    </div>

                    <div className="relative z-10">
                        <Link
                            href="/"
                            className="mb-12 flex items-center gap-2.5"
                        >
                            <img
                                src="/images/logo.png"
                                alt="Upepo Finance"
                                className="h-8 w-8 object-contain"
                            />
                            <span className="text-panel-foreground text-sm font-bold tracking-wide">
                                Upepo Finance
                            </span>
                        </Link>

                        <span className="border-primary/30 bg-primary/15 text-primary mb-4 inline-flex items-center rounded-full border px-3 py-1 text-[10px] font-bold tracking-wider uppercase">
                            30-Day Free Trial
                        </span>

                        <h1 className="pf-display text-panel-foreground mb-4 text-3xl leading-tight font-bold lg:text-4xl">
                            Join 1,200+ institutions
                            <br />
                            across East Africa
                        </h1>

                        <p className="text-panel-foreground/65 mb-10 max-w-sm text-sm leading-relaxed">
                            Get full access to the Professional plan. No credit
                            card. No commitment. Cancel anytime.
                        </p>

                        <ul className="mb-12 space-y-3">
                            {benefits.map((b, i) => (
                                <motion.li
                                    key={b}
                                    initial={{ opacity: 0, x: -16 }}
                                    animate={{ opacity: 1, x: 0 }}
                                    transition={{
                                        duration: 0.5,
                                        delay: 0.3 + i * 0.07,
                                        ease,
                                    }}
                                    className="flex items-start gap-3"
                                >
                                    <CheckCircle2 className="text-primary mt-0.5 h-4 w-4 shrink-0" />
                                    <span className="text-panel-foreground/75 text-sm">
                                        {b}
                                    </span>
                                </motion.li>
                            ))}
                        </ul>
                    </div>

                    {/* Testimonial */}
                    <motion.div
                        initial={{ opacity: 0, y: 16 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ duration: 0.6, delay: 0.8, ease }}
                        className="relative z-10 rounded-2xl border border-white/10 bg-white/5 p-5"
                    >
                        <div className="mb-3 flex gap-0.5">
                            {[...Array(5)].map((_, i) => (
                                <svg
                                    key={i}
                                    className="fill-accent h-3 w-3"
                                    viewBox="0 0 20 20"
                                    aria-hidden="true"
                                >
                                    <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                                </svg>
                            ))}
                        </div>
                        <p className="text-panel-foreground/70 mb-4 text-sm leading-relaxed italic">
                            "{testimonial.quote}"
                        </p>
                        <div className="flex items-center gap-3">
                            <div className="bg-primary/20 text-primary flex h-9 w-9 items-center justify-center rounded-full text-sm font-bold">
                                {testimonial.name[0]}
                            </div>
                            <div>
                                <p className="text-panel-foreground text-sm font-semibold">
                                    {testimonial.name}
                                </p>
                                <p className="text-panel-foreground/50 text-xs">
                                    {testimonial.title} · {testimonial.org}
                                </p>
                            </div>
                        </div>
                    </motion.div>

                    {/* Trust badges */}
                    <div className="relative z-10 mt-8 flex flex-wrap items-center gap-4 border-t border-white/10 pt-6">
                        {[
                            { icon: Lock, label: 'AES-256 Encrypted' },
                            { icon: Database, label: 'Isolated Database' },
                            { icon: Shield, label: 'GDPR Ready' },
                        ].map((b) => (
                            <div
                                key={b.label}
                                className="text-panel-foreground/40 flex items-center gap-1.5 text-[10px] font-semibold tracking-wide uppercase"
                            >
                                <b.icon
                                    className="h-3 w-3"
                                    aria-hidden="true"
                                />
                                {b.label}
                            </div>
                        ))}
                    </div>
                </motion.div>

                {/* ── Right panel — form ────────────────────────────────── */}
                <motion.div
                    initial={{ opacity: 0, x: 30 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ duration: 0.7, delay: 0.1, ease }}
                    className="bg-background flex flex-1 flex-col justify-center px-8 py-16 lg:px-16"
                >
                    {/* Step progress */}
                    <div className="mb-10">
                        <div
                            className="flex items-center gap-1.5"
                            role="list"
                            aria-label="Registration steps"
                        >
                            {steps.map((step, i) => (
                                <div
                                    key={step.num}
                                    className="flex items-center gap-1.5"
                                    role="listitem"
                                >
                                    <div
                                        className={cn(
                                            'flex h-7 w-7 items-center justify-center rounded-full text-xs font-bold transition-all',
                                            step.num === 1
                                                ? 'bg-primary text-primary-foreground shadow-primary/20 shadow-md'
                                                : 'border-border bg-secondary/40 text-muted-foreground border',
                                        )}
                                        aria-current={
                                            step.num === 1 ? 'step' : undefined
                                        }
                                    >
                                        {step.num}
                                    </div>
                                    {step.num === 1 && (
                                        <span className="text-primary hidden text-xs font-semibold sm:block">
                                            {step.label}
                                        </span>
                                    )}
                                    {i < steps.length - 1 && (
                                        <div
                                            className="bg-border h-px w-4 flex-1"
                                            aria-hidden="true"
                                        />
                                    )}
                                </div>
                            ))}
                        </div>
                        <div className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1">
                            <p className="text-muted-foreground mt-3 text-xs font-semibold tracking-wider uppercase">
                                Step 1 of 6: Account Details
                            </p>
                            <p className="text-muted-foreground/60 mt-3 text-xs">
                                Next: organisation → subdomain → plan → payment
                            </p>
                        </div>
                    </div>

                    <div className="w-full max-w-md">
                        <h2 className="pf-display text-foreground mb-2 text-2xl font-bold">
                            Create your account
                        </h2>
                        <p className="text-muted-foreground mb-6 text-sm">
                            Start with your personal details. You'll set up your
                            organisation next.
                        </p>

                        <SocialAuthButtons mode="register" className="mb-5" />

                        <div
                            className="my-5 flex items-center gap-3"
                            aria-hidden="true"
                        >
                            <div className="bg-border h-px flex-1" />
                            <span className="text-muted-foreground text-xs">
                                or continue with email
                            </span>
                            <div className="bg-border h-px flex-1" />
                        </div>

                        <form onSubmit={submit} noValidate>
                            <div className="space-y-4">
                                <Field
                                    label="Full Name"
                                    id="name"
                                    name="name"
                                    placeholder="Fatuma Rashidi"
                                    icon={User}
                                    value={data.name}
                                    onChange={(e) =>
                                        setData('name', e.target.value)
                                    }
                                    error={errors.name}
                                    autoComplete="name"
                                    autoFocus
                                />
                                <Field
                                    label="Work Email"
                                    id="email"
                                    name="email"
                                    type="email"
                                    placeholder="fatuma@kilimosacco.co.tz"
                                    icon={Mail}
                                    value={data.email}
                                    onChange={(e) =>
                                        setData('email', e.target.value)
                                    }
                                    error={errors.email}
                                    autoComplete="email"
                                />
                                <div>
                                    <Field
                                        label="Password"
                                        id="password"
                                        name="password"
                                        type="password"
                                        placeholder="Create a strong password"
                                        icon={Lock}
                                        value={data.password}
                                        onChange={(e) =>
                                            setData('password', e.target.value)
                                        }
                                        error={errors.password}
                                        autoComplete="new-password"
                                        labelAction={
                                            <button
                                                type="button"
                                                onClick={generatePassword}
                                                className="text-primary inline-flex items-center gap-1 text-[11px] font-semibold hover:opacity-80"
                                            >
                                                <Wand2 className="h-3 w-3" />
                                                Generate
                                            </button>
                                        }
                                    />
                                    <PasswordStrengthMeter
                                        password={data.password}
                                        className="mt-2"
                                    />
                                </div>
                                <Field
                                    label="Confirm Password"
                                    id="password_confirmation"
                                    name="password_confirmation"
                                    type="password"
                                    placeholder="Repeat your password"
                                    icon={Lock}
                                    value={data.password_confirmation}
                                    onChange={(e) =>
                                        setData(
                                            'password_confirmation',
                                            e.target.value,
                                        )
                                    }
                                    error={
                                        errors.password_confirmation ||
                                        (passwordsMismatch
                                            ? 'Passwords do not match'
                                            : undefined)
                                    }
                                    autoComplete="new-password"
                                />
                            </div>

                            <p className="text-muted-foreground/70 my-5 text-[11px] leading-relaxed">
                                By continuing you agree to Upepo Finance's{' '}
                                <a
                                    href="#"
                                    className="text-primary underline underline-offset-2 hover:opacity-80"
                                >
                                    Terms of Service
                                </a>{' '}
                                and{' '}
                                <a
                                    href="#"
                                    className="text-primary underline underline-offset-2 hover:opacity-80"
                                >
                                    Privacy Policy
                                </a>
                                .
                            </p>

                            <button
                                type="submit"
                                disabled={processing || !canSubmit}
                                className="pf-btn w-full py-3.5 text-base disabled:cursor-not-allowed disabled:opacity-60"
                            >
                                {processing ? (
                                    'Creating account…'
                                ) : (
                                    <>
                                        <span>Continue</span>
                                        <ArrowRight
                                            className="h-4 w-4"
                                            aria-hidden="true"
                                        />
                                    </>
                                )}
                            </button>
                        </form>

                        <p className="text-muted-foreground mt-6 text-center text-sm">
                            Already have an account?{' '}
                            <Link
                                href="/login"
                                className="text-primary font-semibold underline underline-offset-2 transition-opacity hover:opacity-80"
                            >
                                Sign in
                            </Link>
                        </p>
                    </div>
                </motion.div>
            </div>
        </div>
    );
}
