import * as React from 'react';
import { router } from '@inertiajs/react';
import { useAdminAuth } from '@/features/admin/auth/hooks/useAdminAuth';
import { ApiError } from '@/lib/ApiError';

const INPUT_CLASS =
    'h-10 w-full rounded-lg border border-(--color-border) bg-(--color-surface) px-4 text-sm text-(--color-ink) outline-none transition-colors placeholder:text-(--color-ink-faint) focus:border-(--color-accent) focus:ring-2 focus:ring-(--color-accent)/20';

/**
 * Admin OTP login. The first step sends a code to the registered mobile;
 * the second step verifies it and stores the resulting Sanctum token.
 */
export default function AdminLogin() {
    const { requestOtp, resendOtp, verifyOtp, user, loading } = useAdminAuth();
    const [mobile, setMobile] = React.useState('');
    const [otp, setOtp] = React.useState('');
    const [step, setStep] = React.useState<'mobile' | 'otp'>('mobile');
    const [submitting, setSubmitting] = React.useState(false);
    const [error, setError] = React.useState<string | null>(null);

    React.useEffect(() => {
        if (!loading && user) {
            router.visit('/admin/dashboard');
        }
    }, [loading, user]);

    async function handleSubmit(e: React.FormEvent) {
        e.preventDefault();
        setSubmitting(true);
        setError(null);

        try {
            if (step === 'mobile') {
                await requestOtp(mobile);
                setStep('otp');
                return;
            }

            await verifyOtp(mobile, otp);
            router.visit('/admin/dashboard');
        } catch (err) {
            setError(
                err instanceof ApiError
                    ? err.message
                    : 'Something went wrong. Please try again.',
            );
        } finally {
            setSubmitting(false);
        }
    }

    async function handleResend() {
        setSubmitting(true);
        setError(null);
        try {
            await resendOtp(mobile);
        } catch (err) {
            setError(
                err instanceof ApiError
                    ? err.message
                    : 'Something went wrong. Please try again.',
            );
        } finally {
            setSubmitting(false);
        }
    }

    return (
        <div className="flex min-h-screen items-center justify-center bg-(--color-bg) px-4 text-(--color-ink)">
            <div className="w-full max-w-sm">
                <div className="mb-6 text-center">
                    <h1 className="text-2xl font-semibold text-(--color-accent)">
                        Chowman Admin
                    </h1>
                    <p className="mt-1 text-sm text-(--color-ink-muted)">
                        Quiz & Win administration
                    </p>
                </div>

                <div className="rounded-xl border border-(--color-border) bg-(--color-surface) shadow-(--shadow-md)">
                    <div className="p-6">
                        <form onSubmit={handleSubmit} className="space-y-4">
                            {error && (
                                <div
                                    role="alert"
                                    className="rounded-lg border border-(--color-danger)/30 bg-(--color-danger-light) px-4 py-3 text-sm font-medium text-(--color-danger)"
                                >
                                    {error}
                                </div>
                            )}

                            {step === 'mobile' ? (
                                <div className="space-y-2">
                                    <label
                                        htmlFor="mobile"
                                        className="text-sm font-medium text-(--color-ink)"
                                    >
                                        Registered mobile number
                                        <span className="ml-0.5 text-(--color-danger)">
                                            *
                                        </span>
                                    </label>
                                    <input
                                        id="mobile"
                                        type="tel"
                                        inputMode="numeric"
                                        autoComplete="tel"
                                        required
                                        maxLength={10}
                                        pattern="[6-9][0-9]{9}"
                                        value={mobile}
                                        onChange={(e) =>
                                            setMobile(
                                                e.target.value.replace(
                                                    /\D/g,
                                                    '',
                                                ),
                                            )
                                        }
                                        className={INPUT_CLASS}
                                    />
                                </div>
                            ) : (
                                <>
                                    <p className="text-sm text-(--color-ink-muted)">
                                        Enter the 6-digit code sent to {mobile}.
                                    </p>
                                    <div className="space-y-2">
                                        <label
                                            htmlFor="otp"
                                            className="text-sm font-medium text-(--color-ink)"
                                        >
                                            One-time password
                                            <span className="ml-0.5 text-(--color-danger)">
                                                *
                                            </span>
                                        </label>
                                        <input
                                            id="otp"
                                            type="text"
                                            inputMode="numeric"
                                            autoComplete="one-time-code"
                                            required
                                            maxLength={6}
                                            pattern="[0-9]{6}"
                                            value={otp}
                                            onChange={(e) =>
                                                setOtp(
                                                    e.target.value.replace(
                                                        /\D/g,
                                                        '',
                                                    ),
                                                )
                                            }
                                            className={`${INPUT_CLASS} tracking-[0.35em]`}
                                        />
                                    </div>
                                </>
                            )}

                            <button
                                type="submit"
                                disabled={submitting}
                                className="h-9 w-full rounded-md bg-(--color-accent) font-medium text-white shadow-(--shadow-sm) transition-all duration-200 hover:bg-(--color-accent-hover) hover:shadow-(--shadow-md) focus-visible:ring-2 focus-visible:ring-(--color-accent) focus-visible:ring-offset-2 focus-visible:ring-offset-(--color-surface) focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
                            >
                                {submitting
                                    ? step === 'mobile'
                                        ? 'Sending code...'
                                        : 'Verifying...'
                                    : step === 'mobile'
                                      ? 'Send OTP'
                                      : 'Verify OTP'}
                            </button>

                            {step === 'otp' && (
                                <div className="flex justify-between text-sm">
                                    <button
                                        type="button"
                                        className="text-(--color-ink-muted) underline hover:text-(--color-ink)"
                                        onClick={() => {
                                            setStep('mobile');
                                            setOtp('');
                                            setError(null);
                                        }}
                                    >
                                        Change number
                                    </button>
                                    <button
                                        type="button"
                                        className="text-(--color-accent) underline hover:text-(--color-accent-hover) disabled:cursor-not-allowed disabled:opacity-50"
                                        disabled={submitting}
                                        onClick={handleResend}
                                    >
                                        Resend OTP
                                    </button>
                                </div>
                            )}
                        </form>
                    </div>
                </div>
            </div>
        </div>
    );
}
