'use client'

import { useState, useMemo, useCallback } from 'react'
import { useCountries, useNetworkTopologies, useComplianceRequirements, useDeploymentMilestones, useCostEstimates } from '@/lib/hooks/useInfrastructureData'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Search, X } from 'lucide-react'
import { useRouter } from 'next/navigation'

interface SearchResult {
  type: 'country' | 'topology' | 'compliance' | 'milestone' | 'cost'
  id: string
  title: string
  description: string
  route: string
}

export function GlobalSearch({ open, onOpenChange }: { open: boolean; onOpenChange: (open: boolean) => void }) {
  const [query, setQuery] = useState('')
  const router = useRouter()

  const { countries } = useCountries()
  const { topologies } = useNetworkTopologies()
  const { requirements } = useComplianceRequirements()
  const { milestones } = useDeploymentMilestones()
  const { estimates } = useCostEstimates()

  const results = useMemo<SearchResult[]>(() => {
    if (!query.trim()) return []

    const lowerQuery = query.toLowerCase()
    const allResults: SearchResult[] = []

    // Search countries
    countries
      .filter((c) => c.name.toLowerCase().includes(lowerQuery) || c.region.toLowerCase().includes(lowerQuery))
      .forEach((country) => {
        allResults.push({
          type: 'country',
          id: country.name,
          title: country.name,
          description: `${country.region} • ${country.relationshipType}`,
          route: `/infrastructure/docs/compliance?country=${encodeURIComponent(country.name)}`,
        })
      })

    // Search topologies
    topologies
      .filter((t) => t.region.toLowerCase().includes(lowerQuery) || t.entity.toLowerCase().includes(lowerQuery))
      .forEach((topology) => {
        allResults.push({
          type: 'topology',
          id: topology.id || 'default',
          title: `${topology.region} - ${topology.entity}`,
          description: `${topology.nodes.length} nodes, ${topology.edges.length} edges`,
          route: `/infrastructure/docs/topology?region=${encodeURIComponent(topology.region)}&entity=${encodeURIComponent(topology.entity)}`,
        })
      })

    // Search compliance
    requirements
      .filter((r) => r.country.toLowerCase().includes(lowerQuery) || r.frameworks.some((f) => f.toLowerCase().includes(lowerQuery)))
      .forEach((req) => {
        allResults.push({
          type: 'compliance',
          id: req.country,
          title: req.country,
          description: `${req.status} • ${req.frameworks.join(', ')}`,
          route: `/infrastructure/docs/compliance?country=${encodeURIComponent(req.country)}`,
        })
      })

    // Search milestones
    milestones
      .filter((m) => m.title.toLowerCase().includes(lowerQuery) || m.region.toLowerCase().includes(lowerQuery))
      .forEach((milestone) => {
        allResults.push({
          type: 'milestone',
          id: milestone.id,
          title: milestone.title,
          description: `${milestone.status} • ${milestone.region}`,
          route: `/infrastructure/docs/timeline?milestone=${encodeURIComponent(milestone.id)}`,
        })
      })

    // Search cost estimates
    estimates
      .filter((e) => e.region.toLowerCase().includes(lowerQuery) || e.entity.toLowerCase().includes(lowerQuery))
      .forEach((estimate) => {
        allResults.push({
          type: 'cost',
          id: `${estimate.region}-${estimate.entity}-${estimate.category}`,
          title: `${estimate.region} - ${estimate.category}`,
          description: `$${(estimate.annual / 1000).toFixed(0)}K annually`,
          route: `/infrastructure/docs/costs?region=${encodeURIComponent(estimate.region)}&entity=${encodeURIComponent(estimate.entity)}`,
        })
      })

    return allResults.slice(0, 20) // Limit to 20 results
  }, [query, countries, topologies, requirements, milestones, estimates])

  const handleResultClick = useCallback((result: SearchResult) => {
    router.push(result.route)
    onOpenChange(false)
    setQuery('')
  }, [router, onOpenChange])

  const typeColors: Record<string, string> = {
    country: 'bg-blue-500/20 text-blue-400',
    topology: 'bg-green-500/20 text-green-400',
    compliance: 'bg-yellow-500/20 text-yellow-400',
    milestone: 'bg-purple-500/20 text-purple-400',
    cost: 'bg-orange-500/20 text-orange-400',
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>Global Search</DialogTitle>
        </DialogHeader>
        <div className="space-y-4">
          <div className="relative">
            <Search className="absolute left-3 top-3 h-4 w-4 text-studio-medium" />
            <Input
              placeholder="Search countries, topologies, compliance, milestones, costs..."
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              className="pl-10"
              autoFocus
            />
            {query && (
              <Button
                size="sm"
                variant="ghost"
                className="absolute right-2 top-1"
                onClick={() => setQuery('')}
              >
                <X className="h-4 w-4" />
              </Button>
            )}
          </div>

          {query && (
            <div className="max-h-96 overflow-y-auto space-y-1">
              {results.length === 0 ? (
                <div className="text-center py-8 text-studio-medium">
                  No results found for &quot;{query}&quot;
                </div>
              ) : (
                results.map((result) => (
                  <button
                    key={`${result.type}-${result.id}`}
                    onClick={() => handleResultClick(result)}
                    className="w-full text-left p-3 rounded-lg border border-studio-medium hover:border-studio-light hover:bg-studio-medium/20 transition-colors"
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          <Badge className={typeColors[result.type] || ''}>
                            {result.type}
                          </Badge>
                          <span className="font-semibold text-studio-light">{result.title}</span>
                        </div>
                        <p className="text-sm text-studio-medium">{result.description}</p>
                      </div>
                    </div>
                  </button>
                ))
              )}
            </div>
          )}

          {!query && (
            <div className="text-center py-8 text-studio-medium">
              Start typing to search across all infrastructure data...
            </div>
          )}
        </div>
      </DialogContent>
    </Dialog>
  )
}

