// ================================================================
// frontend/src/components/domain/dashboard/PriorityScoreExplainerModal.tsx
// ================================================================
/**
 * Priority Score Explainer Modal
 *
 * Educational modal explaining the 0-100 priority scoring algorithm.
 * Builds trust by showing transparency into AI decision-making.
 *
 * Shows:
 * - Overall priority score breakdown
 * - 4 weighted components (Business Impact 40%, Urgency 30%, Agency 20%, Confidence 10%)
 * - Example calculations
 * - Visual progress bars for each component
 */

import React from 'react';
import { X, TrendingUp, DollarSign, Clock, Target, Brain, Info } from 'lucide-react';
import { Button } from '../../ui/Button';
import { Badge } from '../../ui/Badge';
import { useTranslation } from 'react-i18next';

export interface PriorityScoreExplainerModalProps {
  isOpen: boolean;
  onClose: () => void;
  exampleScore?: number;
  exampleBreakdown?: {
    businessImpact: number;
    urgency: number;
    agency: number;
    confidence: number;
  };
}

interface ScoreComponent {
  name: string;
  icon: typeof DollarSign;
  weight: number;
  description: string;
  examples: string[];
  color: string;
}

export function PriorityScoreExplainerModal({
  isOpen,
  onClose,
  exampleScore,
  exampleBreakdown,
}: PriorityScoreExplainerModalProps) {
  const { t } = useTranslation('alerts');

  if (!isOpen) return null;

  const components: ScoreComponent[] = [
    {
      name: t('priority_explainer.business_impact.name', 'Business Impact'),
      icon: DollarSign,
      weight: 40,
      description: t(
        'priority_explainer.business_impact.description',
        'Financial consequences, affected orders, customer satisfaction'
      ),
      examples: [
        t('priority_explainer.business_impact.example1', '€500 in potential revenue at risk'),
        t('priority_explainer.business_impact.example2', '10 customer orders affected'),
        t('priority_explainer.business_impact.example3', 'High customer satisfaction impact'),
      ],
      color: 'var(--color-error-500)',
    },
    {
      name: t('priority_explainer.urgency.name', 'Urgency'),
      icon: Clock,
      weight: 30,
      description: t(
        'priority_explainer.urgency.description',
        'Time sensitivity, deadlines, escalation potential'
      ),
      examples: [
        t('priority_explainer.urgency.example1', 'Deadline in 2 hours'),
        t('priority_explainer.urgency.example2', 'Stockout imminent (4 hours)'),
        t('priority_explainer.urgency.example3', 'Production window closing soon'),
      ],
      color: 'var(--color-warning-500)',
    },
    {
      name: t('priority_explainer.agency.name', 'User Agency'),
      icon: Target,
      weight: 20,
      description: t(
        'priority_explainer.agency.description',
        'Can you take action? Do you have control over the outcome?'
      ),
      examples: [
        t('priority_explainer.agency.example1', 'Requires approval from you'),
        t('priority_explainer.agency.example2', 'One-click action available'),
        t('priority_explainer.agency.example3', 'Decision needed within your authority'),
      ],
      color: 'var(--color-primary-500)',
    },
    {
      name: t('priority_explainer.confidence.name', 'AI Confidence'),
      icon: Brain,
      weight: 10,
      description: t(
        'priority_explainer.confidence.description',
        "How certain is the AI about this alert's validity?"
      ),
      examples: [
        t('priority_explainer.confidence.example1', 'Based on historical patterns (95% match)'),
        t('priority_explainer.confidence.example2', 'Data quality: High'),
        t('priority_explainer.confidence.example3', 'Prediction accuracy validated'),
      ],
      color: 'var(--color-info-500)',
    },
  ];

  const calculateExampleScore = (breakdown?: typeof exampleBreakdown): number => {
    if (!breakdown) return 75; // Default example

    return (
      (breakdown.businessImpact * 0.4) +
      (breakdown.urgency * 0.3) +
      (breakdown.agency * 0.2) +
      (breakdown.confidence * 0.1)
    );
  };

  const displayScore = exampleScore ?? calculateExampleScore(exampleBreakdown);

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm animate-in fade-in duration-200"
      onClick={onClose}
    >
      <div
        className="bg-[var(--bg-primary)] rounded-xl shadow-2xl max-w-3xl w-full max-h-[90vh] overflow-y-auto"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div
          className="sticky top-0 z-10 flex items-center justify-between p-6 border-b"
          style={{
            backgroundColor: 'var(--bg-primary)',
            borderColor: 'var(--border-primary)',
          }}
        >
          <div className="flex items-center gap-3">
            <div
              className="p-2 rounded-lg"
              style={{ backgroundColor: 'var(--color-primary-100)' }}
            >
              <TrendingUp className="w-6 h-6" style={{ color: 'var(--color-primary-600)' }} />
            </div>
            <div>
              <h2 className="text-2xl font-bold" style={{ color: 'var(--text-primary)' }}>
                {t('priority_explainer.title', 'Understanding Priority Scores')}
              </h2>
              <p className="text-sm mt-1" style={{ color: 'var(--text-secondary)' }}>
                {t('priority_explainer.subtitle', 'How AI calculates what needs your attention first')}
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 rounded-lg hover:bg-[var(--bg-secondary)] transition-colors"
            aria-label="Close"
          >
            <X className="w-5 h-5" style={{ color: 'var(--text-secondary)' }} />
          </button>
        </div>

        {/* Content */}
        <div className="p-6 space-y-6">
          {/* Overview */}
          <div
            className="rounded-lg p-5 border"
            style={{
              backgroundColor: 'var(--bg-secondary)',
              borderColor: 'var(--border-primary)',
            }}
          >
            <div className="flex items-start gap-3">
              <Info className="w-5 h-5 mt-0.5 flex-shrink-0" style={{ color: 'var(--color-info)' }} />
              <div>
                <h3 className="font-semibold mb-2" style={{ color: 'var(--text-primary)' }}>
                  {t('priority_explainer.overview.title', 'The Priority Score (0-100)')}
                </h3>
                <p className="text-sm" style={{ color: 'var(--text-secondary)' }}>
                  {t(
                    'priority_explainer.overview.description',
                    'Every alert receives a priority score from 0-100 based on four weighted components. This helps you focus on what truly matters for your bakery.'
                  )}
                </p>
              </div>
            </div>
          </div>

          {/* Example Score */}
          {exampleScore !== undefined && (
            <div
              className="rounded-lg p-5 border-2"
              style={{
                backgroundColor: 'var(--color-primary-50)',
                borderColor: 'var(--color-primary-300)',
              }}
            >
              <div className="text-center">
                <div className="text-sm font-medium mb-2" style={{ color: 'var(--text-secondary)' }}>
                  {t('priority_explainer.example_alert', 'Example Alert Priority')}
                </div>
                <div className="flex items-center justify-center gap-3">
                  <div className="text-5xl font-bold" style={{ color: 'var(--color-primary-600)' }}>
                    {displayScore.toFixed(0)}
                  </div>
                  <Badge variant="primary" size="lg">
                    {displayScore >= 90
                      ? t('priority_explainer.level.critical', 'CRITICAL')
                      : displayScore >= 70
                      ? t('priority_explainer.level.important', 'IMPORTANT')
                      : displayScore >= 50
                      ? t('priority_explainer.level.standard', 'STANDARD')
                      : t('priority_explainer.level.info', 'INFO')}
                  </Badge>
                </div>
              </div>
            </div>
          )}

          {/* Components Breakdown */}
          <div>
            <h3 className="text-lg font-bold mb-4" style={{ color: 'var(--text-primary)' }}>
              {t('priority_explainer.components_title', 'Score Components')}
            </h3>
            <div className="space-y-4">
              {components.map((component) => {
                const Icon = component.icon;
                const componentValue = exampleBreakdown
                  ? exampleBreakdown[
                      component.name.toLowerCase().replace(/\s+/g, '') as keyof typeof exampleBreakdown
                    ] || 75
                  : 75;

                return (
                  <div
                    key={component.name}
                    className="rounded-lg p-4 border"
                    style={{
                      backgroundColor: 'var(--bg-secondary)',
                      borderColor: 'var(--border-primary)',
                    }}
                  >
                    {/* Component Header */}
                    <div className="flex items-center justify-between mb-3">
                      <div className="flex items-center gap-3">
                        <div
                          className="p-2 rounded-lg"
                          style={{ backgroundColor: component.color + '20' }}
                        >
                          <Icon className="w-5 h-5" style={{ color: component.color }} />
                        </div>
                        <div>
                          <h4 className="font-semibold" style={{ color: 'var(--text-primary)' }}>
                            {component.name}
                          </h4>
                          <p className="text-xs" style={{ color: 'var(--text-tertiary)' }}>
                            {component.description}
                          </p>
                        </div>
                      </div>
                      <Badge variant="secondary" size="sm">
                        {component.weight}% {t('priority_explainer.weight', 'weight')}
                      </Badge>
                    </div>

                    {/* Progress Bar */}
                    <div className="mb-3">
                      <div
                        className="h-2 rounded-full overflow-hidden"
                        style={{ backgroundColor: 'var(--bg-tertiary)' }}
                      >
                        <div
                          className="h-full transition-all duration-500"
                          style={{
                            width: `${componentValue}%`,
                            backgroundColor: component.color,
                          }}
                        />
                      </div>
                      <div className="flex justify-between text-xs mt-1">
                        <span style={{ color: 'var(--text-tertiary)' }}>0</span>
                        <span className="font-semibold" style={{ color: component.color }}>
                          {componentValue}/100
                        </span>
                        <span style={{ color: 'var(--text-tertiary)' }}>100</span>
                      </div>
                    </div>

                    {/* Examples */}
                    <div className="space-y-1">
                      {component.examples.map((example, idx) => (
                        <div key={idx} className="flex items-start gap-2 text-xs">
                          <span style={{ color: component.color }}>•</span>
                          <span style={{ color: 'var(--text-secondary)' }}>{example}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Formula */}
          <div
            className="rounded-lg p-5 border"
            style={{
              backgroundColor: 'var(--bg-tertiary)',
              borderColor: 'var(--border-secondary)',
            }}
          >
            <h4 className="font-semibold mb-3" style={{ color: 'var(--text-primary)' }}>
              {t('priority_explainer.formula_title', 'The Formula')}
            </h4>
            <div
              className="font-mono text-sm p-3 rounded"
              style={{
                backgroundColor: 'var(--bg-primary)',
                color: 'var(--text-primary)',
              }}
            >
              Priority Score = (Business Impact × 0.40) + (Urgency × 0.30) + (User Agency × 0.20) + (AI Confidence ×
              0.10)
            </div>
          </div>
        </div>

        {/* Footer */}
        <div
          className="sticky bottom-0 flex items-center justify-between p-6 border-t"
          style={{
            backgroundColor: 'var(--bg-primary)',
            borderColor: 'var(--border-primary)',
          }}
        >
          <p className="text-sm" style={{ color: 'var(--text-secondary)' }}>
            {t(
              'priority_explainer.footer',
              'This scoring helps AI prioritize alerts, ensuring you see the most important issues first.'
            )}
          </p>
          <Button onClick={onClose} variant="primary">
            {t('priority_explainer.got_it', 'Got it!')}
          </Button>
        </div>
      </div>
    </div>
  );
}
