'use client';

import { useState, useEffect, useCallback, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Search,
  Phone,
  Wallet,
  Smartphone,
  Facebook,
  User,
  ShieldCheck,
  ShieldAlert,
  ShieldX,
  AlertTriangle,
  ChevronDown,
  ChevronRight,
  CreditCard,
  MapPin,
  Clock,
  Eye,
  ArrowLeft,
  LayoutGrid,
  List,
  FileText,
  TrendingUp,
  Plus,
  History,
  X,
  Zap,
  ChevronLeft,
  ChevronRight as ChevronRightIcon,
} from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Skeleton } from '@/components/ui/skeleton';
import { Separator } from '@/components/ui/separator';
import { useAppStore } from '@/store/app-store';
import type { SearchResult, ScamReportType } from '@/types';

// ─── Helpers ────────────────────────────────────────────────────────────────────

function formatBDT(amount: number): string {
  if (amount >= 10000000) return `৳${(amount / 10000000).toFixed(1)}Cr`;
  if (amount >= 100000) return `৳${(amount / 100000).toFixed(1)}L`;
  if (amount >= 1000) return `৳${(amount / 1000).toFixed(1)}K`;
  return `৳${amount.toLocaleString('en-BD')}`;
}

function timeAgo(dateStr: string): string {
  const now = new Date();
  const date = new Date(dateStr);
  const seconds = Math.floor((now.getTime() - date.getTime()) / 1000);
  if (seconds < 60) return 'Just now';
  const minutes = Math.floor(seconds / 60);
  if (minutes < 60) return `${minutes}m ago`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours}h ago`;
  const days = Math.floor(hours / 24);
  if (days < 30) return `${days}d ago`;
  const months = Math.floor(days / 30);
  if (months < 12) return `${months}mo ago`;
  return `${Math.floor(months / 12)}y ago`;
}

// ─── Risk Config ────────────────────────────────────────────────────────────────

const riskConfig: Record<string, { label: string; color: string; bg: string; border: string; icon: React.ElementType; progressColor: string; gradientFrom: string; gradientTo: string }> = {
  low: {
    label: 'Low Risk',
    color: 'text-emerald-600 dark:text-emerald-400',
    bg: 'bg-emerald-500/10',
    border: 'border-emerald-500/30',
    icon: ShieldCheck,
    progressColor: 'bg-emerald-500',
    gradientFrom: 'from-emerald-500',
    gradientTo: 'to-emerald-600',
  },
  medium: {
    label: 'Medium Risk',
    color: 'text-yellow-600 dark:text-yellow-400',
    bg: 'bg-yellow-500/10',
    border: 'border-yellow-500/30',
    icon: ShieldAlert,
    progressColor: 'bg-yellow-500',
    gradientFrom: 'from-yellow-500',
    gradientTo: 'to-orange-500',
  },
  high: {
    label: 'High Risk',
    color: 'text-orange-600 dark:text-orange-400',
    bg: 'bg-orange-500/10',
    border: 'border-orange-500/30',
    icon: ShieldX,
    progressColor: 'bg-orange-500',
    gradientFrom: 'from-orange-500',
    gradientTo: 'to-red-500',
  },
  critical: {
    label: 'Critical Risk',
    color: 'text-red-600 dark:text-red-400',
    bg: 'bg-red-500/10',
    border: 'border-red-500/30',
    icon: AlertTriangle,
    progressColor: 'bg-red-500',
    gradientFrom: 'from-red-500',
    gradientTo: 'to-red-700',
  },
};

// ─── Entity Type Config ─────────────────────────────────────────────────────────

const entityTypeConfig: Record<string, { label: string; icon: React.ElementType; color: string; bg: string }> = {
  phone: { label: 'Phone', icon: Phone, color: 'text-blue-600 dark:text-blue-400', bg: 'bg-blue-500/10' },
  bkash: { label: 'bKash', icon: Wallet, color: 'text-pink-600 dark:text-pink-400', bg: 'bg-pink-500/10' },
  nagad: { label: 'Nagad', icon: Smartphone, color: 'text-orange-600 dark:text-orange-400', bg: 'bg-orange-500/10' },
  facebook: { label: 'Facebook', icon: Facebook, color: 'text-blue-700 dark:text-blue-300', bg: 'bg-blue-500/10' },
  seller: { label: 'Seller', icon: User, color: 'text-purple-600 dark:text-purple-400', bg: 'bg-purple-500/10' },
};

// ─── Filter Tab Type ────────────────────────────────────────────────────────────

type FilterTab = 'all' | 'phone' | 'bkash' | 'nagad' | 'facebook' | 'seller';
type ViewMode = 'entity' | 'report';

const filterTabs: { value: FilterTab; label: string; icon: React.ElementType }[] = [
  { value: 'all', label: 'All', icon: Search },
  { value: 'phone', label: 'Phone', icon: Phone },
  { value: 'bkash', label: 'bKash', icon: Wallet },
  { value: 'nagad', label: 'Nagad', icon: Smartphone },
  { value: 'facebook', label: 'Facebook', icon: Facebook },
  { value: 'seller', label: 'Seller', icon: User },
];

// ─── Popular Searches ───────────────────────────────────────────────────────────

const POPULAR_SEARCHES = [
  { label: '01712345678', icon: Phone, type: 'phone' },
  { label: 'bKash scam', icon: Wallet, type: 'bkash' },
  { label: 'Facebook seller', icon: Facebook, type: 'facebook' },
  { label: 'Nagad fraud', icon: Smartphone, type: 'nagad' },
  { label: 'Online shop scam', icon: User, type: 'seller' },
];

// ─── Search History Helpers ─────────────────────────────────────────────────────

const SEARCH_HISTORY_KEY = 'scamchecker_search_history';
const MAX_HISTORY = 8;

function getSearchHistory(): string[] {
  if (typeof window === 'undefined') return [];
  try {
    const stored = localStorage.getItem(SEARCH_HISTORY_KEY);
    return stored ? JSON.parse(stored) : [];
  } catch {
    return [];
  }
}

function addToSearchHistory(query: string): void {
  if (!query.trim()) return;
  try {
    const history = getSearchHistory().filter((h) => h !== query.trim());
    history.unshift(query.trim());
    if (history.length > MAX_HISTORY) history.pop();
    localStorage.setItem(SEARCH_HISTORY_KEY, JSON.stringify(history));
  } catch {
    // Silently fail
  }
}

function clearSearchHistory(): void {
  try {
    localStorage.removeItem(SEARCH_HISTORY_KEY);
  } catch {
    // Silently fail
  }
}

// ─── Loading Skeleton ───────────────────────────────────────────────────────────

function SearchLoadingSkeleton() {
  return (
    <div className="space-y-4">
      {Array.from({ length: 4 }).map((_, i) => (
        <Card key={i} className="border-border/50">
          <CardContent className="p-4 sm:p-6">
            <div className="flex items-start gap-4">
              <Skeleton className="h-12 w-12 rounded-xl shrink-0" />
              <div className="flex-1 space-y-3">
                <Skeleton className="h-6 w-52" />
                <div className="flex gap-2">
                  <Skeleton className="h-5 w-16 rounded-full" />
                  <Skeleton className="h-5 w-24 rounded-full" />
                </div>
                <Skeleton className="h-2 w-48 rounded-full" />
                <div className="flex gap-4">
                  <Skeleton className="h-4 w-20" />
                  <Skeleton className="h-4 w-20" />
                  <Skeleton className="h-4 w-24" />
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      ))}
    </div>
  );
}

function ReportLoadingSkeleton() {
  return (
    <div className="space-y-3">
      {Array.from({ length: 5 }).map((_, i) => (
        <Card key={i} className="border-border/50">
          <CardContent className="p-4">
            <div className="space-y-2">
              <Skeleton className="h-5 w-3/4" />
              <div className="flex gap-2">
                <Skeleton className="h-5 w-16 rounded-full" />
                <Skeleton className="h-5 w-20 rounded-full" />
              </div>
              <div className="flex gap-4">
                <Skeleton className="h-4 w-16" />
                <Skeleton className="h-4 w-16" />
                <Skeleton className="h-4 w-16" />
              </div>
            </div>
          </CardContent>
        </Card>
      ))}
    </div>
  );
}

// ─── Empty State ────────────────────────────────────────────────────────────────

function EmptyState({ query, viewMode, onSuggestionClick }: { query: string; viewMode: ViewMode; onSuggestionClick: (q: string) => void }) {
  const suggestions = ['01712345678', 'bKash scam', 'Facebook fraud', 'Nagad', 'online shop'];
  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.4 }}
    >
      <Card className="border-dashed">
        <CardContent className="py-16 text-center">
          <motion.div
            animate={{ y: [0, -8, 0] }}
            transition={{ duration: 2, repeat: Infinity, ease: 'easeInOut' }}
            className="inline-flex p-5 rounded-full bg-emerald-500/10 mb-5"
          >
            <Search className="h-10 w-10 text-emerald-500" />
          </motion.div>
          <h3 className="text-xl font-semibold mb-2">No results found</h3>
          <p className="text-muted-foreground max-w-md mx-auto mb-6">
            {query
              ? `No ${viewMode === 'entity' ? 'entities' : 'reports'} matching "${query}" were found. Try a different search term or check the spelling.`
              : 'Enter a phone number, bKash number, or name to search for scam reports.'}
          </p>
          <div className="space-y-3">
            <p className="text-sm text-muted-foreground">Try searching for:</p>
            <div className="flex flex-wrap justify-center gap-2">
              {suggestions.map((s) => (
                <button
                  key={s}
                  onClick={() => onSuggestionClick(s)}
                  className="px-3 py-1.5 rounded-full border border-border/50 bg-muted/50 hover:bg-emerald-500/10 hover:border-emerald-500/30 text-sm transition-all"
                >
                  {s}
                </button>
              ))}
            </div>
          </div>
          <p className="text-sm text-muted-foreground mt-6">
            Can&apos;t find what you&apos;re looking for?{' '}
            <span className="text-emerald-500 font-medium cursor-pointer hover:underline">
              Help protect others by reporting a scam.
            </span>
          </p>
        </CardContent>
      </Card>
    </motion.div>
  );
}

// ─── Entity Card ────────────────────────────────────────────────────────────────

function EntityCard({
  entity,
  onReportClick,
  onEntitySearch,
  onQuickReport,
}: {
  entity: SearchResult;
  onReportClick: (id: string) => void;
  onEntitySearch: (query: string) => void;
  onQuickReport: (entityValue: string) => void;
}) {
  const [isExpanded, setIsExpanded] = useState(false);
  const risk = riskConfig[entity.riskLevel] || riskConfig.low;
  const entityConf = entityTypeConfig[entity.entityType] || entityTypeConfig.phone;
  const RiskIcon = risk.icon;
  const EntityIcon = entityConf.icon;

  return (
    <motion.div
      initial={{ opacity: 0, y: 16 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.35 }}
      layout
    >
      <Card className="border-border/50 hover:border-emerald-500/20 hover:shadow-lg hover:shadow-emerald-500/5 transition-all duration-300 overflow-hidden group">
        <CardContent className="p-4 sm:p-5">
          {/* Header row */}
          <div className="flex items-start gap-3">
            <div className={`p-2.5 rounded-xl ${entityConf.bg} shrink-0 group-hover:scale-110 transition-transform duration-300`}>
              <EntityIcon className={`h-5 w-5 ${entityConf.color}`} />
            </div>
            <div className="flex-1 min-w-0">
              {/* Entity value & badges */}
              <div className="flex items-center gap-2 flex-wrap mb-1.5">
                <button
                  onClick={() => onEntitySearch(entity.entityValue)}
                  className="font-semibold text-base sm:text-lg hover:text-emerald-500 transition-colors text-left break-all"
                >
                  {entity.entityValue}
                </button>
                <Badge variant="outline" className={`text-xs ${entityConf.color} ${entityConf.bg} border-current/20`}>
                  {entityConf.label}
                </Badge>
                <Badge variant="outline" className={`text-xs ${risk.color} ${risk.bg} ${risk.border}`}>
                  <RiskIcon className="h-3 w-3" />
                  {risk.label}
                </Badge>
              </div>

              {/* Risk Score Progress Bar */}
              <div className="flex items-center gap-3 mb-3">
                <div className="flex-1 max-w-[240px]">
                  <div className="flex items-center justify-between mb-1.5">
                    <span className="text-xs text-muted-foreground font-medium">Risk Score</span>
                    <span className={`text-xs font-bold ${risk.color}`}>{entity.riskScore}/100</span>
                  </div>
                  <div className="h-2.5 w-full bg-muted rounded-full overflow-hidden">
                    <motion.div
                      className={`h-full rounded-full bg-gradient-to-r ${risk.gradientFrom} ${risk.gradientTo}`}
                      initial={{ width: 0 }}
                      animate={{ width: `${entity.riskScore}%` }}
                      transition={{ duration: 1, ease: 'easeOut' }}
                    />
                  </div>
                </div>
              </div>

              {/* Stats row */}
              <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm text-muted-foreground mb-2">
                <span className="flex items-center gap-1">
                  <FileText className="h-3.5 w-3.5" />
                  {entity.reportCount} {entity.reportCount === 1 ? 'report' : 'reports'}
                </span>
                <span className="flex items-center gap-1">
                  <Eye className="h-3.5 w-3.5" />
                  {entity.evidenceCount} {entity.evidenceCount === 1 ? 'evidence' : 'evidence'}
                </span>
                {entity.lastReported && (
                  <span className="flex items-center gap-1">
                    <Clock className="h-3.5 w-3.5" />
                    Last reported {timeAgo(entity.lastReported)}
                  </span>
                )}
              </div>

              {/* Quick Actions */}
              <div className="flex items-center gap-2 mt-2">
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={(e) => {
                    e.stopPropagation();
                    onQuickReport(entity.entityValue);
                  }}
                  className="h-7 gap-1.5 text-xs text-emerald-600 dark:text-emerald-400 hover:text-emerald-700 hover:bg-emerald-500/10"
                >
                  <Plus className="h-3 w-3" />
                  Report this number
                </Button>
              </div>
            </div>
          </div>

          {/* Expand toggle */}
          {entity.relatedReports.length > 0 && (
            <>
              <Separator className="my-3" />
              <button
                onClick={() => setIsExpanded(!isExpanded)}
                className="flex items-center gap-2 text-sm text-emerald-600 dark:text-emerald-400 hover:text-emerald-700 dark:hover:text-emerald-300 transition-colors font-medium w-full"
              >
                {isExpanded ? (
                  <ChevronDown className="h-4 w-4" />
                ) : (
                  <ChevronRight className="h-4 w-4" />
                )}
                {isExpanded ? 'Hide' : 'View'} {entity.relatedReports.length} related {entity.relatedReports.length === 1 ? 'report' : 'reports'}
              </button>

              <AnimatePresence>
                {isExpanded && (
                  <motion.div
                    initial={{ height: 0, opacity: 0 }}
                    animate={{ height: 'auto', opacity: 1 }}
                    exit={{ height: 0, opacity: 0 }}
                    transition={{ duration: 0.3 }}
                    className="overflow-hidden"
                  >
                    <div className="mt-3 space-y-2 max-h-80 overflow-y-auto pr-1 scrollbar-thin">
                      {entity.relatedReports.map((report) => {
                        const reportRisk = riskConfig[report.riskLevel] || riskConfig.low;
                        const ReportRiskIcon = reportRisk.icon;
                        return (
                          <div
                            key={report.id}
                            className="flex items-center justify-between p-3 rounded-lg border border-border/50 hover:border-emerald-500/20 hover:bg-emerald-500/5 transition-all cursor-pointer group/item"
                            onClick={() => onReportClick(report.id)}
                          >
                            <div className="flex-1 min-w-0 mr-3">
                              <h4 className="text-sm font-medium group-hover/item:text-emerald-500 transition-colors line-clamp-1">
                                {report.title}
                              </h4>
                              <div className="flex items-center gap-2 mt-1 text-xs text-muted-foreground">
                                {report.category && (
                                  <span>{report.category.name}</span>
                                )}
                                {report.amountLost > 0 && (
                                  <span className="text-red-500">
                                    {formatBDT(report.amountLost)}
                                  </span>
                                )}
                              </div>
                            </div>
                            <div className="flex items-center gap-2 shrink-0">
                              <Badge variant="outline" className={`text-[10px] ${reportRisk.color} ${reportRisk.bg} ${reportRisk.border}`}>
                                <ReportRiskIcon className="h-2.5 w-2.5" />
                                {reportRisk.label}
                              </Badge>
                              <ChevronRight className="h-4 w-4 text-muted-foreground group-hover/item:text-emerald-500 transition-colors" />
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>
            </>
          )}
        </CardContent>
      </Card>
    </motion.div>
  );
}

// ─── Report Card ────────────────────────────────────────────────────────────────

function ReportCard({
  report,
  onReportClick,
}: {
  report: ScamReportType;
  onReportClick: (id: string) => void;
}) {
  const risk = riskConfig[report.riskLevel] || riskConfig.low;
  const RiskIcon = risk.icon;

  return (
    <motion.div
      initial={{ opacity: 0, x: -16 }}
      animate={{ opacity: 1, x: 0 }}
      transition={{ duration: 0.3 }}
    >
      <Card
        className="group cursor-pointer border-border/50 hover:border-emerald-500/30 transition-all duration-300 hover:shadow-lg hover:shadow-emerald-500/5"
        onClick={() => onReportClick(report.id)}
      >
        <CardContent className="p-4 sm:p-5">
          <div className="flex items-start justify-between gap-3">
            <div className="flex-1 min-w-0">
              <div className="flex flex-wrap items-center gap-2 mb-1.5">
                {report.category && (
                  <Badge variant="secondary" className="text-xs">
                    {report.category.name}
                  </Badge>
                )}
                <Badge variant="outline" className={`text-xs ${risk.color} ${risk.bg} ${risk.border}`}>
                  <RiskIcon className="h-3 w-3" />
                  {risk.label}
                </Badge>
              </div>
              <h3 className="font-semibold text-base sm:text-lg group-hover:text-emerald-500 transition-colors line-clamp-1">
                {report.title}
              </h3>
              <div className="flex flex-wrap items-center gap-x-4 gap-y-1 mt-2 text-sm text-muted-foreground">
                {report.amountLost > 0 && (
                  <span className="flex items-center gap-1 text-red-500 dark:text-red-400">
                    <CreditCard className="h-3.5 w-3.5" />
                    {formatBDT(report.amountLost)}
                  </span>
                )}
                {report.district && (
                  <span className="flex items-center gap-1">
                    <MapPin className="h-3.5 w-3.5" />
                    {report.district}
                  </span>
                )}
                <span className="flex items-center gap-1">
                  <Clock className="h-3.5 w-3.5" />
                  {timeAgo(report.createdAt)}
                </span>
                <span className="flex items-center gap-1">
                  <TrendingUp className="h-3.5 w-3.5" />
                  {report.upvotes} upvotes
                </span>
              </div>
            </div>
            <ChevronRight className="h-5 w-5 text-muted-foreground group-hover:text-emerald-500 transition-colors shrink-0 mt-1" />
          </div>
        </CardContent>
      </Card>
    </motion.div>
  );
}

// ─── Pagination Component ───────────────────────────────────────────────────────

function Pagination({
  currentPage,
  totalPages,
  onPageChange,
}: {
  currentPage: number;
  totalPages: number;
  onPageChange: (page: number) => void;
}) {
  const getPageNumbers = (): (number | 'ellipsis')[] => {
    if (totalPages <= 7) {
      return Array.from({ length: totalPages }, (_, i) => i + 1);
    }
    const pages: (number | 'ellipsis')[] = [1];
    if (currentPage > 3) pages.push('ellipsis');
    const start = Math.max(2, currentPage - 1);
    const end = Math.min(totalPages - 1, currentPage + 1);
    for (let i = start; i <= end; i++) pages.push(i);
    if (currentPage < totalPages - 2) pages.push('ellipsis');
    pages.push(totalPages);
    return pages;
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      className="flex items-center justify-center gap-1.5 mt-8"
    >
      <Button
        variant="outline"
        size="sm"
        disabled={currentPage === 1}
        onClick={() => onPageChange(currentPage - 1)}
        className="gap-1 h-9"
      >
        <ChevronLeft className="h-4 w-4" />
        <span className="hidden sm:inline">Previous</span>
      </Button>
      <div className="flex items-center gap-1">
        {getPageNumbers().map((pageNum, idx) =>
          pageNum === 'ellipsis' ? (
            <span key={`ellipsis-${idx}`} className="px-2 text-muted-foreground">
              ...
            </span>
          ) : (
            <Button
              key={pageNum}
              variant={currentPage === pageNum ? 'default' : 'outline'}
              size="sm"
              onClick={() => onPageChange(pageNum)}
              className={`w-9 h-9 p-0 transition-all ${
                currentPage === pageNum
                  ? 'bg-emerald-600 hover:bg-emerald-700 text-white shadow-md shadow-emerald-500/20'
                  : 'hover:border-emerald-500/30 hover:text-emerald-500'
              }`}
            >
              {pageNum}
            </Button>
          )
        )}
      </div>
      <Button
        variant="outline"
        size="sm"
        disabled={currentPage === totalPages}
        onClick={() => onPageChange(currentPage + 1)}
        className="gap-1 h-9"
      >
        <span className="hidden sm:inline">Next</span>
        <ChevronRightIcon className="h-4 w-4" />
      </Button>
    </motion.div>
  );
}

// ─── Main SearchPage Component ──────────────────────────────────────────────────

export function SearchPage() {
  const navigate = useAppStore((s) => s.navigate);
  const searchQuery = useAppStore((s) => s.searchQuery);
  const setSearchQuery = useAppStore((s) => s.setSearchQuery);
  const setSelectedReportId = useAppStore((s) => s.setSelectedReportId);

  const [inputValue, setInputValue] = useState(searchQuery);
  const [activeFilter, setActiveFilter] = useState<FilterTab>('all');
  const [viewMode, setViewMode] = useState<ViewMode>('entity');
  const [entityResults, setEntityResults] = useState<SearchResult[]>([]);
  const [reportResults, setReportResults] = useState<ScamReportType[]>([]);
  const [totalResults, setTotalResults] = useState(0);
  const [isLoading, setIsLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [searchHistory, setSearchHistory] = useState<string[]>([]);
  const [showHistory, setShowHistory] = useState(false);
  const [isSearchFocused, setIsSearchFocused] = useState(false);

  const debounceTimerRef = useRef<NodeJS.Timeout | null>(null);
  const searchInputRef = useRef<HTMLInputElement>(null);

  // Load search history
  useEffect(() => {
    setSearchHistory(getSearchHistory());
  }, []);

  // Sync input with store query
  useEffect(() => {
    setInputValue(searchQuery);
  }, [searchQuery]);

  // Fetch entity search results
  const fetchEntityResults = useCallback(async (query: string) => {
    if (!query.trim()) {
      setEntityResults([]);
      setTotalResults(0);
      return;
    }
    setIsLoading(true);
    try {
      const res = await fetch(`/api/search?q=${encodeURIComponent(query.trim())}`);
      const data = await res.json();
      if (data.success) {
        let results = data.data.results as SearchResult[];
        // Apply filter
        if (activeFilter !== 'all') {
          results = results.filter((r) => r.entityType === activeFilter);
        }
        setEntityResults(results);
        setTotalResults(data.data.totalResults);
      }
    } catch {
      setEntityResults([]);
    } finally {
      setIsLoading(false);
    }
  }, [activeFilter]);

  // Fetch report search results
  const fetchReportResults = useCallback(async (query: string, page: number) => {
    if (!query.trim()) {
      setReportResults([]);
      return;
    }
    setIsLoading(true);
    try {
      const res = await fetch(
        `/api/reports?search=${encodeURIComponent(query.trim())}&limit=10&sort=createdAt&page=${page}`
      );
      const data = await res.json();
      if (data.success) {
        setReportResults(data.data.reports);
        setTotalPages(data.data.pagination.totalPages);
      }
    } catch {
      setReportResults([]);
    } finally {
      setIsLoading(false);
    }
  }, []);

  // Auto-search when query or filter changes
  useEffect(() => {
    if (viewMode === 'entity') {
      fetchEntityResults(searchQuery);
    } else {
      fetchReportResults(searchQuery, currentPage);
    }
  }, [searchQuery, activeFilter, viewMode, currentPage, fetchEntityResults, fetchReportResults]);

  // Reset page when filter or view mode changes
  useEffect(() => {
    setCurrentPage(1);
  }, [activeFilter, viewMode, searchQuery]);

  // Debounced search handler
  const handleInputChange = useCallback((value: string) => {
    setInputValue(value);
    if (debounceTimerRef.current) {
      clearTimeout(debounceTimerRef.current);
    }
    debounceTimerRef.current = setTimeout(() => {
      const trimmed = value.trim();
      if (trimmed) {
        setSearchQuery(trimmed);
        addToSearchHistory(trimmed);
        setSearchHistory(getSearchHistory());
      } else {
        setSearchQuery('');
      }
    }, 500);
  }, [setSearchQuery]);

  const handleSearch = useCallback(() => {
    const trimmed = inputValue.trim();
    if (trimmed) {
      setSearchQuery(trimmed);
      addToSearchHistory(trimmed);
      setSearchHistory(getSearchHistory());
      setCurrentPage(1);
    }
  }, [inputValue, setSearchQuery]);

  const handleReportClick = useCallback(
    (id: string) => {
      setSelectedReportId(id);
      navigate('report-detail');
    },
    [setSelectedReportId, navigate]
  );

  const handleEntitySearch = useCallback(
    (query: string) => {
      setSearchQuery(query);
      setInputValue(query);
      addToSearchHistory(query);
      setSearchHistory(getSearchHistory());
      setCurrentPage(1);
    },
    [setSearchQuery]
  );

  const handleQuickReport = useCallback(
    (entityValue: string) => {
      // Pre-fill search query and navigate to report form
      setSearchQuery(entityValue);
      navigate('report');
    },
    [setSearchQuery, navigate]
  );

  const handlePageChange = useCallback((page: number) => {
    setCurrentPage(page);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, []);

  const handleHistoryClick = useCallback(
    (query: string) => {
      setInputValue(query);
      setSearchQuery(query);
      setShowHistory(false);
      setCurrentPage(1);
    },
    [setSearchQuery]
  );

  const handleClearHistory = useCallback(() => {
    clearSearchHistory();
    setSearchHistory([]);
  }, []);

  const handleSuggestionClick = useCallback(
    (query: string) => {
      setInputValue(query);
      setSearchQuery(query);
      addToSearchHistory(query);
      setSearchHistory(getSearchHistory());
      setCurrentPage(1);
    },
    [setSearchQuery]
  );

  return (
    <div className="min-h-screen bg-background">
      {/* Hero Search Header */}
      <div className="relative overflow-hidden border-b">
        {/* Animated Background */}
        <div className="absolute inset-0 bg-gradient-to-br from-emerald-950/20 via-teal-950/10 to-transparent dark:from-emerald-950/40 dark:via-teal-950/20 dark:to-transparent" />
        <div className="absolute inset-0">
          <motion.div
            animate={{ opacity: [0.3, 0.6, 0.3] }}
            transition={{ duration: 4, repeat: Infinity, ease: 'easeInOut' }}
            className="absolute top-4 right-[10%] w-64 h-64 bg-emerald-500/5 rounded-full blur-3xl"
          />
          <motion.div
            animate={{ opacity: [0.2, 0.5, 0.2] }}
            transition={{ duration: 5, repeat: Infinity, ease: 'easeInOut', delay: 1 }}
            className="absolute bottom-0 left-[5%] w-48 h-48 bg-teal-500/5 rounded-full blur-3xl"
          />
        </div>

        <div className="relative max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 pt-8 pb-8">
          {/* Back button & Title */}
          <div className="flex items-center gap-3 mb-6">
            <Button
              variant="ghost"
              size="icon"
              onClick={() => navigate('home')}
              className="shrink-0 hover:bg-emerald-500/10 hover:text-emerald-500"
            >
              <ArrowLeft className="h-5 w-5" />
            </Button>
            <div>
              <h1 className="text-xl sm:text-2xl font-bold">Search Database</h1>
              <p className="text-sm text-muted-foreground">Find scam reports by phone, bKash, or name</p>
            </div>
          </div>

          {/* Google-style Search Input */}
          <div className="relative max-w-2xl mx-auto">
            <motion.div
              animate={{
                boxShadow: isSearchFocused
                  ? '0 4px 20px rgba(16, 185, 129, 0.15)'
                  : '0 1px 3px rgba(0, 0, 0, 0.08)',
              }}
              transition={{ duration: 0.3 }}
              className="relative"
            >
              <Search className="absolute left-5 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground group-focus-within:text-emerald-500 transition-colors" />
              <Input
                ref={searchInputRef}
                type="text"
                placeholder="Search phone number, bKash, Facebook page..."
                value={inputValue}
                onChange={(e) => handleInputChange(e.target.value)}
                onFocus={() => {
                  setIsSearchFocused(true);
                  if (searchHistory.length > 0 && !inputValue) setShowHistory(true);
                }}
                onBlur={() => {
                  setIsSearchFocused(false);
                  setTimeout(() => setShowHistory(false), 200);
                }}
                onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                className="h-14 pl-12 pr-12 text-base sm:text-lg rounded-2xl border-2 border-emerald-500/20 focus-visible:border-emerald-500/50 focus-visible:ring-emerald-500/20 bg-background/90 backdrop-blur-sm shadow-sm"
              />
              {inputValue && (
                <button
                  onClick={() => {
                    setInputValue('');
                    setSearchQuery('');
                    searchInputRef.current?.focus();
                  }}
                  className="absolute right-5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                >
                  <X className="h-5 w-5" />
                </button>
              )}
            </motion.div>

            {/* Search History Dropdown */}
            <AnimatePresence>
              {showHistory && searchHistory.length > 0 && !inputValue && (
                <motion.div
                  initial={{ opacity: 0, y: -4 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -4 }}
                  transition={{ duration: 0.15 }}
                  className="absolute z-50 top-full mt-2 w-full bg-background border border-border rounded-xl shadow-xl overflow-hidden"
                >
                  <div className="flex items-center justify-between px-4 py-2 border-b bg-muted/30">
                    <span className="text-xs font-medium text-muted-foreground flex items-center gap-1.5">
                      <History className="h-3 w-3" />
                      Recent Searches
                    </span>
                    <button
                      onClick={handleClearHistory}
                      className="text-xs text-muted-foreground hover:text-destructive transition-colors"
                    >
                      Clear all
                    </button>
                  </div>
                  <div className="max-h-60 overflow-y-auto">
                    {searchHistory.map((query, idx) => (
                      <button
                        key={`${query}-${idx}`}
                        className="flex items-center gap-3 w-full px-4 py-2.5 hover:bg-emerald-500/5 transition-colors text-left"
                        onMouseDown={() => handleHistoryClick(query)}
                      >
                        <History className="h-4 w-4 text-muted-foreground shrink-0" />
                        <span className="text-sm">{query}</span>
                      </button>
                    ))}
                  </div>
                </motion.div>
              )}
            </AnimatePresence>
          </div>

          {/* Popular Searches & Search History Chips */}
          <div className="max-w-2xl mx-auto mt-4 space-y-3">
            {/* Search History Chips */}
            {searchHistory.length > 0 && (
              <div className="flex items-center gap-2 flex-wrap">
                <History className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
                {searchHistory.slice(0, 5).map((query) => (
                  <button
                    key={query}
                    onClick={() => handleHistoryClick(query)}
                    className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full border border-border/50 bg-muted/30 hover:bg-emerald-500/10 hover:border-emerald-500/30 text-xs transition-all"
                  >
                    {query}
                    <X
                      className="h-3 w-3 text-muted-foreground hover:text-destructive"
                      onClick={(e) => {
                        e.stopPropagation();
                        const updated = searchHistory.filter((h) => h !== query);
                        try {
                          localStorage.setItem(SEARCH_HISTORY_KEY, JSON.stringify(updated));
                        } catch { /* ignore */ }
                        setSearchHistory(updated);
                      }}
                    />
                  </button>
                ))}
              </div>
            )}

            {/* Popular Searches */}
            {!searchQuery && (
              <div className="flex items-center gap-2 flex-wrap">
                <Zap className="h-3.5 w-3.5 text-emerald-500 shrink-0" />
                <span className="text-xs text-muted-foreground">Popular:</span>
                {POPULAR_SEARCHES.map((item) => {
                  const Icon = item.icon;
                  return (
                    <button
                      key={item.label}
                      onClick={() => handleSuggestionClick(item.label)}
                      className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-emerald-500/20 bg-emerald-500/5 hover:bg-emerald-500/15 hover:border-emerald-500/40 text-xs transition-all"
                    >
                      <Icon className="h-3 w-3 text-emerald-500" />
                      <span className="text-emerald-700 dark:text-emerald-300">{item.label}</span>
                    </button>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Filters & View Toggle */}
      <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
          {/* Filter Tabs - Custom styled with emerald underline */}
          <div className="relative">
            <div className="flex items-center gap-1 overflow-x-auto pb-1 scrollbar-none">
              {filterTabs.map((tab) => {
                const Icon = tab.icon;
                const isActive = activeFilter === tab.value;
                return (
                  <button
                    key={tab.value}
                    onClick={() => setActiveFilter(tab.value)}
                    className={`relative flex items-center gap-1.5 px-3 py-2 text-sm font-medium rounded-lg transition-all whitespace-nowrap ${
                      isActive
                        ? 'text-emerald-600 dark:text-emerald-400 bg-emerald-500/10'
                        : 'text-muted-foreground hover:text-foreground hover:bg-muted/50'
                    }`}
                  >
                    <Icon className="h-3.5 w-3.5" />
                    <span>{tab.label}</span>
                    {isActive && (
                      <motion.div
                        layoutId="activeFilterUnderline"
                        className="absolute bottom-0 left-2 right-2 h-0.5 bg-emerald-500 rounded-full"
                        transition={{ type: 'spring', stiffness: 300, damping: 30 }}
                      />
                    )}
                  </button>
                );
              })}
            </div>
          </div>

          {/* View Mode Toggle */}
          <div className="flex items-center gap-1 bg-muted rounded-lg p-1 shrink-0">
            <Button
              variant={viewMode === 'entity' ? 'default' : 'ghost'}
              size="sm"
              onClick={() => setViewMode('entity')}
              className={`h-8 gap-1.5 text-xs transition-all ${
                viewMode === 'entity'
                  ? 'bg-emerald-600 hover:bg-emerald-700 text-white shadow-md shadow-emerald-500/20'
                  : 'hover:bg-emerald-500/10'
              }`}
            >
              <LayoutGrid className="h-3.5 w-3.5" />
              Entity View
            </Button>
            <Button
              variant={viewMode === 'report' ? 'default' : 'ghost'}
              size="sm"
              onClick={() => setViewMode('report')}
              className={`h-8 gap-1.5 text-xs transition-all ${
                viewMode === 'report'
                  ? 'bg-emerald-600 hover:bg-emerald-700 text-white shadow-md shadow-emerald-500/20'
                  : 'hover:bg-emerald-500/10'
              }`}
            >
              <List className="h-3.5 w-3.5" />
              Report View
            </Button>
          </div>
        </div>

        {/* Results summary with animation */}
        <AnimatePresence>
          {searchQuery && !isLoading && (
            <motion.p
              initial={{ opacity: 0, y: -5 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -5 }}
              className="text-sm text-muted-foreground mt-3"
            >
              {viewMode === 'entity' ? (
                <>
                  Found{' '}
                  <motion.span
                    key={totalResults}
                    initial={{ scale: 1.2, color: 'rgb(16, 185, 129)' }}
                    animate={{ scale: 1, color: 'inherit' }}
                    transition={{ duration: 0.3 }}
                    className="font-semibold text-foreground"
                  >
                    {totalResults}
                  </motion.span>{' '}
                  {totalResults === 1 ? 'entity' : 'entities'} matching &quot;{searchQuery}&quot;
                </>
              ) : (
                <>
                  Showing reports matching &quot;{searchQuery}&quot; (Page {currentPage} of {totalPages})
                </>
              )}
            </motion.p>
          )}
        </AnimatePresence>
      </div>

      {/* Results Area */}
      <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 pb-16">
        <AnimatePresence mode="wait">
          {isLoading ? (
            <motion.div
              key="loading"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
            >
              {viewMode === 'entity' ? <SearchLoadingSkeleton /> : <ReportLoadingSkeleton />}
            </motion.div>
          ) : viewMode === 'entity' ? (
            entityResults.length > 0 ? (
              <motion.div
                key="entity-results"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ duration: 0.3 }}
                className="space-y-4"
              >
                {entityResults.map((entity, idx) => (
                  <motion.div
                    key={`${entity.entityType}:${entity.entityValue}`}
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.3, delay: idx * 0.05 }}
                  >
                    <EntityCard
                      entity={entity}
                      onReportClick={handleReportClick}
                      onEntitySearch={handleEntitySearch}
                      onQuickReport={handleQuickReport}
                    />
                  </motion.div>
                ))}
              </motion.div>
            ) : (
              <EmptyState key="empty-entity" query={searchQuery} viewMode="entity" onSuggestionClick={handleSuggestionClick} />
            )
          ) : reportResults.length > 0 ? (
            <motion.div
              key="report-results"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ duration: 0.3 }}
              className="space-y-3"
            >
              {reportResults.map((report, idx) => (
                <motion.div
                  key={report.id}
                  initial={{ opacity: 0, y: 16 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.3, delay: idx * 0.04 }}
                >
                  <ReportCard
                    report={report}
                    onReportClick={handleReportClick}
                  />
                </motion.div>
              ))}

              {/* Pagination */}
              {totalPages > 1 && (
                <Pagination
                  currentPage={currentPage}
                  totalPages={totalPages}
                  onPageChange={handlePageChange}
                />
              )}
            </motion.div>
          ) : (
            <EmptyState key="empty-report" query={searchQuery} viewMode="report" onSuggestionClick={handleSuggestionClick} />
          )}
        </AnimatePresence>
      </div>
    </div>
  );
}
