import React, { useState, useMemo } from 'react';
import { Map } from '../ui/map';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../ui/card';
import { Badge } from '../ui/badge';
import { Button } from '../ui/button';
import { Checkbox } from '../ui/checkbox';
import { Label } from '../ui/label';
import {
  Utensils,
  Hotel,
  MapPin,
  Landmark,
  ShoppingBag,
  Coffee,
  X,
  Filter,
  type LucideIcon,
} from 'lucide-react';
import { cn } from '../shared/utils';

/**
 * Exemplo avançado de mapa com marcadores personalizados e filtros por grupos
 * Demonstra como criar marcadores com cores e ícones distintos que podem ser filtrados
 * IMPORTANTE: Usa ícones Lucide com cores sólidas para contraste com fundos coloridos
 */

// Helper para criar SVG string de ícones Lucide manualmente
function createLucideIconSvg(iconName: string): string {
  // SVG paths para os ícones Lucide usados
  const iconPaths: Record<string, string> = {
    utensils:
      '<path d="M3 2v7c0 1.1.9 2 2 2h4a2 2 0 0 0 2-2V2"></path><path d="M7 2v20"></path><path d="M21 15V2v0a5 5 0 0 0-5 5v6c0 1.1.9 2 2 2h3Zm0 0v7"></path>',
    hotel:
      '<path d="M18 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2Z"></path><path d="M8 6h8"></path><path d="M8 10h8"></path><path d="M8 14h8"></path><path d="M8 18h8"></path>',
    landmark:
      '<path d="m3 21 18-18"></path><path d="M9 15V6h6v9"></path><path d="M12 3v3"></path><path d="M3 15h18"></path><path d="M6 21v-6"></path><path d="M18 21v-6"></path>',
    shopping:
      '<path d="M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4Z"></path><path d="M3 6h18"></path><path d="M16 10a4 4 0 0 1-8 0"></path>',
    coffee:
      '<path d="M17 8h1a4 4 0 1 1 0 8h-1"></path><path d="M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z"></path><line x1="6" x2="6" y1="2" y2="4"></line><line x1="10" x2="10" y1="2" y2="4"></line><line x1="14" x2="14" y1="2" y2="4"></line>',
  };

  const path = iconPaths[iconName] || '';
  return `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">${path}</svg>`;
}

// Definir tipos de grupos com cores e ícones Lucide
export const markerGroups = {
  restaurant: {
    id: 'restaurant',
    name: 'Restaurantes',
    color: 'var(--destructive)', // red
    iconColor: '#FFFFFF', // white para contraste
    iconName: 'utensils',
    icon: Utensils,
  },
  hotel: {
    id: 'hotel',
    name: 'Hotéis',
    color: 'var(--info)', // blue
    iconColor: '#FFFFFF',
    iconName: 'hotel',
    icon: Hotel,
  },
  landmark: {
    id: 'landmark',
    name: 'Pontos Turísticos',
    color: 'var(--success)', // green
    iconColor: '#FFFFFF',
    iconName: 'landmark',
    icon: Landmark,
  },
  shopping: {
    id: 'shopping',
    name: 'Compras',
    color: 'var(--warning)', // orange
    iconColor: '#FFFFFF',
    iconName: 'shopping',
    icon: ShoppingBag,
  },
  cafe: {
    id: 'cafe',
    name: 'Cafeterias',
    color: 'var(--primary)', // purple
    iconColor: '#FFFFFF',
    iconName: 'coffee',
    icon: Coffee,
  },
} as const;

export type MarkerGroupId = keyof typeof markerGroups;

// Dados de exemplo com diferentes grupos
const sampleLocations = [
  // Restaurantes
  {
    position: { lat: -23.5505, lng: -46.6333 },
    title: 'Restaurante Italiano',
    info: 'Melhor pizza da cidade',
    group: 'restaurant' as MarkerGroupId,
  },
  {
    position: { lat: -23.5485, lng: -46.635 },
    title: 'Sushi Bar',
    info: 'Comida japonesa autêntica',
    group: 'restaurant' as MarkerGroupId,
  },
  {
    position: { lat: -23.552, lng: -46.631 },
    title: 'Churrascaria Premium',
    info: 'Rodízio tradicional brasileiro',
    group: 'restaurant' as MarkerGroupId,
  },
  // Hotéis
  {
    position: { lat: -23.5475, lng: -46.6361 },
    title: 'Hotel Luxo',
    info: '5 estrelas - Vista panorâmica',
    group: 'hotel' as MarkerGroupId,
  },
  {
    position: { lat: -23.553, lng: -46.634 },
    title: 'Hotel Boutique',
    info: 'Design moderno e aconchegante',
    group: 'hotel' as MarkerGroupId,
  },
  // Pontos Turísticos
  {
    position: { lat: -23.5613, lng: -46.6563 },
    title: 'Parque Ibirapuera',
    info: 'Maior parque urbano da cidade',
    group: 'landmark' as MarkerGroupId,
  },
  {
    position: { lat: -23.5558, lng: -46.6396 },
    title: 'MASP',
    info: 'Museu de Arte de São Paulo',
    group: 'landmark' as MarkerGroupId,
  },
  {
    position: { lat: -23.5489, lng: -46.6388 },
    title: 'Avenida Paulista',
    info: 'Centro financeiro e cultural',
    group: 'landmark' as MarkerGroupId,
  },
  // Shopping
  {
    position: { lat: -23.5465, lng: -46.64 },
    title: 'Shopping Center',
    info: 'Mais de 300 lojas',
    group: 'shopping' as MarkerGroupId,
  },
  {
    position: { lat: -23.554, lng: -46.638 },
    title: 'Galeria de Arte',
    info: 'Arte contemporânea e design',
    group: 'shopping' as MarkerGroupId,
  },
  // Cafeterias
  {
    position: { lat: -23.5495, lng: -46.6345 },
    title: 'Café Artesanal',
    info: 'Café especial e brunch',
    group: 'cafe' as MarkerGroupId,
  },
  {
    position: { lat: -23.551, lng: -46.637 },
    title: 'Coffee House',
    info: 'Café gourmet e wi-fi',
    group: 'cafe' as MarkerGroupId,
  },
  {
    position: { lat: -23.5525, lng: -46.6355 },
    title: 'Café Cultural',
    info: 'Livros e café',
    group: 'cafe' as MarkerGroupId,
  },
];

/**
 * Componente de Mapa com Filtro de Grupos
 * Permite filtrar marcadores por categorias com interface integrada no mapa
 * COMPACTO: Usa checkboxes para economia de espaço
 */
export interface FilterableMapExampleProps {
  apiKey?: string;
}

export function FilterableMapExample({ apiKey }: FilterableMapExampleProps) {
  const [activeFilters, setActiveFilters] = useState<Set<MarkerGroupId>>(
    new Set(Object.keys(markerGroups) as MarkerGroupId[])
  );
  const [showFilters, setShowFilters] = useState(true);

  // Filtrar locais baseado nos filtros ativos
  const filteredLocations = useMemo(() => {
    return sampleLocations.filter(location => activeFilters.has(location.group));
  }, [activeFilters]);

  // Toggle de filtro individual
  const toggleFilter = (groupId: MarkerGroupId) => {
    setActiveFilters(prev => {
      const newFilters = new Set(prev);
      if (newFilters.has(groupId)) {
        newFilters.delete(groupId);
      } else {
        newFilters.add(groupId);
      }
      return newFilters;
    });
  };

  // Selecionar/Desselecionar todos
  const toggleAll = () => {
    if (activeFilters.size === Object.keys(markerGroups).length) {
      setActiveFilters(new Set());
    } else {
      setActiveFilters(new Set(Object.keys(markerGroups) as MarkerGroupId[]));
    }
  };

  // Preparar marcadores com cores personalizadas e ícones
  const markersWithCustomization = filteredLocations.map(location => ({
    ...location,
    customColor: markerGroups[location.group].color,
    iconSvg: createLucideIconSvg(markerGroups[location.group].iconName),
    iconColor: markerGroups[location.group].iconColor,
  }));

  // Contar marcadores por grupo
  const getGroupCount = (groupId: MarkerGroupId) => {
    return sampleLocations.filter(loc => loc.group === groupId).length;
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <MapPin className="w-5 h-5 text-primary" />
          <h3>Filtro por Categorias</h3>
        </div>
        <Badge variant="secondary">
          {filteredLocations.length} de {sampleLocations.length} locais
        </Badge>
      </div>

      <p className="text-muted-foreground">
        Use os filtros compactos no canto superior esquerdo do mapa para visualizar marcadores por
        categoria
      </p>

      {/* Container do Mapa com Filtros Integrados */}
      <div className="relative">
        <Map
          center={{ lat: -23.5505, lng: -46.6333 }}
          zoom={14}
          markers={markersWithCustomization}
          height="500px"
          zoomControl={true}
          fullscreenControl={true}
          apiKey={apiKey}
        />
        {/* Painel de Filtros COMPACTO Integrado no Mapa */}
        <div
          className={cn(
            'absolute top-4 left-4 z-10 transition-all duration-300',
            showFilters ? 'translate-x-0' : '-translate-x-full'
          )}
        >
          <div className="p-2.5 rounded-lg shadow-[var(--shadow-elevation-sm)] bg-card border border-border max-w-[220px]">
            <div className="flex items-center justify-between mb-2 gap-2">
              <div className="flex items-center gap-1.5">
                <Filter className="w-3.5 h-3.5 text-foreground" />
                <span className="text-sm text-foreground">Filtros</span>
              </div>
              <Button
                size="sm"
                variant="ghost"
                onClick={() => setShowFilters(false)}
                className="h-5 w-5 p-0"
              >
                <X className="w-3 h-3" />
              </Button>
            </div>

            <div className="space-y-1.5">
              {/* Checkbox Todos */}
              <div className="flex items-center space-x-2 py-0.5">
                <Checkbox
                  id="filter-all"
                  checked={activeFilters.size === Object.keys(markerGroups).length}
                  onCheckedChange={toggleAll}
                />
                <Label
                  htmlFor="filter-all"
                  className="flex items-center gap-1.5 cursor-pointer text-sm"
                >
                  <MapPin className="w-3.5 h-3.5" />
                  Todos
                  <Badge variant="secondary" className="text-xs h-4 px-1">
                    {sampleLocations.length}
                  </Badge>
                </Label>
              </div>

              {/* Checkboxes de Filtro por Grupo */}
              {Object.entries(markerGroups).map(([id, group]) => {
                const groupId = id as MarkerGroupId;
                const Icon = group.icon;
                const isActive = activeFilters.has(groupId);
                const count = getGroupCount(groupId);

                return (
                  <div key={id} className="flex items-center space-x-2 py-0.5">
                    <Checkbox
                      id={`filter-${id}`}
                      checked={isActive}
                      onCheckedChange={() => toggleFilter(groupId)}
                    />
                    <Label
                      htmlFor={`filter-${id}`}
                      className="flex items-center gap-1.5 cursor-pointer text-sm"
                    >
                      <Icon className="w-3.5 h-3.5" style={{ color: group.color }} />
                      <span className={isActive ? 'text-foreground' : 'text-muted-foreground'}>
                        {group.name}
                      </span>
                      <Badge variant="outline" className="text-xs h-4 px-1">
                        {count}
                      </Badge>
                    </Label>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        {/* Botão para mostrar filtros quando estão escondidos */}
        {!showFilters && (
          <Button
            size="sm"
            onClick={() => setShowFilters(true)}
            className="absolute top-4 left-4 z-10 h-8 bg-primary text-primary-foreground"
          >
            <Filter className="w-3.5 h-3.5 mr-1.5" />
            Filtros
          </Button>
        )}
      </div>

      {/* Legenda Horizontal */}
      <div className="flex flex-wrap gap-3 justify-center pt-2 border-t border-border">
        {Object.entries(markerGroups).map(([id, group]) => {
          const Icon = group.icon;
          const count = getGroupCount(id as MarkerGroupId);
          return (
            <div key={id} className="flex items-center gap-2 px-3 py-1 rounded-lg bg-muted">
              <div className="w-3 h-3 rounded-full" style={{ backgroundColor: group.color }} />
              <Icon className="w-4 h-4" style={{ color: group.color }} />
              <span className="text-sm" style={{ color: 'var(--foreground)' }}>
                {group.name}
              </span>
              <Badge variant="secondary" className="text-xs h-5">
                {count}
              </Badge>
            </div>
          );
        })}
      </div>

      {/* Estatísticas */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <div className="text-center p-3 rounded-lg bg-muted">
          <p className="text-muted-foreground">Total de Locais</p>
          <p className="text-2xl text-foreground">{sampleLocations.length}</p>
        </div>
        <div className="text-center p-3 rounded-lg bg-muted">
          <p className="text-muted-foreground">Visíveis</p>
          <p className="text-2xl text-primary">{filteredLocations.length}</p>
        </div>
        <div className="text-center p-3 rounded-lg bg-muted">
          <p className="text-muted-foreground">Categorias</p>
          <p className="text-2xl text-foreground">{Object.keys(markerGroups).length}</p>
        </div>
        <div className="text-center p-3 rounded-lg bg-muted">
          <p className="text-muted-foreground">Filtros Ativos</p>
          <p className="text-2xl text-chart-2">{activeFilters.size}</p>
        </div>
      </div>
    </div>
  );
}
