import { useTranslation } from '@/hooks/use-translation';
import InputError from '@/components/input-error';
import TextLink from '@/components/text-link';
import { BannerDisplay } from '@/components/banner-display';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Spinner } from '@/components/ui/spinner';
import AuthLayout from '@/layouts/auth-layout';
import { register } from '@/routes';
import { store } from '@/routes/login';
import { request } from '@/routes/password';
import { Form, Head, usePage, router } from '@inertiajs/react';
import { type Banner } from '@/types';
import axios from 'axios';

interface LoginProps {
    status?: string;
    canResetPassword: boolean;
    canRegister: boolean;
}

export default function Login({
    status,
    canResetPassword,
    canRegister,
}: LoginProps) {
    const { t } = useTranslation();
    const { loginBanners, auth } = usePage().props as any;
    const banners = (loginBanners || []) as Banner[];
    const isAuthenticated = !!auth?.user;

    const handleBannerDismiss = async (bannerId: number) => {
        if (isAuthenticated) {
            try {
                await axios.post(`/api/member/banners/${bannerId}/dismissed`);
                router.reload({ only: ['loginBanners'] });
            } catch (error) {
                console.error('Failed to dismiss banner:', error);
            }
        }
        // For unauthenticated users, dismissal is only client-side
    };

    const handleBannerView = async (bannerId: number) => {
        if (isAuthenticated) {
            try {
                await axios.post(`/api/member/banners/${bannerId}/viewed`);
            } catch (error) {
                console.error('Failed to mark banner as viewed:', error);
            }
        }
    };

    const handleBannerClick = async (bannerId: number) => {
        if (isAuthenticated) {
            try {
                await axios.post(`/api/member/banners/${bannerId}/clicked`);
            } catch (error) {
                console.error('Failed to mark banner as clicked:', error);
            }
        }
    };

    return (
        <AuthLayout
            title={t('Log in to your account')}
            description={t('Enter your email and password below to log in')}
        >
            <Head title={t('Log in')} />

            {banners.length > 0 && (
                <div className="mb-6">
                    <BannerDisplay 
                        banners={banners}
                        onDismiss={handleBannerDismiss}
                        onView={handleBannerView}
                        onClick={handleBannerClick}
                    />
                </div>
            )}

            <Form
                {...store.form()}
                resetOnSuccess={['password']}
                className="flex flex-col gap-6"
            >
                {({ processing, errors }) => (
                    <>
                        <div className="grid gap-6">
                            <div className="grid gap-2">
                                <Label htmlFor="email">{t('Email address')}</Label>
                                <Input
                                    id="email"
                                    type="email"
                                    name="email"
                                    required
                                    autoFocus
                                    tabIndex={1}
                                    autoComplete="email"
                                    placeholder="email@example.com"
                                />
                                <InputError message={errors.email} />
                            </div>

                            <div className="grid gap-2">
                                <div className="flex items-center">
                                    <Label htmlFor="password">{t('Password')}</Label>
                                    {canResetPassword && (
                                        <TextLink
                                            href={request()}
                                            className="ms-auto text-sm"
                                            tabIndex={5}
                                        >
                                            {t('Forgot password?')}
                                        </TextLink>
                                    )}
                                </div>
                                <Input
                                    id="password"
                                    type="password"
                                    name="password"
                                    required
                                    tabIndex={2}
                                    autoComplete="current-password"
                                    placeholder={t('Password')}
                                />
                                <InputError message={errors.password} />
                            </div>

                            <div className="flex items-center space-x-3">
                                <Checkbox
                                    id="remember"
                                    name="remember"
                                    tabIndex={3}
                                />
                                <Label htmlFor="remember">{t('Remember me')}</Label>
                            </div>

                            <Button
                                type="submit"
                                className="mt-4 w-full"
                                tabIndex={4}
                                disabled={processing}
                                data-test="login-button"
                            >
                                {processing && <Spinner />}
                                Log in
                            </Button>
                        </div>

                        {canRegister && (
                            <div className="text-center text-sm text-muted-foreground">
                                {t('Don\'t have an account?')}{' '}
                                <TextLink href={register()} tabIndex={5}>
                                    {t('Sign up')}
                                </TextLink>
                            </div>
                        )}
                    </>
                )}
            </Form>

            {status && (
                <div className="mb-4 text-center text-sm font-medium text-green-600">
                    {status}
                </div>
            )}
        </AuthLayout>
    );
}
