'use client';

import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Formik, Form } from 'formik';
import * as Yup from 'yup';
import { Eye, EyeOff, Lock, Mail, AlertCircle } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { FormTextField, PageLoader } from '@/components/teltoinstall/_index';
import { useLogin } from '@/hooks/teltoinstall/_index';
import { useAuth } from '@/hooks/teltoinstall/auth/useAuth';

export default function LoginView() {
  const { t } = useTranslation();
  const { login, loading, error } = useLogin();
  const { isAuthenticated } = useAuth();
  const router = useRouter();
  const [showPassword, setShowPassword] = useState(false);

  // Déjà connecté : la page de login n'a pas de sens, on renvoie vers la liste.
  useEffect(() => {
    if (isAuthenticated) {
      router.replace('/installation-requests');
    }
  }, [isAuthenticated, router]);

  if (isAuthenticated) return <PageLoader />;

  const validationSchema = Yup.object({
    email: Yup.string().email(t('errors.invalidEmail')).required(t('errors.required')),
    password: Yup.string().required(t('errors.required')),
  });

  return (
    <div
      className="min-h-screen flex flex-col"
      style={{ background: 'linear-gradient(160deg, #0A1628 0%, #0D2B5E 50%, #0A1628 100%)' }}
    >
      {/* Fond décoratif */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div
          className="absolute top-0 left-1/2 -translate-x-1/2 w-[600px] h-[600px] rounded-full opacity-10"
          style={{ background: 'radial-gradient(circle, #067efb 0%, transparent 70%)' }}
        />
        <div
          className="absolute bottom-0 right-0 w-[400px] h-[400px] rounded-full opacity-5"
          style={{ background: 'radial-gradient(circle, #059669 0%, transparent 70%)' }}
        />
      </div>

      <div className="relative z-10 flex flex-col flex-1 items-center justify-center px-4 py-8">
        {/* Logo */}
        <div className="text-center mb-8 animate-slide-in">
          <div className="w-20 h-20 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-2xl bg-white p-4">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src="/installer/dadycar.svg" alt="Dadycar" className="w-full h-full object-contain" />
          </div>
          <h1 className="text-3xl font-bold text-white tracking-tight">{t('app.title')}</h1>
          <p className="text-blue-300 mt-1 text-sm">{t('app.subtitle')}</p>
        </div>

        {/* Carte de connexion */}
        <div className="w-full max-w-sm animate-slide-in">
          <div className="bg-white rounded-2xl shadow-2xl overflow-hidden">
            <div className="px-6 pt-6 pb-4 border-b border-border">
              <h2 className="text-xl font-bold text-foreground">{t('auth.loginTitle')}</h2>
              <p className="text-sm text-muted-foreground mt-0.5">{t('auth.loginSubtitle')}</p>
            </div>

            <Formik
              initialValues={{ email: '', password: '' }}
              validationSchema={validationSchema}
              onSubmit={(values) => login(values.email, values.password)}
            >
              <Form className="px-6 py-5 space-y-4">
                {error && (
                  <div className="flex items-center gap-2 p-3 bg-red-50 border border-red-200 rounded-lg animate-fade-in">
                    <AlertCircle className="w-4 h-4 text-red-500 shrink-0" />
                    <p className="text-sm text-red-600">{t(error)}</p>
                  </div>
                )}

                <FormTextField
                  name="email"
                  label={t('auth.email')}
                  type="email"
                  autoComplete="email"
                  autoFocus
                  placeholder="votre@email.fr"
                  startIcon={<Mail className="w-4 h-4" />}
                />

                <FormTextField
                  name="password"
                  label={t('auth.password')}
                  type={showPassword ? 'text' : 'password'}
                  autoComplete="current-password"
                  placeholder="••••••••"
                  startIcon={<Lock className="w-4 h-4" />}
                  endIcon={
                    <button
                      type="button"
                      onClick={() => setShowPassword((p) => !p)}
                      className="text-muted-foreground"
                    >
                      {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                    </button>
                  }
                />

                <button
                  type="submit"
                  disabled={loading}
                  className="btn-primary flex items-center justify-center gap-2 mt-2 disabled:opacity-70"
                >
                  {loading ? (
                    <>
                      <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                      {t('wizard.saving')}
                    </>
                  ) : (
                    <>
                      <Lock className="w-4 h-4" />
                      {t('auth.login')}
                    </>
                  )}
                </button>

                <p className="text-center text-xs text-muted-foreground">{t('auth.forgotPassword')}</p>
              </Form>
            </Formik>
          </div>
        </div>

        <p className="relative z-10 text-white/30 text-xs mt-8 text-center">
          Dadycar v1.0 — Interface Installateur
        </p>
      </div>
    </div>
  );
}
