// ================================================================
// frontend/src/components/dashboard/CollapsibleSetupBanner.tsx
// ================================================================
/**
 * Collapsible Setup Banner - Recommended Configuration Reminder
 *
 * JTBD: "Remind me to complete optional setup without blocking my workflow"
 *
 * This banner appears at the top of the dashboard when:
 * - Critical setup is complete (can operate bakery)
 * - BUT recommended setup is incomplete (missing features)
 * - Progress: 50-99%
 *
 * Features:
 * - Collapsible (default: collapsed to minimize distraction)
 * - Dismissible (persists in localStorage for 7 days)
 * - Shows progress + remaining sections
 * - One-click navigation to incomplete sections
 */

import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { CheckCircle, ChevronDown, ChevronUp, X, ArrowRight } from 'lucide-react';

interface RemainingSection {
  id: string;
  title: string;
  icon: React.ElementType;
  path: string;
  count: number;
  recommended: number;
}

interface CollapsibleSetupBannerProps {
  remainingSections: RemainingSection[];
  progressPercentage: number;
  onDismiss?: () => void;
}

const DISMISS_KEY = 'setup_banner_dismissed';
const DISMISS_DURATION = 7 * 24 * 60 * 60 * 1000; // 7 days in milliseconds

export function CollapsibleSetupBanner({ remainingSections, progressPercentage, onDismiss }: CollapsibleSetupBannerProps) {
  const { t } = useTranslation(['dashboard']);
  const navigate = useNavigate();
  const [expanded, setExpanded] = useState(false);
  const [dismissed, setDismissed] = useState(false);

  // Check if banner was dismissed
  useEffect(() => {
    const dismissedUntil = localStorage.getItem(DISMISS_KEY);
    if (dismissedUntil) {
      const dismissedTime = parseInt(dismissedUntil, 10);
      if (Date.now() < dismissedTime) {
        setDismissed(true);
      } else {
        localStorage.removeItem(DISMISS_KEY);
      }
    }
  }, []);

  const handleDismiss = () => {
    const dismissUntil = Date.now() + DISMISS_DURATION;
    localStorage.setItem(DISMISS_KEY, dismissUntil.toString());
    setDismissed(true);
    if (onDismiss) {
      onDismiss();
    }
  };

  const handleSectionClick = (path: string) => {
    navigate(path);
  };

  if (dismissed || remainingSections.length === 0) {
    return null;
  }

  return (
    <div
      className="mb-6 rounded-xl border-2 shadow-md transition-all duration-300"
      style={{
        backgroundColor: 'var(--bg-primary)',
        borderColor: expanded ? 'var(--color-info-300)' : 'var(--border-secondary)',
      }}
    >
      {/* Compact Header (Always Visible) */}
      <div
        className="flex items-center gap-4 p-4 cursor-pointer hover:bg-[var(--bg-secondary)] transition-colors"
        onClick={() => setExpanded(!expanded)}
      >
        {/* Progress Circle */}
        <div className="relative w-12 h-12 flex-shrink-0">
          <svg className="w-full h-full transform -rotate-90">
            {/* Background circle */}
            <circle
              cx="24"
              cy="24"
              r="20"
              fill="none"
              stroke="var(--bg-tertiary)"
              strokeWidth="4"
            />
            {/* Progress circle */}
            <circle
              cx="24"
              cy="24"
              r="20"
              fill="none"
              stroke="var(--color-success)"
              strokeWidth="4"
              strokeDasharray={`${2 * Math.PI * 20}`}
              strokeDashoffset={`${2 * Math.PI * 20 * (1 - progressPercentage / 100)}`}
              strokeLinecap="round"
            />
          </svg>
          <div className="absolute inset-0 flex items-center justify-center">
            <span className="text-xs font-bold" style={{ color: 'var(--color-success)' }}>
              {progressPercentage}%
            </span>
          </div>
        </div>

        {/* Text */}
        <div className="flex-1 min-w-0">
          <h3 className="font-semibold text-base mb-1" style={{ color: 'var(--text-primary)' }}>
            📋 {t('dashboard:setup_banner.title', '{count} paso(s) más para desbloquear todas las funciones', { count: remainingSections.length })}
          </h3>
          <p className="text-sm" style={{ color: 'var(--text-secondary)' }}>
            {remainingSections.map(s => s.title).join(', ')} {t('dashboard:setup_banner.recommended', '(recomendado)')}
          </p>
        </div>

        {/* Expand/Collapse Button */}
        <button
          onClick={(e) => {
            e.stopPropagation();
            setExpanded(!expanded);
          }}
          className="flex-shrink-0 p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
          title={expanded ? 'Ocultar' : 'Expandir'}
        >
          {expanded ? (
            <ChevronUp className="w-5 h-5" style={{ color: 'var(--text-secondary)' }} />
          ) : (
            <ChevronDown className="w-5 h-5" style={{ color: 'var(--text-secondary)' }} />
          )}
        </button>

        {/* Dismiss Button */}
        <button
          onClick={(e) => {
            e.stopPropagation();
            handleDismiss();
          }}
          className="flex-shrink-0 p-2 rounded-lg hover:bg-[var(--color-error)]/10 transition-colors"
          title={t('dashboard:setup_banner.dismiss', 'Ocultar por 7 días')}
        >
          <X className="w-5 h-5" style={{ color: 'var(--text-tertiary)' }} />
        </button>
      </div>

      {/* Expanded Content */}
      {expanded && (
        <div
          className="px-4 pb-4 border-t"
          style={{ borderColor: 'var(--border-secondary)' }}
        >
          <div className="space-y-3 mt-4">
            {remainingSections.map((section) => {
              const Icon = section.icon || (() => <div>⚙️</div>);

              return (
                <button
                  key={section.id}
                  onClick={() => handleSectionClick(section.path)}
                  className="w-full flex items-center gap-4 p-4 rounded-lg border border-[var(--border-secondary)] hover:border-[var(--color-primary)] hover:bg-[var(--bg-secondary)] transition-all group text-left"
                >
                  {/* Icon */}
                  <div className="w-10 h-10 rounded-full flex items-center justify-center bg-[var(--bg-tertiary)] group-hover:bg-[var(--color-primary)]/10 transition-colors">
                    <Icon className="w-5 h-5 text-[var(--text-secondary)] group-hover:text-[var(--color-primary)] transition-colors" />
                  </div>

                  {/* Content */}
                  <div className="flex-1 min-w-0">
                    <h4 className="font-semibold mb-1" style={{ color: 'var(--text-primary)' }}>
                      {section.title}
                    </h4>
                    <p className="text-sm" style={{ color: 'var(--text-secondary)' }}>
                      {section.count} {t('dashboard:setup_banner.added', 'agregado(s)')} • {t('dashboard:setup_banner.recommended_count', 'Recomendado')}: {section.recommended}
                    </p>
                  </div>

                  {/* Arrow */}
                  <ArrowRight className="w-5 h-5 text-[var(--text-tertiary)] group-hover:text-[var(--color-primary)] group-hover:translate-x-1 transition-all" />
                </button>
              );
            })}
          </div>

          {/* Benefits of Completion */}
          <div
            className="mt-4 p-4 rounded-lg"
            style={{ backgroundColor: 'var(--color-info)]/5', border: '1px solid var(--color-info)/20' }}
          >
            <div className="flex items-start gap-3">
              <CheckCircle className="w-5 h-5 flex-shrink-0 mt-0.5" style={{ color: 'var(--color-info)' }} />
              <div>
                <h5 className="font-semibold text-sm mb-1" style={{ color: 'var(--text-primary)' }}>
                  {t('dashboard:setup_banner.benefits_title', '✨ Al completar estos pasos, desbloquearás')}:
                </h5>
                <ul className="text-sm space-y-1" style={{ color: 'var(--text-secondary)' }}>
                  <li>• {t('dashboard:setup_banner.benefit_1', 'Análisis de costos más preciso')}</li>
                  <li>• {t('dashboard:setup_banner.benefit_2', 'Recomendaciones de IA mejoradas')}</li>
                  <li>• {t('dashboard:setup_banner.benefit_3', 'Planificación de producción optimizada')}</li>
                </ul>
              </div>
            </div>
          </div>

          {/* Dismiss Info */}
          <p className="text-xs text-center mt-4" style={{ color: 'var(--text-tertiary)' }}>
            💡 {t('dashboard:setup_banner.dismiss_info', 'Puedes ocultar este banner por 7 días haciendo clic en la X')}
          </p>
        </div>
      )}
    </div>
  );
}
