import React, { useState, useEffect, useMemo } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "./ui/dialog";
import { Input } from "./ui/input";
import { Badge } from "./ui/badge";
import { Search, FileText, Users, Building, Package, Calculator, ArrowRight } from "lucide-react";
import { useData } from "./contexts/DataContext";
import { cn } from "./ui/utils";

interface IntegratedSearchProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onNavigate: (page: string, id?: string) => void;
}

interface SearchResult {
  id: string;
  type: 'item' | 'quote' | 'site';
  title: string;
  subtitle: string;
  category?: string;
  page: string;
  icon: React.ReactNode;
}

export function IntegratedSearch({ open, onOpenChange, onNavigate }: IntegratedSearchProps) {
  const [searchQuery, setSearchQuery] = useState("");
  const { itemMasters, clients, suppliers, quotes, sites } = useData();

  // 메뉴 데이터
  const menuItems = [
    { id: 'dashboard', name: '대시보드', page: 'dashboard', category: '홈' },
    { id: 'item-management', name: '품목관리', page: 'item-management', category: '기준정보' },
    { id: 'customer-management', name: '고객사관리', page: 'customer-management', category: '기준정보' },
    { id: 'supplier-management', name: '공급업체관리', page: 'supplier-management', category: '구매' },
    { id: 'quote-management', name: '견적관리', page: 'quote-management', category: '영업' },
    { id: 'sales-order-management', name: '수주관리', page: 'sales-order-management', category: '영업' },
    { id: 'production-management', name: '생산관리', page: 'production-management', category: '생산' },
    { id: 'quality-management', name: '품질관리', page: 'quality-management', category: '품질' },
    { id: 'inventory-management', name: '재고관리', page: 'inventory-management', category: '재고' },
    { id: 'bom-management', name: 'BOM관리', page: 'bom-management', category: '기준정보' },
    { id: 'pricing-management', name: '단가관리', page: 'pricing-management', category: '기준정보' },
    { id: 'formula-management', name: '공식관리', page: 'formula-management', category: '기준정보' },
  ];

  // 통합 검색 결과
  const searchResults = useMemo(() => {
    if (!searchQuery.trim()) return [];

    const query = searchQuery.toLowerCase();
    const results: SearchResult[] = [];

    // 제품명 검색 (SEARCHABLE_FIELDS.item)
    itemMasters.forEach(item => {
      if (item.itemName?.toLowerCase().includes(query)) {
        results.push({
          id: item.id,
          type: 'item',
          title: item.itemName || '',
          subtitle: `제품코드: ${item.itemCode || ''} | ${item.itemCategory || ''}`,
          category: item.itemCategory,
          page: 'item-management',
          icon: <Package className="h-4 w-4" />
        });
      }
    });

    // 견적 검색 (SEARCHABLE_FIELDS.quote: 견적번호, 발주처, 담당자)
    if (quotes) {
      quotes.forEach(quote => {
        const matchesQuoteNumber = quote.quoteNumber?.toLowerCase().includes(query); // 견적번호
        const matchesClient = quote.clientName?.toLowerCase().includes(query); // 발주처
        const matchesManager = quote.managerName?.toLowerCase().includes(query); // 담당자
        
        if (matchesQuoteNumber || matchesClient || matchesManager) {
          results.push({
            id: quote.id,
            type: 'quote',
            title: quote.quoteNumber || '',
            subtitle: `발주처: ${quote.clientName || ''} | 담당자: ${quote.managerName || ''}`,
            page: 'quote-management',
            icon: <Calculator className="h-4 w-4" />
          });
        }
      });
    }

    // 현장 검색 (SEARCHABLE_FIELDS.site: 현장코드, 현장명)
    if (sites) {
      sites.forEach(site => {
        const matchesSiteCode = site.code?.toLowerCase().includes(query); // 현장코드
        const matchesSiteName = site.name?.toLowerCase().includes(query); // 현장명
        
        if (matchesSiteCode || matchesSiteName) {
          results.push({
            id: site.id,
            type: 'site',
            title: site.name || '',
            subtitle: `현장코드: ${site.code || ''} | ${site.category || ''}`,
            category: site.category,
            page: 'site-management',
            icon: <Building className="h-4 w-4" />
          });
        }
      });
    }

    // 상위 20개만 반환
    return results.slice(0, 20);
  }, [searchQuery, itemMasters, quotes, sites]);

  // 다이얼로그 열릴 때 검색어 초기화
  useEffect(() => {
    if (open) {
      setSearchQuery("");
    }
  }, [open]);

  // 검색 결과 클릭 핸들러
  const handleResultClick = (result: SearchResult) => {
    onNavigate(result.page, result.id);
    onOpenChange(false);
    setSearchQuery("");
  };

  // 타입별 배지 색상
  const getTypeBadgeColor = (type: string) => {
    switch (type) {
      case 'item':
        return 'bg-blue-100 text-blue-800';
      case 'quote':
        return 'bg-orange-100 text-orange-800';
      case 'site':
        return 'bg-green-100 text-green-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  // 타입별 한글 이름
  const getTypeLabel = (type: string) => {
    switch (type) {
      case 'item':
        return '제품명';
      case 'quote':
        return '견적';
      case 'site':
        return '현장';
      default:
        return type;
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[600px] p-0">
        <DialogHeader className="px-6 pt-6 pb-4">
          <DialogTitle>통합검색</DialogTitle>
        </DialogHeader>

        {/* 검색 입력 */}
        <div className="px-6 pb-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input
              autoFocus
              placeholder="견적번호/발주처/담당자/제품명/현장코드/현장명 검색"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-10 h-12"
            />
          </div>
        </div>

        {/* 검색 결과 */}
        <div className="overflow-y-auto max-h-[400px] px-2">
          {searchQuery.trim() === "" ? (
            <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
              <Search className="h-12 w-12 mb-4 opacity-20" />
              <p>검색어를 입력하세요</p>
              <p className="text-sm mt-2">견적번호, 발주처, 담당자, 제품명, 현장코드, 현장명을 검색할 수 있습니다</p>
            </div>
          ) : searchResults.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
              <Search className="h-12 w-12 mb-4 opacity-20" />
              <p>검색 결과가 없습니다</p>
              <p className="text-sm mt-2">다른 검색어를 입력해보세요</p>
            </div>
          ) : (
            <div className="space-y-1 pb-4">
              {searchResults.map((result) => (
                <button
                  key={`${result.type}-${result.id}`}
                  onClick={() => handleResultClick(result)}
                  className="w-full text-left px-4 py-3 rounded-lg hover:bg-accent transition-colors group"
                >
                  <div className="flex items-start gap-3">
                    <div className="mt-1 text-muted-foreground">
                      {result.icon}
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1">
                        <Badge className={cn("text-xs", getTypeBadgeColor(result.type))}>
                          {getTypeLabel(result.type)}
                        </Badge>
                        <span className="font-medium truncate">{result.title}</span>
                      </div>
                      <p className="text-sm text-muted-foreground truncate">
                        {result.subtitle}
                      </p>
                    </div>
                    <ArrowRight className="h-4 w-4 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity mt-1" />
                  </div>
                </button>
              ))}
            </div>
          )}
        </div>

        {/* 하단 안내 */}
        {searchResults.length > 0 && (
          <div className="px-6 py-3 bg-muted/30 border-t">
            <p className="text-xs text-muted-foreground">
              {searchResults.length}개의 결과 · 항목을 클릭하여 이동하세요
            </p>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}