import React, { useState } from 'react';
import { SWOTCombination } from '../../services/api';
import { SWOT_COLORS, SWOT_LABELS } from '../../utils/constants';
import { TrendingUp, AlertTriangle, Target, Shield, ChevronDown, ChevronUp } from 'lucide-react';

interface SWOTAnalysisProps {
  combinations: SWOTCombination[];
}

const SWOTAnalysis: React.FC<SWOTAnalysisProps> = ({ combinations }) => {
  const [expandedCategory, setExpandedCategory] = useState<string | null>(null);

  // Group combinations by SWOT category
  const groupedCombinations = {
    S: combinations.filter(c => c.label === 'S'),
    W: combinations.filter(c => c.label === 'W'),
    O: combinations.filter(c => c.label === 'O'),
    T: combinations.filter(c => c.label === 'T'),
  };

  const getCategoryIcon = (category: string) => {
    switch (category) {
      case 'S': return Shield;
      case 'W': return AlertTriangle;
      case 'O': return Target;
      case 'T': return TrendingUp;
      default: return Shield;
    }
  };

  const getCategoryDescription = (category: string) => {
    switch (category) {
      case 'S': return 'Your natural strengths and positive traits that give you advantages';
      case 'W': return 'Areas that may require attention or could pose challenges';
      case 'O': return 'Potential opportunities and favorable circumstances';
      case 'T': return 'Potential threats or situations to be mindful of';
      default: return '';
    }
  };

  const toggleCategory = (category: string) => {
    setExpandedCategory(expandedCategory === category ? null : category);
  };

  return (
    <div className="bg-white rounded-xl shadow-lg p-8">
      <div className="text-center mb-8">
        <h3 className="text-2xl font-bold text-gray-800 mb-2">SWOT Analysis</h3>
        <p className="text-gray-600">
          Based on numerology patterns found in your calculation
        </p>
        <div className="text-sm text-gray-500 mt-2">
          {combinations.length} pattern{combinations.length !== 1 ? 's' : ''} identified
        </div>
      </div>

      {/* SWOT Grid */}
      <div className="grid md:grid-cols-2 gap-6">
        {Object.entries(groupedCombinations).map(([category, items]) => {
          const Icon = getCategoryIcon(category);
          const hasItems = items.length > 0;
          const isExpanded = expandedCategory === category;

          return (
            <div
              key={category}
              className={`border-2 rounded-lg transition-all duration-300 ${
                hasItems 
                  ? `${SWOT_COLORS[category as keyof typeof SWOT_COLORS]} hover:shadow-md` 
                  : 'bg-gray-50 border-gray-200 opacity-50'
              }`}
            >
              {/* Category Header */}
              <div
                className={`p-4 cursor-pointer ${hasItems ? 'hover:bg-opacity-80' : ''}`}
                onClick={() => hasItems && toggleCategory(category)}
              >
                <div className="flex items-center justify-between">
                  <div className="flex items-center space-x-3">
                    <div className="p-2 bg-white rounded-lg shadow-sm">
                      <Icon className="h-5 w-5" />
                    </div>
                    <div>
                      <h4 className="font-semibold text-lg">
                        {SWOT_LABELS[category as keyof typeof SWOT_LABELS]}
                      </h4>
                      <p className="text-sm opacity-80">
                        {hasItems ? `${items.length} pattern${items.length !== 1 ? 's' : ''}` : 'No patterns found'}
                      </p>
                    </div>
                  </div>
                  {hasItems && (
                    <div className="text-gray-600">
                      {isExpanded ? (
                        <ChevronUp className="h-5 w-5" />
                      ) : (
                        <ChevronDown className="h-5 w-5" />
                      )}
                    </div>
                  )}
                </div>
              </div>

              {/* Category Description */}
              {!hasItems && (
                <div className="px-4 pb-4">
                  <p className="text-sm text-gray-500">
                    {getCategoryDescription(category)}
                  </p>
                </div>
              )}

              {/* Expandable Content */}
              {hasItems && (
                <div className={`transition-all duration-300 overflow-hidden ${
                  isExpanded ? 'max-h-96 opacity-100' : 'max-h-0 opacity-0'
                }`}>
                  <div className="px-4 pb-4">
                    <p className="text-sm opacity-80 mb-3">
                      {getCategoryDescription(category)}
                    </p>
                    <div className="space-y-3">
                      {items.map((item, index) => (
                        <div
                          key={index}
                          className="bg-white bg-opacity-70 rounded-lg p-3 border border-white border-opacity-50"
                        >
                          <div className="flex items-center justify-between mb-2">
                            <span className="font-mono text-sm font-bold">
                              {item.sequence}
                            </span>
                            <span className="text-xs opacity-75">
                              Pattern {index + 1}
                            </span>
                          </div>
                          <p className="text-sm leading-relaxed">
                            {item.description}
                          </p>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Overall Summary */}
      {combinations.length > 0 && (
        <div className="mt-8 p-6 bg-gradient-to-r from-purple-50 to-blue-50 rounded-lg border border-purple-200">
          <h4 className="text-lg font-semibold text-gray-800 mb-3">SWOT Summary</h4>
          <div className="grid md:grid-cols-2 gap-4 text-sm">
            <div>
              <span className="font-medium text-gray-700">Dominant Areas:</span>
              <span className="ml-2 text-gray-600">
                {Object.entries(groupedCombinations)
                  .filter(([, items]) => items.length > 0)
                  .sort((a, b) => b[1].length - a[1].length)
                  .map(([category]) => SWOT_LABELS[category as keyof typeof SWOT_LABELS])
                  .join(', ') || 'None identified'}
              </span>
            </div>
            <div>
              <span className="font-medium text-gray-700">Total Patterns:</span>
              <span className="ml-2 text-gray-600">
                {combinations.length} unique numerology combinations
              </span>
            </div>
          </div>
        </div>
      )}

      {/* No Patterns Message */}
      {combinations.length === 0 && (
        <div className="text-center py-8">
          <div className="text-gray-400 mb-4">
            <Target className="h-12 w-12 mx-auto" />
          </div>
          <h4 className="text-lg font-medium text-gray-600 mb-2">No SWOT Patterns Found</h4>
          <p className="text-sm text-gray-500">
            Your numerology calculation didn't reveal any specific SWOT combinations from our database.
            This doesn't mean you lack strengths or opportunities - it simply means your pattern is unique!
          </p>
        </div>
      )}
    </div>
  );
};

export default SWOTAnalysis;