'use client';

import React, { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import { formatCurrency } from '@/lib/utils';
import {
  Search,
  Loader2,
  FileText,
  Users,
  Building2,
  BookOpen,
  CreditCard,
  Landmark,
  DollarSign,
  ChevronRight,
} from 'lucide-react';

interface SearchResult {
  id: string;
  title: string;
  subtitle: string;
  category: string;
  href: string;
  badge?: string;
  badgeColor?: string;
  amount?: number;
}

const CATEGORY_ICONS: Record<string, React.ReactNode> = {
  'Accounts Payable': <FileText size={16} className="text-blue-500" />,
  'Accounts Receivable': <FileText size={16} className="text-emerald-500" />,
  'Vendors': <Building2 size={16} className="text-orange-500" />,
  'Customers': <Users size={16} className="text-purple-500" />,
  'Chart of Accounts': <BookOpen size={16} className="text-indigo-500" />,
  'Journal Entries': <BookOpen size={16} className="text-cyan-500" />,
  'Payments': <CreditCard size={16} className="text-pink-500" />,
  'Bank Accounts': <Landmark size={16} className="text-teal-500" />,
};

const BADGE_COLORS: Record<string, string> = {
  emerald: 'bg-emerald-900/25 text-emerald-700',
  red: 'bg-red-900/25 text-red-700',
  blue: 'bg-blue-900/25 text-blue-700',
  amber: 'bg-amber-900/25 text-amber-700',
  slate: 'bg-[#1A1A1F] text-[#8B8B9E]',
};

export default function SearchPage() {
  const searchParams = useSearchParams();
  const initialQuery = searchParams.get('q') || '';

  const [query, setQuery] = useState(initialQuery);
  const [grouped, setGrouped] = useState<Record<string, SearchResult[]>>({});
  const [totalCount, setTotalCount] = useState(0);
  const [loading, setLoading] = useState(false);
  const [searched, setSearched] = useState(false);


  const doSearch = useCallback(async (q: string) => {
    if (q.trim().length < 2) {
      setGrouped({});
      setTotalCount(0);
      return;
    }
    setLoading(true);
    try {
      const res = await fetch(`/api/search?q=${encodeURIComponent(q)}`);
      const data = await res.json();
      setGrouped(data.grouped || {});
      setTotalCount(data.totalCount || 0);
      setSearched(true);
    } catch {
      console.error('Search failed');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (initialQuery) doSearch(initialQuery);
  }, [initialQuery, doSearch]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    doSearch(query);
  };

  const categories = Object.keys(grouped);

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      {/* Search Header */}
      <div>
        <h1 className="text-2xl font-bold text-[#F0F0F3] flex items-center gap-2">
          <Search size={24} className="text-blue-600" />
          Search
        </h1>
        <p className="text-sm text-[#5A5A6E] mt-0.5">
          Search across all modules — invoices, vendors, customers, accounts, and more
        </p>
      </div>

      {/* Search Input */}
      <form onSubmit={handleSubmit} className="relative">
        <div className="flex items-center gap-2 bg-[#1A1A1F] border border-[#2A2A32] rounded-xl px-4 py-3 shadow-sm focus-within:ring-2 focus-within:ring-blue-500 focus-within:border-blue-500">
          <Search size={20} className="text-[#5A5A6E] flex-shrink-0" />
          <input
            type="text"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Search invoices, vendors, customers, accounts, payments..."
            className="flex-1 text-base outline-none text-[#F0F0F3] placeholder-[#5A5A6E]"
            autoFocus
          />
          {loading && <Loader2 size={18} className="text-blue-500 animate-spin flex-shrink-0" />}
          <button
            type="submit"
            className="px-4 py-1.5 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors flex-shrink-0"
          >
            Search
          </button>
        </div>
      </form>

      {/* Results */}
      {searched && !loading && totalCount === 0 && (
        <div className="text-center py-12">
          <Search size={40} className="text-slate-200 mx-auto mb-3" />
          <p className="text-sm text-[#5A5A6E]">No results found for &quot;{query}&quot;</p>
          <p className="text-xs text-[#5A5A6E] mt-1">Try a different search term</p>
        </div>
      )}

      {totalCount > 0 && (
        <p className="text-xs text-[#5A5A6E]">
          {totalCount} result{totalCount !== 1 ? 's' : ''} across {categories.length} categor{categories.length !== 1 ? 'ies' : 'y'}
        </p>
      )}

      {categories.map((category) => (
        <div key={category} className="bg-[#1A1A1F] rounded-xl border border-[#2A2A32] overflow-hidden">
          {/* Category Header */}
          <div className="flex items-center gap-2 px-5 py-3 bg-[#111114] border-b border-[#2A2A32]">
            {CATEGORY_ICONS[category] || <FileText size={16} className="text-[#5A5A6E]" />}
            <h2 className="text-sm font-semibold text-[#8B8B9E]">{category}</h2>
            <span className="text-[10px] bg-[#222228] text-[#5A5A6E] px-1.5 py-0.5 rounded-full font-medium">
              {grouped[category].length}
            </span>
          </div>

          {/* Results */}
          <div className="divide-y divide-slate-50">
            {grouped[category].map((result) => (
              <Link
                key={result.id}
                href={result.href}
                className="flex items-center gap-4 px-5 py-3 hover:bg-[#222228] transition-colors"
              >
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <p className="text-sm font-medium text-[#F0F0F3]">{result.title}</p>
                    {result.badge && (
                      <span
                        className={`text-[10px] px-1.5 py-0.5 rounded font-medium ${
                          BADGE_COLORS[result.badgeColor || 'slate']
                        }`}
                      >
                        {result.badge.replace(/_/g, ' ')}
                      </span>
                    )}
                  </div>
                  <p className="text-xs text-[#5A5A6E] truncate mt-0.5">{result.subtitle}</p>
                </div>
                {result.amount !== undefined && (
                  <p className="text-sm font-semibold text-[#8B8B9E] flex items-center gap-0.5 flex-shrink-0">
                    <DollarSign size={12} className="text-[#5A5A6E]" />
                    {formatCurrency(result.amount).replace('$', '')}
                  </p>
                )}
                <ChevronRight size={14} className="text-slate-300 flex-shrink-0" />
              </Link>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}
