
import React, { useState, useEffect, useMemo } from 'react';
import { analyzeDomain } from './services/geminiService';
import { DomainMetrics, HistoryItem } from './types';
import MetricCard from './components/MetricCard';
import { 
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer
} from 'recharts';

const MAX_DOMAINS = 200;
const CONCURRENCY_LIMIT = 3; // Number of simultaneous API calls

const App: React.FC = () => {
  const [domainInput, setDomainInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState<DomainMetrics[]>([]);
  const [history, setHistory] = useState<HistoryItem[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [progress, setProgress] = useState({ current: 0, total: 0 });
  const [selectedDomain, setSelectedDomain] = useState<DomainMetrics | null>(null);
  const [isStopping, setIsStopping] = useState(false);

  useEffect(() => {
    const savedHistory = localStorage.getItem('seo_history_v3');
    if (savedHistory) {
      setHistory(JSON.parse(savedHistory));
    }
  }, []);

  const handleSearch = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!domainInput.trim() || loading) return;

    const domains = domainInput
      .split(/[\s,\n]+/)
      .map(d => d.trim().replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0])
      .filter(d => d.length > 0)
      .slice(0, MAX_DOMAINS);

    if (domains.length === 0) return;

    setLoading(true);
    setError(null);
    setResults([]);
    setProgress({ current: 0, total: domains.length });
    setIsStopping(false);
    setSelectedDomain(null);

    const accumulatedResults: DomainMetrics[] = [];
    const newHistoryItems: HistoryItem[] = [];

    // Helper to process in batches
    const processInBatches = async () => {
      const queue = [...domains];
      const activePromises: Promise<void>[] = [];

      const processNext = async (): Promise<void> => {
        if (queue.length === 0 || isStopping) return;

        const d = queue.shift()!;
        try {
          const result = await analyzeDomain(d);
          accumulatedResults.push(result);
          setResults([...accumulatedResults]);
          setProgress(prev => ({ ...prev, current: prev.current + 1 }));

          const historyItem: HistoryItem = {
            id: Math.random().toString(36).substr(2, 9),
            domain: result.domain,
            timestamp: Date.now(),
            da: result.da,
            pa: result.pa,
            domainAge: result.domainAge
          };
          newHistoryItems.push(historyItem);
        } catch (err) {
          console.error(`Error analyzing ${d}:`, err);
          // Continue with next domain instead of failing completely
        }
        return processNext();
      };

      for (let i = 0; i < Math.min(CONCURRENCY_LIMIT, queue.length); i++) {
        activePromises.push(processNext());
      }

      await Promise.all(activePromises);
    };

    await processInBatches();

    const updatedHistory = [...newHistoryItems, ...history].slice(0, 50);
    setHistory(updatedHistory);
    localStorage.setItem('seo_history_v3', JSON.stringify(updatedHistory));
    setLoading(false);
    
    if (accumulatedResults.length > 0) {
        setSelectedDomain(accumulatedResults[0]);
    }
  };

  const exportToCSV = () => {
    if (results.length === 0) return;
    const headers = ["Domain", "DA", "PA", "Age", "Spam Score", "Backlinks"];
    const rows = results.map(r => [r.domain, r.da, r.pa, `"${r.domainAge}"`, `${r.spamScore}%`, r.totalBacklinks]);
    const csvContent = [headers, ...rows].map(e => e.join(",")).join("\n");
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement("a");
    const url = URL.createObjectURL(blob);
    link.setAttribute("href", url);
    link.setAttribute("download", `domain_analysis_${Date.now()}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return (
    <div className="min-h-screen bg-slate-950 text-slate-50 p-4 md:p-8">
      <div className="fixed top-0 left-0 w-full h-full pointer-events-none opacity-20 z-0">
        <div className="absolute top-[-10%] left-[-10%] w-[50%] h-[50%] bg-indigo-900 rounded-full blur-[150px]"></div>
        <div className="absolute bottom-[-10%] right-[-10%] w-[50%] h-[50%] bg-purple-900 rounded-full blur-[150px]"></div>
      </div>

      <div className="max-w-7xl mx-auto relative z-10">
        <header className="mb-8 text-center">
          <h1 className="text-4xl md:text-5xl font-extrabold tracking-tight mb-3 bg-clip-text text-transparent bg-gradient-to-r from-indigo-400 to-purple-400">
            Domain Insight Pro
          </h1>
          <p className="text-slate-400 text-base max-w-2xl mx-auto">
            Bulk Domain Analyzer. Mendukung hingga <span className="text-indigo-400 font-bold">200 domain</span> sekaligus dengan estimasi DA, PA, dan Age.
          </p>
        </header>

        {/* Input Section */}
        <div className="glass p-6 rounded-3xl mb-8 shadow-2xl">
          <form onSubmit={handleSearch} className="space-y-4">
            <textarea 
              placeholder="Masukkan hingga 200 domain (pisahkan dengan koma atau baris baru)..."
              className="w-full bg-slate-900/50 border border-slate-700 text-white px-5 py-3 rounded-2xl focus:outline-none focus:ring-2 focus:ring-indigo-500 transition-all text-base min-h-[150px] resize-none"
              value={domainInput}
              onChange={(e) => setDomainInput(e.target.value)}
              disabled={loading}
            />
            <div className="flex flex-col md:flex-row justify-between items-center gap-4">
              <div className="text-slate-500 text-xs">
                Mendukung paste dari Excel/Text. Batch processing otomatis aktif untuk stabilitas.
              </div>
              <div className="flex gap-3 w-full md:w-auto">
                {loading && (
                    <button 
                        type="button"
                        onClick={() => setIsStopping(true)}
                        className="flex-1 md:flex-none border border-red-500/50 text-red-400 px-6 py-3 rounded-xl hover:bg-red-500/10 transition-all text-sm font-semibold"
                    >
                        Hentikan
                    </button>
                )}
                <button 
                  type="submit"
                  disabled={loading}
                  className="flex-1 md:flex-none bg-indigo-600 hover:bg-indigo-500 text-white font-bold py-3 px-8 rounded-xl transition-all shadow-lg shadow-indigo-500/20 active:scale-95 disabled:opacity-50 min-w-[180px]"
                >
                  {loading ? `Memproses (${progress.current}/${progress.total})` : "Mulai Analisis"}
                </button>
              </div>
            </div>
          </form>
          
          {loading && (
            <div className="mt-6 space-y-2">
                <div className="flex justify-between text-xs text-slate-400 px-1">
                    <span>Progress Analisis</span>
                    <span>{Math.round((progress.current / progress.total) * 100)}%</span>
                </div>
                <div className="w-full h-2 bg-slate-800 rounded-full overflow-hidden">
                    <div 
                        className="h-full bg-gradient-to-r from-indigo-500 to-purple-500 transition-all duration-500"
                        style={{ width: `${(progress.current / progress.total) * 100}%` }}
                    ></div>
                </div>
            </div>
          )}
          {error && <p className="mt-4 text-red-400 text-sm font-medium">{error}</p>}
        </div>

        <div className="grid grid-cols-1 xl:grid-cols-3 gap-8">
          {/* Table View */}
          <div className="xl:col-span-2 space-y-6">
            <div className="glass rounded-3xl overflow-hidden">
              <div className="p-5 border-b border-slate-800 flex justify-between items-center bg-slate-900/50">
                <h3 className="font-bold flex items-center">
                  <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-2 text-indigo-400" viewBox="0 0 20 20" fill="currentColor"><path fillRule="evenodd" d="M3 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clipRule="evenodd" /></svg>
                  Daftar Analisis ({results.length})
                </h3>
                {results.length > 0 && (
                  <button onClick={exportToCSV} className="text-xs bg-slate-800 hover:bg-slate-700 px-3 py-1.5 rounded-lg transition-colors flex items-center">
                    <svg xmlns="http://www.w3.org/2000/svg" className="h-3 w-3 mr-1" viewBox="0 0 20 20" fill="currentColor"><path fillRule="evenodd" d="M3 17a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm3.293-7.707a1 1 0 011.414 0L9 10.586V3a1 1 0 112 0v7.586l1.293-1.293a1 1 0 111.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z" clipRule="evenodd" /></svg>
                    Export CSV
                  </button>
                )}
              </div>
              <div className="max-h-[600px] overflow-y-auto">
                <table className="w-full text-left text-sm">
                  <thead className="sticky top-0 bg-slate-900 z-10">
                    <tr className="border-b border-slate-800 text-slate-500">
                      <th className="px-6 py-3 font-semibold">Domain</th>
                      <th className="px-6 py-3 font-semibold">DA</th>
                      <th className="px-6 py-3 font-semibold">PA</th>
                      <th className="px-6 py-3 font-semibold">Age</th>
                      <th className="px-6 py-3 font-semibold text-right">Spam</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-800/50">
                    {results.length === 0 && !loading && (
                      <tr>
                        <td colSpan={5} className="px-6 py-12 text-center text-slate-600 italic">
                          Belum ada data. Silakan masukkan domain dan mulai analisis.
                        </td>
                      </tr>
                    )}
                    {results.map((r, i) => (
                      <tr 
                        key={i} 
                        className={`hover:bg-indigo-500/5 cursor-pointer transition-colors ${selectedDomain?.domain === r.domain ? 'bg-indigo-500/10' : ''}`}
                        onClick={() => setSelectedDomain(r)}
                      >
                        <td className="px-6 py-4 font-medium text-slate-200">{r.domain}</td>
                        <td className="px-6 py-4">
                          <span className={`px-2 py-0.5 rounded text-[10px] font-bold ${r.da > 50 ? 'bg-emerald-500/10 text-emerald-400' : 'bg-slate-800 text-slate-400'}`}>
                            {r.da}
                          </span>
                        </td>
                        <td className="px-6 py-4 text-slate-400">{r.pa}</td>
                        <td className="px-6 py-4 text-slate-500 text-xs">{r.domainAge}</td>
                        <td className="px-6 py-4 text-right">
                          <span className={r.spamScore > 10 ? 'text-red-400' : 'text-slate-500'}>{r.spamScore}%</span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>

          {/* Drill Down Detail View */}
          <div className="space-y-6">
            <div className="glass p-6 rounded-3xl sticky top-8">
              {selectedDomain ? (
                <div className="space-y-6 animate-in fade-in zoom-in duration-300">
                  <div className="pb-4 border-b border-slate-800">
                    <h2 className="text-xl font-bold text-indigo-400 break-all">{selectedDomain.domain}</h2>
                    <p className="text-xs text-slate-500 mt-1">Estimasi Age: <span className="text-slate-300 font-medium">{selectedDomain.domainAge}</span></p>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div className="bg-slate-900/50 p-4 rounded-2xl border border-slate-800">
                      <p className="text-[10px] uppercase tracking-wider text-slate-500 font-bold mb-1">Authority</p>
                      <div className="flex items-baseline space-x-1">
                        <span className="text-2xl font-bold text-white">{selectedDomain.da}</span>
                        <span className="text-[10px] text-slate-500">DA</span>
                      </div>
                    </div>
                    <div className="bg-slate-900/50 p-4 rounded-2xl border border-slate-800">
                      <p className="text-[10px] uppercase tracking-wider text-slate-500 font-bold mb-1">Page Value</p>
                      <div className="flex items-baseline space-x-1">
                        <span className="text-2xl font-bold text-white">{selectedDomain.pa}</span>
                        <span className="text-[10px] text-slate-500">PA</span>
                      </div>
                    </div>
                  </div>

                  <div className="space-y-4">
                    <div className="h-[180px] w-full">
                        <ResponsiveContainer width="100%" height="100%">
                            <BarChart data={[
                                { name: 'DA', val: selectedDomain.da },
                                { name: 'PA', val: selectedDomain.pa },
                                { name: 'Health', val: selectedDomain.siteHealth },
                                { name: 'Trust', val: selectedDomain.trustFlow }
                            ]}>
                                <CartesianGrid strokeDasharray="3 3" stroke="#1e293b" vertical={false} />
                                <XAxis dataKey="name" stroke="#64748b" fontSize={10} axisLine={false} tickLine={false} />
                                <Tooltip contentStyle={{ backgroundColor: '#0f172a', border: 'none', borderRadius: '12px', fontSize: '10px' }} />
                                <Bar dataKey="val" fill="#6366f1" radius={[4, 4, 0, 0]} barSize={30} />
                            </BarChart>
                        </ResponsiveContainer>
                    </div>

                    <div>
                      <h4 className="text-xs font-bold text-slate-400 mb-3 flex items-center uppercase tracking-widest">
                        Keywords Teratas
                      </h4>
                      <div className="flex flex-wrap gap-1.5">
                        {selectedDomain.topKeywords.map((kw, i) => (
                          <span key={i} className="text-[10px] px-2 py-1 bg-indigo-500/10 border border-indigo-500/20 text-indigo-300 rounded-md">
                            {kw}
                          </span>
                        ))}
                      </div>
                    </div>

                    <div>
                      <h4 className="text-xs font-bold text-slate-400 mb-3 flex items-center uppercase tracking-widest">
                        Saran Perbaikan
                      </h4>
                      <ul className="space-y-2">
                        {selectedDomain.recommendations.slice(0, 3).map((rec, i) => (
                          <li key={i} className="text-[11px] text-slate-400 flex items-start">
                            <span className="text-indigo-500 mr-2">•</span>
                            {rec}
                          </li>
                        ))}
                      </ul>
                    </div>
                  </div>
                </div>
              ) : (
                <div className="h-[400px] flex flex-col items-center justify-center text-center p-6 border-2 border-dashed border-slate-800 rounded-2xl">
                  <div className="bg-slate-900 w-16 h-16 rounded-full flex items-center justify-center mb-4 text-slate-700">
                    <svg xmlns="http://www.w3.org/2000/svg" className="h-8 w-8" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                    </svg>
                  </div>
                  <h4 className="text-slate-400 font-bold mb-2">Pilih Domain</h4>
                  <p className="text-xs text-slate-600">Klik salah satu baris di tabel untuk melihat analisis mendalam.</p>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      <footer className="mt-20 py-8 text-center text-slate-600 text-[10px] uppercase tracking-[0.2em]">
        <p>© {new Date().getFullYear()} Domain Insight Pro • Engine Powered by Gemini AI</p>
      </footer>
    </div>
  );
};

export default App;
