
import React, { useState } from 'react';
import { Search, ArrowRight, Loader2, Globe, Link as LinkIcon, Languages, Upload, FileText, X, FolderOpen, FileUp } from 'lucide-react';
import { Language, AnalysisResult, SearchStrategy } from '../types';
import { parseMarkdownReport } from '../utils/reportParser';

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 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-2xl mx-auto mt-12 p-6">
      <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 Existing Audit
          </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">
            <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>
    </div>
  );
};
