
import React, { useState } from 'react';
import { Trash2, Plus, CheckCircle2, ExternalLink, FileText, Globe, Landmark, MapPin } from 'lucide-react';
import { Competitor } from '../types';

interface StepReviewProps {
  competitors: Competitor[]; // Flattened list for overall count and manual management
  categorizedCompetitors: { 
    localCompetitors: Competitor[]; 
    nationalCompetitors: Competitor[]; 
    internationalCompetitors: Competitor[];
  } | null;
  onRemove: (id: string) => void;
  onAdd: (name: string) => void;
  onConfirm: () => void;
  hasResults?: boolean;
  onShowReport?: () => void;
}

export const StepReview: React.FC<StepReviewProps> = ({ competitors, categorizedCompetitors, onRemove, onAdd, onConfirm, hasResults, onShowReport }) => {
  console.log("StepReview Props:", { competitors, categorizedCompetitors });
  const [newCompany, setNewCompany] = useState('');

  const handleAdd = (e: React.FormEvent) => {
    e.preventDefault();
    if (newCompany.trim()) {
      onAdd(newCompany.trim());
      setNewCompany('');
    }
  };

  const renderCompetitorList = (comps: Competitor[], category: string) => {
    // Filter out competitors that have been removed from the main list
    const activeIds = new Set(competitors.map(c => c.id));
    const activeComps = comps.filter(c => activeIds.has(c.id));

    if (!activeComps || activeComps.length === 0) {
      return (
        <li className="p-4 text-center text-slate-500 italic bg-white rounded-md border border-slate-100 mb-2 last:mb-0">
          Keine {category} Konkurrenten gefunden.
        </li>
      );
    }
    return activeComps.map((comp) => (
      <li key={comp.id} className="flex items-start justify-between p-4 hover:bg-slate-50 transition-colors group bg-white rounded-md border border-slate-100 mb-2 last:mb-0">
        <div className="flex-1">
          <div className="flex items-center gap-2">
            <span className="font-bold text-slate-800 text-lg">{comp.name}</span>
            {comp.url && (
              <a 
                href={comp.url} 
                target="_blank" 
                rel="noreferrer" 
                className="text-indigo-500 hover:text-indigo-700 p-1 rounded hover:bg-indigo-50"
                title={comp.url}
              >
                <ExternalLink size={14} />
              </a>
            )}
          </div>
          {comp.description && (
            <p className="text-sm text-slate-500 mt-1 pr-8">{comp.description}</p>
          )}
        </div>
        
        <button
          onClick={() => onRemove(comp.id)}
          className="text-slate-400 hover:text-red-500 p-2 rounded-full hover:bg-red-50 transition-colors opacity-0 group-hover:opacity-100 focus:opacity-100 self-center"
          aria-label="Remove"
        >
          <Trash2 size={18} />
        </button>
      </li>
    ));
  };

  return (
    <div className="max-w-4xl mx-auto mt-8 px-4 pb-24">
      <div className="flex items-end justify-between mb-6">
        <div>
          <h2 className="text-2xl font-bold text-slate-900">Confirm Target List</h2>
          <p className="text-slate-600 mt-1">Review the identified companies before starting the deep tech audit.</p>
        </div>
        <div className="text-right">
          <span className="bg-indigo-50 text-indigo-700 font-bold py-1 px-3 rounded-full text-sm">
            {competitors.length} Companies
          </span>
        </div>
      </div>

      <div className="space-y-8">
        {/* Local Competitors */}
        <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
          <h3 className="text-lg font-bold text-slate-800 mb-4 flex items-center gap-2">
            <MapPin size={20} className="text-indigo-600" /> Lokale Konkurrenten
          </h3>
          <ul className="space-y-2">
            {categorizedCompetitors?.localCompetitors && renderCompetitorList(categorizedCompetitors.localCompetitors, 'lokale')}
          </ul>
        </div>

        {/* National Competitors */}
        <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
          <h3 className="text-lg font-bold text-slate-800 mb-4 flex items-center gap-2">
            <Landmark size={20} className="text-indigo-600" /> Nationale Konkurrenten
          </h3>
          <ul className="space-y-2">
            {categorizedCompetitors?.nationalCompetitors && renderCompetitorList(categorizedCompetitors.nationalCompetitors, 'nationale')}
          </ul>
        </div>

        {/* International Competitors */}
        <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
          <h3 className="text-lg font-bold text-slate-800 mb-4 flex items-center gap-2">
            <Globe size={20} className="text-indigo-600" /> Internationale Konkurrenten
          </h3>
          <ul className="space-y-2">
            {categorizedCompetitors?.internationalCompetitors && renderCompetitorList(categorizedCompetitors.internationalCompetitors, 'internationale')}
          </ul>
        </div>

        {/* Manual Additions */}
        <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
          <h3 className="text-lg font-bold text-slate-800 mb-4 flex items-center gap-2">
            <Plus size={20} className="text-slate-600" /> Manuelle Ergänzungen
          </h3>
          <form onSubmit={handleAdd} className="flex gap-2">
            <input 
              type="text" 
              value={newCompany}
              onChange={(e) => setNewCompany(e.target.value)}
              placeholder="Add another company manually..."
              className="flex-1 px-4 py-2 rounded-lg border border-slate-300 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/20 outline-none"
            />
            <button 
              type="submit"
              disabled={!newCompany.trim()}
              className="bg-white border border-slate-300 text-slate-700 hover:bg-slate-100 font-medium px-4 py-2 rounded-lg flex items-center gap-2 disabled:opacity-50"
            >
              <Plus size={18} /> Add
            </button>
          </form>
          {competitors.length > 0 && (
            <ul className="mt-4 space-y-2">
              {competitors.filter(comp => !categorizedCompetitors?.localCompetitors?.some(c => c.id === comp.id) && 
                                          !categorizedCompetitors?.nationalCompetitors?.some(c => c.id === comp.id) &&
                                          !categorizedCompetitors?.internationalCompetitors?.some(c => c.id === comp.id))
                           .map((comp) => (
                <li key={comp.id} className="flex items-start justify-between p-4 hover:bg-slate-50 transition-colors group bg-white rounded-md border border-slate-100">
                  <div className="flex-1">
                    <div className="flex items-center gap-2">
                      <span className="font-bold text-slate-800 text-lg">{comp.name}</span>
                      {comp.url && (
                        <a 
                          href={comp.url} 
                          target="_blank" 
                          rel="noreferrer" 
                          className="text-indigo-500 hover:text-indigo-700 p-1 rounded hover:bg-indigo-50"
                          title={comp.url}
                        >
                          <ExternalLink size={14} />
                        </a>
                      )}
                    </div>
                    {comp.description && (
                      <p className="text-sm text-slate-500 mt-1 pr-8">{comp.description}</p>
                    )}
                  </div>
                  
                  <button
                    onClick={() => onRemove(comp.id)}
                    className="text-slate-400 hover:text-red-500 p-2 rounded-full hover:bg-red-50 transition-colors opacity-0 group-hover:opacity-100 focus:opacity-100 self-center"
                    aria-label="Remove"
                  >
                    <Trash2 size={18} />
                  </button>
                </li>
              ))}
            </ul>
          )}
        </div>
      </div>

      {/* Sticky Footer CTA */}
      <div className="fixed bottom-0 left-0 right-0 bg-white/80 backdrop-blur-md border-t border-slate-200 p-4 z-40">
        <div className="max-w-4xl mx-auto flex justify-end gap-3">
             {hasResults && onShowReport && (
                <button
                    onClick={onShowReport}
                    className="bg-white border border-slate-300 hover:bg-slate-50 text-slate-700 font-bold py-3 px-6 rounded-xl shadow-sm transition-all flex items-center gap-2"
                >
                    <FileText size={20} /> View Report
                </button>
            )}
             <button
                onClick={onConfirm}
                disabled={competitors.length === 0}
                className="bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-3 px-8 rounded-xl shadow-lg shadow-emerald-600/20 transition-all transform active:scale-[0.98] flex items-center gap-2"
            >
                <CheckCircle2 size={20} /> {hasResults ? "Restart Analysis" : "Confirm & Run Audit"}
            </button>
        </div>
      </div>
    </div>
  );
};
