import React, { useState, useEffect } from 'react';
import { Search, ArrowRight, Loader2, Globe, Link as LinkIcon, Languages, Upload, FileText, X, FolderOpen, FileUp, History, Clock, Trash2 } from 'lucide-react';
import { Language, AnalysisResult, SearchStrategy } from '../types';
import { parseMarkdownReport } from '../utils/reportParser';
import { listProjects, loadProject, deleteProject } from '../services/geminiService';

interface StepInputProps {
  onSearch: (url: string, context: string, market: string, language: Language) => void;
  onLoadReport: (strategy: SearchStrategy, results: AnalysisResult[]) => void;
  isLoading: boolean;
}

const COUNTRIES = [
  "Germany", "Austria", "Switzerland", "United Kingdom", "France", "Spain", "Italy", "Netherlands", "Europe (General)", "USA"
];

export const StepInput: React.FC<StepInputProps> = ({ onSearch, onLoadReport, isLoading }) => {
  const [activeMode, setActiveMode] = useState<'new' | 'load'>('new');
  const [url, setUrl] = useState('');
  const [fileContent, setFileContent] = useState('');
  const [fileName, setFileName] = useState('');
  const [market, setMarket] = useState(COUNTRIES[0]);
  const [language, setLanguage] = useState<Language>('de');
  
  const [recentProjects, setRecentProjects] = useState<any[]>([]);
  const [isLoadingProjects, setIsLoadingProjects] = useState(false);
  const [showHistory, setShowHistory] = useState(false);

  const fetchProjects = async () => {
      setIsLoadingProjects(true);
      try {
          const projects = await listProjects();
          setRecentProjects(projects);
      } catch (e) {
          console.error("Failed to load projects", e);
      } finally {
          setIsLoadingProjects(false);
      }
  };

  useEffect(() => {
      if (showHistory) {
          fetchProjects();
      }
  }, [showHistory]);

  const handleProjectSelect = async (projectId: string) => {
      try {
          const projectData = await loadProject(projectId);
          // Check for full project data first
          if (projectData && (projectData.strategy || projectData.competitors)) {
              onLoadReport(projectData, []); // Pass full object, let App.tsx handle hydration logic
          } else {
              alert("Project data is incomplete or corrupted.");
          }
      } catch (e) {
          console.error(e);
          alert("Failed to load project.");
      }
  };

  const handleDeleteProject = async (e: React.MouseEvent, projectId: string) => {
      e.stopPropagation(); // Prevent loading the project
      if (confirm("Are you sure you want to delete this project?")) {
          try {
              await deleteProject(projectId);
              fetchProjects(); // Refresh list
          } catch (error) {
              console.error("Failed to delete", error);
              alert("Failed to delete project.");
          }
      }
  };

  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (event) => {
        setFileContent(event.target?.result as string);
        setFileName(file.name);
      };
      reader.readAsText(file);
    }
  };

  const handleLoadReport = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (event) => {
        const content = event.target?.result as string;
        const parsed = parseMarkdownReport(content);
        if (parsed) {
          onLoadReport(parsed.strategy, parsed.results);
        } else {
          alert("Could not parse report. Please make sure it's a valid ProspectIntel MD file.");
        }
      };
      reader.readAsText(file);
    }
  };

  const handleRemoveFile = () => {
    setFileContent('');
    setFileName('');
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (url.trim() && fileContent.trim()) {
      onSearch(url.trim(), fileContent.trim(), market, language);
    }
  };

  return (
    <div className="max-w-4xl mx-auto mt-12 p-6 relative">
      
      <div className="text-center mb-10">
        <h2 className="text-3xl font-bold text-slate-900 mb-4">Market Intelligence Agent</h2>
        <div className="flex justify-center gap-2 mb-6">
          <button 
            onClick={() => setActiveMode('new')}
            className={`px-4 py-2 rounded-lg text-sm font-bold transition-all ${activeMode === 'new' ? 'bg-indigo-600 text-white shadow-md' : 'bg-slate-100 text-slate-500 hover:bg-slate-200'}`}
          >
            Start New Audit
          </button>
          <button 
            onClick={() => setActiveMode('load')}
            className={`px-4 py-2 rounded-lg text-sm font-bold transition-all ${activeMode === 'load' ? 'bg-indigo-600 text-white shadow-md' : 'bg-slate-100 text-slate-500 hover:bg-slate-200'}`}
          >
            Load .MD File
          </button>
          <button 
            onClick={() => setShowHistory(true)}
            className="px-4 py-2 rounded-lg text-sm font-bold bg-slate-800 text-white shadow-md hover:bg-slate-700 flex items-center gap-2"
          >
            <History size={16} /> Load History
          </button>
        </div>
        
        {activeMode === 'new' ? (
          <p className="text-lg text-slate-600">
            Upload your <strong>Strategy Document</strong> to let AI design the perfect market audit.
          </p>
        ) : (
          <p className="text-lg text-slate-600">
            Select an exported <strong>.md Report</strong> to continue working on an existing analysis.
          </p>
        )}
      </div>

      <div className="bg-white shadow-xl rounded-2xl p-8 border border-slate-100">
        {activeMode === 'new' ? (
          <form onSubmit={handleSubmit} className="space-y-8">
            {/* Form Fields (kept same) */}
            <div>
              <label className="block text-sm font-semibold text-slate-700 mb-3">
                  1. Strategic Context (Markdown/Text)
                  <span className="block font-normal text-slate-400 text-xs mt-1">Expected: Offer, Target Groups, Personas, Pain Points, Benefits.</span>
              </label>
              
              {!fileContent ? (
                  <div className="border-2 border-dashed border-slate-300 rounded-xl p-8 text-center hover:border-indigo-400 hover:bg-slate-50 transition-all group">
                      <input 
                          type="file" 
                          accept=".md,.txt,.markdown" 
                          onChange={handleFileUpload}
                          id="strategy-upload"
                          className="hidden"
                      />
                      <label htmlFor="strategy-upload" className="cursor-pointer flex flex-col items-center gap-3 w-full">
                          <div className="bg-indigo-50 p-3 rounded-full text-indigo-500 group-hover:bg-indigo-100 transition-colors">
                              <Upload size={24} />
                          </div>
                          <div>
                              <p className="font-semibold text-slate-700">Upload Strategy File</p>
                              <p className="text-xs text-slate-400 mt-1">.md or .txt files</p>
                          </div>
                      </label>
                  </div>
              ) : (
                  <div className="flex items-center gap-4 p-4 bg-emerald-50 border border-emerald-100 rounded-xl">
                      <div className="bg-emerald-100 p-2 rounded-lg shrink-0">
                          <FileText className="text-emerald-600" size={24} />
                      </div>
                      <div className="flex-1 min-w-0">
                          <p className="font-semibold text-emerald-900 truncate">{fileName}</p>
                          <p className="text-xs text-emerald-700">Context loaded successfully</p>
                      </div>
                      <button 
                          type="button"
                          onClick={handleRemoveFile}
                          className="p-2 hover:bg-emerald-100 rounded-full text-emerald-600 transition-colors"
                      >
                          <X size={18} />
                      </button>
                  </div>
              )}
            </div>

            <div>
              <label className="block text-sm font-semibold text-slate-700 mb-2">2. Reference Company URL</label>
              <div className="relative">
                <input
                  type="text"
                  value={url}
                  onChange={(e) => setUrl(e.target.value)}
                  placeholder="e.g. https://www.reference-customer.com"
                  className="w-full pl-12 pr-4 py-3 rounded-xl border border-slate-200 focus:border-indigo-500 focus:ring-4 focus:ring-indigo-500/10 outline-none transition-all text-lg"
                  required
                />
                <LinkIcon className="absolute left-4 top-3.5 text-slate-400" size={20} />
              </div>
               <p className="text-xs text-slate-400 mt-2">Used to calibrate the search and find lookalikes.</p>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-semibold text-slate-700 mb-2">Target Market</label>
                <div className="relative">
                  <select
                    value={market}
                    onChange={(e) => setMarket(e.target.value)}
                    className="w-full pl-12 pr-4 py-3 rounded-xl border border-slate-200 focus:border-indigo-500 focus:ring-4 focus:ring-indigo-500/10 outline-none transition-all text-lg appearance-none bg-white cursor-pointer"
                  >
                    {COUNTRIES.map((c) => (
                      <option key={c} value={c}>{c}</option>
                    ))}
                  </select>
                  <Globe className="absolute left-4 top-3.5 text-slate-400" size={20} />
                </div>
              </div>

              <div>
                <label className="block text-sm font-semibold text-slate-700 mb-2">Report Language</label>
                <div className="relative">
                  <select
                    value={language}
                    onChange={(e) => setLanguage(e.target.value as Language)}
                    className="w-full pl-12 pr-4 py-3 rounded-xl border border-slate-200 focus:border-indigo-500 focus:ring-4 focus:ring-indigo-500/10 outline-none transition-all text-lg appearance-none bg-white cursor-pointer"
                  >
                    <option value="de">German</option>
                    <option value="en">English</option>
                  </select>
                  <Languages className="absolute left-4 top-3.5 text-slate-400" size={20} />
                </div>
              </div>
            </div>

            <button
              type="submit"
              disabled={isLoading || !url || !fileContent}
              className="w-full bg-indigo-600 hover:bg-indigo-700 disabled:bg-indigo-300 disabled:cursor-not-allowed text-white font-bold py-4 rounded-xl shadow-lg shadow-indigo-600/20 transition-all transform active:scale-[0.98] flex items-center justify-center gap-2 text-lg"
            >
              {isLoading ? (
                <>
                  <Loader2 className="animate-spin" /> Analyzing Strategy...
                </>
              ) : (
                <>
                  Analyze Context & Build Strategy <ArrowRight size={20} />
                </>
              )}
            </button>
          </form>
        ) : (
          <div className="space-y-6">
            <div className="border-2 border-dashed border-slate-300 rounded-xl p-12 text-center hover:border-indigo-400 hover:bg-slate-50 transition-all group">
              <input 
                  type="file" 
                  accept=".md" 
                  onChange={handleLoadReport}
                  id="report-load"
                  className="hidden"
              />
              <label htmlFor="report-load" className="cursor-pointer flex flex-col items-center gap-4 w-full">
                  <div className="bg-indigo-50 p-4 rounded-full text-indigo-500 group-hover:bg-indigo-100 transition-colors">
                      <FolderOpen size={32} />
                  </div>
                  <div>
                      <p className="text-xl font-semibold text-slate-900">Upload Markdown Report</p>
                      <p className="text-sm text-slate-500 mt-1">Reconstruct your analysis from a .md file</p>
                  </div>
                  <div className="mt-4 bg-white border border-slate-200 px-6 py-2 rounded-lg font-bold text-slate-700 shadow-sm flex items-center gap-2 group-hover:bg-slate-50">
                    <FileUp size={18} /> Browse Files
                  </div>
              </label>
            </div>
            
            <div className="bg-slate-50 p-4 rounded-xl border border-slate-100">
              <h4 className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Note:</h4>
              <p className="text-sm text-slate-600">
                Loading an existing audit will take you directly to the Report view. You can then trigger new outreach campaigns for any company in the list.
              </p>
            </div>
          </div>
        )}
      </div>

      {/* History Modal */}
      {showHistory && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm">
              <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg overflow-hidden flex flex-col max-h-[80vh]">
                  <div className="p-4 border-b border-slate-200 flex justify-between items-center bg-slate-50">
                      <h3 className="font-bold text-slate-900 text-lg flex items-center gap-2">
                          <History className="text-indigo-600" size={20} />
                          Project History
                      </h3>
                      <button onClick={() => setShowHistory(false)} className="text-slate-400 hover:text-slate-600 p-1">
                          <X size={20} />
                      </button>
                  </div>
                  
                  <div className="flex-1 overflow-y-auto p-4 space-y-3">
                      {isLoadingProjects ? (
                          <div className="flex justify-center p-8">
                              <Loader2 className="animate-spin text-indigo-500" size={32} />
                          </div>
                      ) : recentProjects.length > 0 ? (
                          recentProjects.map((p) => (
                              <button 
                                  key={p.id}
                                  onClick={() => handleProjectSelect(p.id)}
                                  className="w-full text-left p-4 rounded-xl bg-slate-50 hover:bg-indigo-50 border border-slate-200 hover:border-indigo-200 transition-all group relative flex items-center justify-between"
                              >
                                  <div className="flex-1 min-w-0 pr-4">
                                      <div className="font-semibold text-slate-800 group-hover:text-indigo-700 truncate">{p.name}</div>
                                      <div className="flex items-center gap-2 mt-1.5 text-xs text-slate-400">
                                          <Clock size={12} />
                                          <span>{new Date(p.updated_at).toLocaleDateString()} {new Date(p.updated_at).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}</span>
                                      </div>
                                  </div>
                                  
                                  <div className="flex items-center gap-2">
                                      <span 
                                          onClick={(e) => handleDeleteProject(e, p.id)}
                                          className="p-2 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-full transition-colors z-10"
                                          title="Delete Project"
                                      >
                                          <Trash2 size={18} />
                                      </span>
                                      <ArrowRight className="text-indigo-300 group-hover:text-indigo-600 transition-colors" size={20} />
                                  </div>
                              </button>
                          ))
                      ) : (
                          <div className="text-center text-slate-400 py-10">
                              <History size={48} className="mx-auto mb-4 opacity-20" />
                              No past projects found.
                          </div>
                      )}
                  </div>
              </div>
          </div>
      )}

    </div>
  );
};