/**
 * ReadinessGateModal
 *
 * Shown when the user clicks a paid plan while their account isn't ready for
 * billing: profile incomplete (missing address / VAT ID) and/or email not
 * confirmed. Keeps the user on /dashboard/subscription so they don't lose the
 * plan-selection context.
 *
 * Reads readiness from AuthenticatedUserStore directly — pure client state,
 * no network at display time. Server-side 409 (PROFILE_INCOMPLETE /
 * EMAIL_NOT_VERIFIED) remains defense-in-depth for tampered clients.
 *
 * (c) 2026 TWWIM UG. All rights reserved. (www.twwim.com)
 */

import { AlertTriangle, MailCheck, Pencil, X, Loader2 } from 'lucide-react';
import { Link } from '@tanstack/react-router';
import { useAuthenticatedUser } from '@/features/auth/hooks/useAuthenticatedUser';
import { useProfile, useResendVerification } from '@/features/profile/hooks/useProfile';
import { useTranslation } from '@/i18n/TranslationProvider';

const FIELD_LABEL_KEYS: Record<string, string> = {
  'address.street': 'profileCompleteness.field.street',
  'address.zip': 'profileCompleteness.field.zip',
  'address.city': 'profileCompleteness.field.city',
  'address.country': 'profileCompleteness.field.country',
  'vatId': 'profileCompleteness.field.vatId',
  'legalForm': 'profileCompleteness.field.legalForm',
  'registerCourt': 'profileCompleteness.field.registerCourt',
  'registerNumber': 'profileCompleteness.field.registerNumber',
  'directorName': 'profileCompleteness.field.directorName',
};

interface ReadinessGateModalProps {
  onClose: () => void;
}

export function ReadinessGateModal({ onClose }: ReadinessGateModalProps) {
  const { t } = useTranslation();
  const authed = useAuthenticatedUser();
  const { data: profile } = useProfile();
  const resendMutation = useResendVerification();

  if (!authed) return null;
  const { account } = authed;
  const needsProfile = !account.isProfileComplete;
  const needsVerify = !account.emailVerified;
  // If somehow opened while ready, close silently — caller should not have
  // shown us, but don't trap the user in a dead modal either.
  if (!needsProfile && !needsVerify) {
    onClose();
    return null;
  }

  const editPath = profile?.isPersonal ? '/dashboard/profile' : '/dashboard/company';
  const missingFieldLabels = account.missingProfileFields
    .map((key) => FIELD_LABEL_KEYS[key])
    .filter(Boolean)
    .map((key) => t(key!));

  return (
    <>
      <div
        className="fixed inset-0 bg-black/50 z-40 animate-fade-in"
        onClick={onClose}
        aria-hidden="true"
      />
      <div className="fixed inset-0 z-50 flex items-center justify-center p-4 pointer-events-none">
        <div
          data-testid="readiness-gate-modal"
          className="bg-card rounded-2xl border border-border shadow-2xl w-full max-w-md pointer-events-auto animate-scale-in"
          onClick={(e) => e.stopPropagation()}
        >
          <div className="flex items-start justify-between p-6 border-b border-border">
            <div className="flex items-start gap-3">
              <AlertTriangle className="w-6 h-6 text-amber-600 flex-shrink-0 mt-0.5" />
              <div>
                <h2 className="text-lg font-semibold text-foreground">{t('readiness.title')}</h2>
                <p className="text-sm text-muted-foreground mt-1">{t('readiness.subtitle')}</p>
              </div>
            </div>
            <button
              onClick={onClose}
              className="p-1.5 hover:bg-muted rounded-lg transition-colors flex-shrink-0"
              aria-label={t('common.close')}
            >
              <X className="w-5 h-5 text-muted-foreground" />
            </button>
          </div>

          <ul className="p-6 space-y-4">
            {needsProfile && (
              <li className="flex items-start gap-3">
                <Pencil className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
                <div className="text-sm">
                  <p className="font-medium text-foreground">{t('readiness.missingProfile')}</p>
                  {missingFieldLabels.length > 0 && (
                    <p className="text-muted-foreground mt-0.5">
                      {t('readiness.missingProfileFields')}
                      <span className="font-medium"> {missingFieldLabels.join(', ')}</span>
                    </p>
                  )}
                </div>
              </li>
            )}
            {needsVerify && (
              <li className="flex items-start gap-3">
                <MailCheck className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
                <div className="text-sm flex-1 min-w-0">
                  <p className="font-medium text-foreground">{t('readiness.missingEmail')}</p>
                  <p className="text-muted-foreground mt-0.5">{t('readiness.missingEmailDescription')}</p>
                  <button
                    type="button"
                    onClick={() => resendMutation.mutate()}
                    disabled={resendMutation.isPending || resendMutation.isSuccess}
                    className="mt-2 inline-flex items-center gap-1 text-xs font-medium text-primary hover:text-primary/80 disabled:opacity-50 transition-colors"
                  >
                    {resendMutation.isPending && <Loader2 className="h-3 w-3 animate-spin" />}
                    {resendMutation.isSuccess
                      ? t('profile.verificationSent')
                      : resendMutation.isPending
                        ? t('profile.sending')
                        : t('profile.resend')}
                  </button>
                </div>
              </li>
            )}
          </ul>

          <div className="p-6 pt-0 flex items-center gap-3 justify-end">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 rounded-lg text-sm font-medium text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
            >
              {t('common.cancel')}
            </button>
            {needsProfile && (
              <Link
                to={editPath}
                onClick={onClose}
                className="bg-primary text-primary-foreground px-4 py-2 rounded-lg text-sm font-medium hover:bg-primary/90 transition-colors"
              >
                {t('readiness.editProfile')}
              </Link>
            )}
          </div>
        </div>
      </div>
    </>
  );
}
