// [REQ F1]  System uwierzytelniania – formularz rejestracji z weryfikacją e-mail
// [REQ T8]  Obsługa formularzy i walidacja – Formik + Zod, błędy inline przy każdym polu
import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useFormik } from 'formik';
import { z } from 'zod';
import { toFormikValidationSchema } from 'zod-formik-adapter';
import { Mail, CheckCircle2, Loader2 } from 'lucide-react';
import { registerUser, verifyUser } from '../api/users';
import styles from './RegisterPage.module.scss';

const schema = z
  .object({
    name: z.string().min(2, 'Name must be at least 2 characters.'),
    email: z.string().email('Enter a valid email address.'),
    password: z
      .string()
      .min(8, 'Password must be at least 8 characters.')
      .regex(/[A-Z]/, 'Must contain at least one uppercase letter.')
      .regex(/\d/, 'Must contain at least one digit.'),
    confirmPassword: z.string(),
  })
  // superRefine pozwala na dodanie niestandardowej walidacji, która porównuje dwa pola password i confirmPassword, jeśli nie są takie same to dodaje błąd do confirmPassword
  .superRefine((data, ctx) => {
    if (data.password !== data.confirmPassword) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: 'Passwords do not match.',
        path: ['confirmPassword'],
      });
    }
  });

const RegisterPage = () => {
  const navigate = useNavigate();
  const [stage, setStage] = useState('form'); // 'form' | 'sent' | 'done'
  const [pending, setPending] = useState(null);
  const [serverError, setServerError] = useState('');
  const [verifying, setVerifying] = useState(false);

  const formik = useFormik({
    initialValues: { name: '', email: '', password: '', confirmPassword: '' },
    validationSchema: toFormikValidationSchema(schema),
    onSubmit: async ({ name, email, password }) => {
      setServerError('');
      try {
        const result = await registerUser({ name, email, password });
        setPending(result);
        setStage('sent');
      } catch (err) {
        setServerError(err.message);
      }
    },
  });

  const handleVerify = async () => {
    setVerifying(true);
    try {
      await verifyUser(pending.token);
      setStage('done');
      setTimeout(() => navigate('/login', { state: { registered: true } }), 2500);
    } catch (err) {
      setServerError(err.message);
    } finally {
      setVerifying(false);
    }
  };
   // jeśli stage jest 'done' to wyświetlamy ekran sukcesu z informacją o weryfikacji konta i przekierowaniu do logowania
  if (stage === 'done') {
    return (
      <div className={styles['reg']}>
        <div className={styles['reg__card']}>
          <div className={styles['reg__success']}>
            <CheckCircle2 size={52} className={styles['reg__success-icon']} />
            <h2 className={styles['reg__success-title']}>Account verified!</h2>
            <p className={styles['reg__success-sub']}>Redirecting you to sign in...</p>
          </div>
        </div>
      </div>
    );
  }
  // jeśli stage jest 'sent' to wyświetlamy ekran z informacją o wysłaniu maila weryfikacyjnego oraz podglądem tego maila, 
  // z którego można kliknąć przycisk weryfikacji, który wywołuje funkcję handleVerify
  if (stage === 'sent') {
    return (
      <div className={styles['reg']}>
        <div className={[styles['reg__card'], styles['reg__card--wide']].join(' ')}>
          <div className={styles['reg__header']}>
            <Mail size={32} className={styles['reg__mail-icon']} />
            <h1 className={styles['reg__title']}>Check your inbox</h1>
            <p className={styles['reg__subtitle']}>
              We sent a verification link to <strong>{pending.user.email}</strong>
            </p>
          </div>

          <div className={styles['reg__email-preview']}>
            <div className={styles['reg__email-bar']}>
              <span className={styles['reg__email-dot']} />
              <span className={styles['reg__email-dot']} />
              <span className={styles['reg__email-dot']} />
              <span className={styles['reg__email-bar-label']}>Email preview</span>
            </div>
            <div className={styles['reg__email-meta']}>
              <div className={styles['reg__email-row']}>
                <span className={styles['reg__email-key']}>From</span>
                <span className={styles['reg__email-val']}>noreply@reservations.dev</span>
              </div>
              <div className={styles['reg__email-row']}>
                <span className={styles['reg__email-key']}>To</span>
                <span className={styles['reg__email-val']}>{pending.user.email}</span>
              </div>
              <div className={styles['reg__email-row']}>
                <span className={styles['reg__email-key']}>Subject</span>
                <span className={styles['reg__email-val']}>Verify your Reservation System account</span>
              </div>
            </div>
            <div className={styles['reg__email-body']}>
              <p className={styles['reg__email-greeting']}>Hello {pending.user.name},</p>
              <p className={styles['reg__email-text']}>
                Thanks for signing up! Click the button below to verify your email address
                and activate your account.
              </p>
              <button
                className={styles['reg__email-cta']}
                onClick={handleVerify}
                disabled={verifying}
              >
                {verifying
                  ? <><Loader2 size={16} className={styles['reg__spinner']} /> Verifying...</>
                  : 'Verify my account'
                }
              </button>
              <p className={styles['reg__email-footer']}>
                This link expires in 24 hours. If you did not create an account, ignore this email.
              </p>
            </div>
          </div>

          {serverError && (
            <p className={styles['reg__server-error']}>{serverError}</p>
          )}

          <p className={styles['reg__resend']}>
            Wrong email?{' '}
            <button
              type="button"
              className={styles['reg__link-btn']}
              onClick={() => { setStage('form'); setPending(null); }}
            >
              Go back
            </button>
          </p>
        </div>
      </div>
    );
  }
  // jeśli stage jest 'form' to wyświetlamy normalny formularz rejestracji, który jest obsługiwany przez hook useFormik
  // , a błędy walidacji są wyświetlane inline przy każdym polu, a błąd serwera jest wyświetlany na górze formularza
  return (
    <div className={styles['reg']}>
      <div className={styles['reg__card']}>
        <div className={styles['reg__header']}>
          <h1 className={styles['reg__title']}>Create account</h1>
          <p className={styles['reg__subtitle']}>Join the Reservation System</p>
        </div>

        <form className={styles['reg__form']} onSubmit={formik.handleSubmit} noValidate>
          {serverError && (
            <div className={styles['reg__alert']} role="alert">{serverError}</div>
          )}

          <div className={styles['reg__field']}>
            <label htmlFor="name" className={styles['reg__label']}>Full name</label>
            <input
              id="name"
              type="text"
              className={[
                styles['reg__input'],
                formik.touched.name && formik.errors.name ? styles['reg__input--error'] : '',
              ].join(' ')}
              placeholder="Jan Kowalski"
              autoComplete="name"
              {...formik.getFieldProps('name')}
            />
            {formik.touched.name && formik.errors.name && (
              <p className={styles['reg__field-error']}>{formik.errors.name}</p>
            )}
          </div>

          <div className={styles['reg__field']}>
            <label htmlFor="email" className={styles['reg__label']}>Email</label>
            <input
              id="email"
              type="email"
              className={[
                styles['reg__input'],
                formik.touched.email && formik.errors.email ? styles['reg__input--error'] : '',
              ].join(' ')}
              placeholder="you@example.com"
              autoComplete="email"
              {...formik.getFieldProps('email')}
            />
            {formik.touched.email && formik.errors.email && (
              <p className={styles['reg__field-error']}>{formik.errors.email}</p>
            )}
          </div>

          <div className={styles['reg__field']}>
            <label htmlFor="password" className={styles['reg__label']}>Password</label>
            <input
              id="password"
              type="password"
              className={[
                styles['reg__input'],
                formik.touched.password && formik.errors.password ? styles['reg__input--error'] : '',
              ].join(' ')}
              placeholder="min. 8 characters"
              autoComplete="new-password"
              {...formik.getFieldProps('password')}
            />
            {formik.touched.password && formik.errors.password && (
              <p className={styles['reg__field-error']}>{formik.errors.password}</p>
            )}
          </div>

          <div className={styles['reg__field']}>
            <label htmlFor="confirmPassword" className={styles['reg__label']}>
              Confirm password
            </label>
            <input
              id="confirmPassword"
              type="password"
              className={[
                styles['reg__input'],
                formik.touched.confirmPassword && formik.errors.confirmPassword
                  ? styles['reg__input--error']
                  : '',
              ].join(' ')}
              placeholder="repeat password"
              autoComplete="new-password"
              {...formik.getFieldProps('confirmPassword')}
            />
            {formik.touched.confirmPassword && formik.errors.confirmPassword && (
              <p className={styles['reg__field-error']}>{formik.errors.confirmPassword}</p>
            )}
          </div>

          <button
            type="submit"
            className={styles['reg__submit']}
            disabled={formik.isSubmitting}
          >
            {formik.isSubmitting
              ? <><Loader2 size={16} className={styles['reg__spinner']} /> Creating account...</>
              : 'Create account'
            }
          </button>
        </form>

        <p className={styles['reg__signin-link']}>
          Already have an account?{' '}
          <Link to="/login" className={styles['reg__link']}>Sign in</Link>
        </p>
      </div>
    </div>
  );
};

export default RegisterPage;
