'use client';

import { useState, useEffect } from 'react';
import { Search, Copy, Check, Hash, Key, AlertCircle, Loader2, Database } from 'lucide-react';

interface SearchResult {
  found: boolean;
  hashType?: string;
  hash?: string;
  isPlaintext?: boolean;
  plaintext?: string;
  wasGenerated?: boolean;
  hashes?: {
    md5: string;
    sha1: string;
    sha256: string;
    sha512: string;
  };
  results?: Array<{
    plaintext: string;
    hashes: {
      md5: string;
      sha1: string;
      sha256: string;
      sha512: string;
    };
  }>;
  message?: string;
}

interface IndexStats {
  documentCount: number;
  indexSize: number;
}

function formatBytes(bytes: number): string {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

function formatNumber(num: number): string {
  return num.toLocaleString();
}

export default function Home() {
  const [query, setQuery] = useState('');
  const [result, setResult] = useState<SearchResult | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [copiedField, setCopiedField] = useState<string | null>(null);
  const [stats, setStats] = useState<IndexStats | null>(null);

  useEffect(() => {
    const fetchStats = async () => {
      try {
        const response = await fetch('/api/health');
        if (response.ok) {
          const data = await response.json();
          if (data.index?.stats) {
            setStats(data.index.stats);
          }
        }
      } catch (_err) {
        // Silently fail - stats are not critical
      }
    };

    fetchStats();
  }, [result]); // Refresh stats after each search result

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

    setLoading(true);
    setError('');
    setResult(null);

    try {
      const response = await fetch('/api/search', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ query: query.trim() })
      });

      if (!response.ok) {
        throw new Error('Search failed');
      }

      const data = await response.json();
      setResult(data);
    } catch (_err) {
      setError('Failed to perform search. Please check your connection.');
    } finally {
      setLoading(false);
    }
  };

  const copyToClipboard = (text: string, field: string) => {
    navigator.clipboard.writeText(text);
    setCopiedField(field);
    setTimeout(() => setCopiedField(null), 2000);
  };

  const HashDisplay = ({ label, value, field }: { label: string; value: string; field: string }) => (
    <div className="bg-gray-50 rounded-lg p-4 border border-gray-200">
      <div className="flex items-center justify-between mb-2">
        <span className="text-sm font-semibold text-gray-700 uppercase">{label}</span>
        <button
          onClick={() => copyToClipboard(value, field)}
          className="text-gray-500 hover:text-gray-700 transition-colors"
          title="Copy to clipboard"
        >
          {copiedField === field ? (
            <Check className="w-4 h-4 text-green-600" />
          ) : (
            <Copy className="w-4 h-4" />
          )}
        </button>
      </div>
      <code className="text-xs font-mono break-all text-gray-900">{value}</code>
    </div>
  );

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50">
      <div className="container mx-auto px-4 py-12 max-w-4xl">
        {/* Header */}
        <div className="text-center mb-12">
          <div className="flex items-center justify-center mb-4">
            <div className="bg-gradient-to-r from-blue-600 to-purple-600 p-4 rounded-2xl shadow-lg">
              <Hash className="w-12 h-12 text-white" />
            </div>
          </div>
          <h1 className="text-5xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent mb-3">
            Hasher
          </h1>
          <p className="text-gray-600 text-lg">
            Search for hashes or generate them from plaintext
          </p>
          <p className="text-sm text-gray-500 mt-2">
            Supports MD5, SHA1, SHA256, and SHA512
          </p>
          {stats && (
            <div className="flex items-center justify-center gap-4 mt-4 text-sm text-gray-500">
              <div className="flex items-center gap-1.5">
                <Database className="w-4 h-4" />
                <span><strong>{formatNumber(stats.documentCount)}</strong> hashes</span>
              </div>
              <span className="text-gray-300">•</span>
              <div>
                <span><strong>{formatBytes(stats.indexSize)}</strong> indexed</span>
              </div>
            </div>
          )}
        </div>

        {/* Search Form */}
        <form onSubmit={handleSearch} className="mb-8">
          <div className="relative">
            <input
              type="text"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="Enter a hash or plaintext..."
              className="w-full px-6 py-4 pr-14 text-lg rounded-2xl border-2 border-gray-200 focus:border-blue-500 focus:ring-4 focus:ring-blue-100 outline-none transition-all shadow-sm"
            />
            <button
              type="submit"
              disabled={loading || !query.trim()}
              className="absolute right-2 top-1/2 -translate-y-1/2 bg-gradient-to-r from-blue-600 to-purple-600 text-white p-3 rounded-xl hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed transition-all"
            >
              {loading ? (
                <Loader2 className="w-6 h-6 animate-spin" />
              ) : (
                <Search className="w-6 h-6" />
              )}
            </button>
          </div>
        </form>

        {/* Error Message */}
        {error && (
          <div className="bg-red-50 border-2 border-red-200 rounded-2xl p-4 mb-8 flex items-start gap-3">
            <AlertCircle className="w-6 h-6 text-red-600 flex-shrink-0 mt-0.5" />
            <div>
              <h3 className="font-semibold text-red-900 mb-1">Error</h3>
              <p className="text-red-700">{error}</p>
            </div>
          </div>
        )}

        {/* Results */}
        {result && (
          <div className="bg-white rounded-2xl shadow-xl p-8 border border-gray-100">
            {result.isPlaintext ? (
              <>
                <div className="flex items-center gap-3 mb-6 pb-6 border-b border-gray-200">
                  <div className="bg-green-100 p-3 rounded-xl">
                    <Key className="w-6 h-6 text-green-600" />
                  </div>
                  <div>
                    <h2 className="text-2xl font-bold text-gray-900">Generated Hashes</h2>
                    <p className="text-gray-600">For plaintext: <span className="font-mono font-semibold">{result.plaintext}</span></p>
                  </div>
                </div>
                <div className="space-y-4">
                  <HashDisplay label="MD5" value={result.hashes!.md5} field="md5-gen" />
                  <HashDisplay label="SHA1" value={result.hashes!.sha1} field="sha1-gen" />
                  <HashDisplay label="SHA256" value={result.hashes!.sha256} field="sha256-gen" />
                  <HashDisplay label="SHA512" value={result.hashes!.sha512} field="sha512-gen" />
                </div>
                {result.wasGenerated && (
                  <div className="mt-6 bg-blue-50 border border-blue-200 rounded-xl p-4">
                    <p className="text-sm text-blue-800">
                      ✨ These hashes have been saved to the database for future lookups.
                    </p>
                  </div>
                )}
              </>
            ) : result.found && result.results && result.results.length > 0 ? (
              <>
                <div className="flex items-center gap-3 mb-6 pb-6 border-b border-gray-200">
                  <div className="bg-green-100 p-3 rounded-xl">
                    <Check className="w-6 h-6 text-green-600" />
                  </div>
                  <div>
                    <h2 className="text-2xl font-bold text-gray-900">Hash Found!</h2>
                    <p className="text-gray-600">Type: <span className="font-semibold uppercase">{result.hashType}</span></p>
                  </div>
                </div>
                {result.results.map((item, idx) => (
                  <div key={idx} className="mb-6 last:mb-0">
                    <div className="bg-green-50 border-2 border-green-200 rounded-xl p-5 mb-4">
                      <div className="flex items-center justify-between mb-2">
                        <span className="text-sm font-semibold text-green-900 uppercase">Plaintext</span>
                        <button
                          onClick={() => copyToClipboard(item.plaintext, `plaintext-${idx}`)}
                          className="text-green-700 hover:text-green-900 transition-colors"
                        >
                          {copiedField === `plaintext-${idx}` ? (
                            <Check className="w-4 h-4" />
                          ) : (
                            <Copy className="w-4 h-4" />
                          )}
                        </button>
                      </div>
                      <div className="text-2xl font-bold text-green-900 font-mono break-all">
                        {item.plaintext}
                      </div>
                    </div>
                    <div className="space-y-3">
                      <HashDisplay label="MD5" value={item.hashes.md5} field={`md5-${idx}`} />
                      <HashDisplay label="SHA1" value={item.hashes.sha1} field={`sha1-${idx}`} />
                      <HashDisplay label="SHA256" value={item.hashes.sha256} field={`sha256-${idx}`} />
                      <HashDisplay label="SHA512" value={item.hashes.sha512} field={`sha512-${idx}`} />
                    </div>
                  </div>
                ))}
              </>
            ) : (
              <>
                <div className="flex items-center gap-3 mb-4">
                  <div className="bg-yellow-100 p-3 rounded-xl">
                    <AlertCircle className="w-6 h-6 text-yellow-600" />
                  </div>
                  <div>
                    <h2 className="text-2xl font-bold text-gray-900">Hash Not Found</h2>
                    <p className="text-gray-600">Type: <span className="font-semibold uppercase">{result.hashType}</span></p>
                  </div>
                </div>
                <div className="bg-yellow-50 border border-yellow-200 rounded-xl p-4">
                  <p className="text-yellow-800">
                    This hash is not in our database. Try searching with plaintext to generate hashes.
                  </p>
                </div>
              </>
            )}
          </div>
        )}

        {/* Info Cards */}
        {!result && !loading && (
          <div className="grid md:grid-cols-2 gap-6 mt-12">
            <div className="bg-white rounded-2xl p-6 shadow-lg border border-gray-100">
              <div className="bg-blue-100 w-12 h-12 rounded-xl flex items-center justify-center mb-4">
                <Search className="w-6 h-6 text-blue-600" />
              </div>
              <h3 className="text-xl font-bold text-gray-900 mb-2">Search Hashes</h3>
              <p className="text-gray-600">
                Enter a hash to find its original plaintext value. Our database contains commonly used words and phrases.
              </p>
            </div>
            <div className="bg-white rounded-2xl p-6 shadow-lg border border-gray-100">
              <div className="bg-purple-100 w-12 h-12 rounded-xl flex items-center justify-center mb-4">
                <Hash className="w-6 h-6 text-purple-600" />
              </div>
              <h3 className="text-xl font-bold text-gray-900 mb-2">Generate Hashes</h3>
              <p className="text-gray-600">
                Enter any plaintext to instantly generate MD5, SHA1, SHA256, and SHA512 hashes. Results are saved automatically.
              </p>
            </div>
          </div>
        )}

        {/* Footer */}
        <footer className="mt-16 text-center text-gray-500 text-sm">
          <p>Powered by Redis • Built with Next.js</p>
        </footer>
      </div>
    </div>
  );
}

