/**
 * QuotaOverageModal Component
 *
 * Modal that appears on login/masquerade when the tenant has exceeded quotas.
 * Shows warning about grace period and what will happen when it expires.
 * Uses sessionStorage to only show once per session.
 */

import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import {
  AlertTriangle,
  X,
  Clock,
  Archive,
  ChevronRight,
  Users,
  Layers,
  Briefcase,
  Mail,
  Zap,
} from 'lucide-react';
import { QuotaOverage } from '../api/auth';

interface QuotaOverageModalProps {
  overages: QuotaOverage[];
  onDismiss: () => void;
}

const QUOTA_ICONS: Record<string, React.ReactNode> = {
  'MAX_ADDITIONAL_USERS': <Users className="w-5 h-5" />,
  'MAX_RESOURCES': <Layers className="w-5 h-5" />,
  'MAX_SERVICES': <Briefcase className="w-5 h-5" />,
  'MAX_EMAIL_TEMPLATES': <Mail className="w-5 h-5" />,
  'MAX_AUTOMATED_TASKS': <Zap className="w-5 h-5" />,
};

const SESSION_STORAGE_KEY = 'quota_overage_modal_dismissed';

const QuotaOverageModal: React.FC<QuotaOverageModalProps> = ({ overages, onDismiss }) => {
  const { t } = useTranslation();
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    // Check if already dismissed this session
    const dismissed = sessionStorage.getItem(SESSION_STORAGE_KEY);
    if (!dismissed && overages && overages.length > 0) {
      setIsVisible(true);
    }
  }, [overages]);

  const handleDismiss = () => {
    sessionStorage.setItem(SESSION_STORAGE_KEY, 'true');
    setIsVisible(false);
    onDismiss();
  };

  if (!isVisible || !overages || overages.length === 0) {
    return null;
  }

  // Find the most urgent overage (least days remaining)
  const mostUrgent = overages.reduce((prev, curr) =>
    curr.days_remaining < prev.days_remaining ? curr : prev
  );

  const isCritical = mostUrgent.days_remaining <= 1;
  const isUrgent = mostUrgent.days_remaining <= 7;

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString(undefined, {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
  };

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm">
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl max-w-lg w-full overflow-hidden">
        {/* Header */}
        <div className={`px-6 py-4 ${
          isCritical
            ? 'bg-red-600'
            : isUrgent
              ? 'bg-amber-500'
              : 'bg-amber-100 dark:bg-amber-900/30'
        }`}>
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className={`p-2 rounded-full ${
                isCritical || isUrgent
                  ? 'bg-white/20'
                  : 'bg-amber-200 dark:bg-amber-800'
              }`}>
                <AlertTriangle className={`w-6 h-6 ${
                  isCritical || isUrgent
                    ? 'text-white'
                    : 'text-amber-700 dark:text-amber-300'
                }`} />
              </div>
              <div>
                <h2 className={`text-lg font-bold ${
                  isCritical || isUrgent
                    ? 'text-white'
                    : 'text-amber-900 dark:text-amber-100'
                }`}>
                  {isCritical
                    ? t('quota.modal.titleCritical', 'Action Required Immediately!')
                    : isUrgent
                      ? t('quota.modal.titleUrgent', 'Action Required Soon')
                      : t('quota.modal.title', 'Quota Exceeded')
                  }
                </h2>
                <p className={`text-sm ${
                  isCritical || isUrgent
                    ? 'text-white/90'
                    : 'text-amber-700 dark:text-amber-200'
                }`}>
                  {mostUrgent.days_remaining <= 0
                    ? t('quota.modal.subtitleExpired', 'Grace period has expired')
                    : mostUrgent.days_remaining === 1
                      ? t('quota.modal.subtitleOneDay', '1 day remaining')
                      : t('quota.modal.subtitle', '{{days}} days remaining', { days: mostUrgent.days_remaining })
                  }
                </p>
              </div>
            </div>
            <button
              onClick={handleDismiss}
              className={`p-2 rounded-lg transition-colors ${
                isCritical || isUrgent
                  ? 'hover:bg-white/20 text-white'
                  : 'hover:bg-amber-200 dark:hover:bg-amber-800 text-amber-700 dark:text-amber-300'
              }`}
              aria-label={t('common.close', 'Close')}
            >
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* Body */}
        <div className="px-6 py-5 space-y-5">
          {/* Main message */}
          <div className="flex items-start gap-3 p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
            <Clock className="w-5 h-5 text-gray-500 dark:text-gray-400 mt-0.5 flex-shrink-0" />
            <div className="text-sm text-gray-700 dark:text-gray-300">
              <p className="font-medium mb-1">
                {t('quota.modal.gracePeriodEnds', 'Grace period ends on {{date}}', {
                  date: formatDate(mostUrgent.grace_period_ends_at)
                })}
              </p>
              <p>
                {t('quota.modal.explanation',
                  'Your account has exceeded its plan limits. Please remove or archive excess items before the grace period ends, or they will be automatically archived.'
                )}
              </p>
            </div>
          </div>

          {/* Overage list */}
          <div className="space-y-3">
            <h3 className="text-sm font-semibold text-gray-900 dark:text-white">
              {t('quota.modal.overagesTitle', 'Items Over Quota')}
            </h3>
            <div className="space-y-2">
              {overages.map((overage) => (
                <div
                  key={overage.id}
                  className={`flex items-center justify-between p-3 rounded-lg border ${
                    overage.days_remaining <= 1
                      ? 'border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/20'
                      : overage.days_remaining <= 7
                        ? 'border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900/20'
                        : 'border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-700/30'
                  }`}
                >
                  <div className="flex items-center gap-3">
                    <div className={`p-2 rounded-lg ${
                      overage.days_remaining <= 1
                        ? 'bg-red-100 dark:bg-red-800/50 text-red-600 dark:text-red-400'
                        : overage.days_remaining <= 7
                          ? 'bg-amber-100 dark:bg-amber-800/50 text-amber-600 dark:text-amber-400'
                          : 'bg-gray-200 dark:bg-gray-600 text-gray-600 dark:text-gray-300'
                    }`}>
                      {QUOTA_ICONS[overage.quota_type] || <Layers className="w-5 h-5" />}
                    </div>
                    <div>
                      <p className="font-medium text-gray-900 dark:text-white">
                        {overage.display_name}
                      </p>
                      <p className="text-sm text-gray-500 dark:text-gray-400">
                        {t('quota.modal.usageInfo', '{{current}} used / {{limit}} allowed', {
                          current: overage.current_usage,
                          limit: overage.allowed_limit
                        })}
                      </p>
                    </div>
                  </div>
                  <div className="text-right">
                    <p className={`font-bold ${
                      overage.days_remaining <= 1
                        ? 'text-red-600 dark:text-red-400'
                        : overage.days_remaining <= 7
                          ? 'text-amber-600 dark:text-amber-400'
                          : 'text-gray-600 dark:text-gray-300'
                    }`}>
                      +{overage.overage_amount}
                    </p>
                    <p className="text-xs text-gray-500 dark:text-gray-400">
                      {t('quota.modal.overLimit', 'over limit')}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* What happens section */}
          <div className="flex items-start gap-3 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
            <Archive className="w-5 h-5 text-blue-600 dark:text-blue-400 mt-0.5 flex-shrink-0" />
            <div className="text-sm text-blue-800 dark:text-blue-200">
              <p className="font-medium mb-1">
                {t('quota.modal.whatHappens', 'What happens if I don\'t take action?')}
              </p>
              <p>
                {t('quota.modal.autoArchiveExplanation',
                  'After the grace period ends, the oldest items over your limit will be automatically archived. Archived items remain in your account but cannot be used until you upgrade or remove other items.'
                )}
              </p>
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="px-6 py-4 bg-gray-50 dark:bg-gray-700/50 border-t border-gray-200 dark:border-gray-700 flex items-center justify-between gap-3">
          <button
            onClick={handleDismiss}
            className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600 rounded-lg transition-colors"
          >
            {t('quota.modal.dismissButton', 'Remind Me Later')}
          </button>
          <Link
            to="/settings/quota"
            onClick={handleDismiss}
            className="inline-flex items-center gap-2 px-5 py-2.5 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 transition-colors"
          >
            {t('quota.modal.manageButton', 'Manage Quota')}
            <ChevronRight className="w-4 h-4" />
          </Link>
        </div>
      </div>
    </div>
  );
};

export default QuotaOverageModal;

/**
 * Clear the session storage dismissal flag
 * Call this when user logs out or masquerade changes
 */
export const resetQuotaOverageModalDismissal = () => {
  sessionStorage.removeItem(SESSION_STORAGE_KEY);
};
