import React, { useState } from 'react';
import { Map } from '../ui/map';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { MapPin, Store, Home, Building2, Navigation } from 'lucide-react';

/**
 * LocationPickerExample
 *
 * Exemplo avançado que demonstra:
 * - Seleção de localização em um mapa
 * - Múltiplas categorias de locais
 * - Estado interativo
 * - Integração com outros componentes UI
 */

interface Location {
  id: string;
  name: string;
  address: string;
  category: 'store' | 'office' | 'home';
  coords: { lat: number; lng: number };
  description: string;
  isOpen?: boolean;
  phone?: string;
}

const mockLocations: Location[] = [
  {
    id: '1',
    name: 'Loja Centro',
    address: 'Av. Paulista, 1000 - Bela Vista, São Paulo',
    category: 'store',
    coords: { lat: -23.5505, lng: -46.6333 },
    description: 'Nossa loja principal no centro da cidade',
    isOpen: true,
    phone: '(11) 3456-7890',
  },
  {
    id: '2',
    name: 'Loja Shopping',
    address: 'Shopping Ibirapuera - Vila Clementino, São Paulo',
    category: 'store',
    coords: { lat: -23.5965, lng: -46.652 },
    description: 'Loja no Shopping Ibirapuera',
    isOpen: true,
    phone: '(11) 3456-7891',
  },
  {
    id: '3',
    name: 'Escritório Administrativo',
    address: 'Rua Augusta, 2000 - Consolação, São Paulo',
    category: 'office',
    coords: { lat: -23.5558, lng: -46.66 },
    description: 'Sede administrativa da empresa',
    isOpen: false,
    phone: '(11) 3456-7892',
  },
  {
    id: '4',
    name: 'Centro de Distribuição',
    address: 'Rodovia dos Bandeirantes, km 24',
    category: 'office',
    coords: { lat: -23.485, lng: -46.685 },
    description: 'Centro de logística e distribuição',
    isOpen: true,
    phone: '(11) 3456-7893',
  },
];

export function LocationPickerExample() {
  const [selectedLocation, setSelectedLocation] = useState<Location | null>(mockLocations[0]);
  const [activeCategory, setActiveCategory] = useState<string>('all');

  // Filtrar localizações por categoria
  const filteredLocations =
    activeCategory === 'all'
      ? mockLocations
      : mockLocations.filter(loc => loc.category === activeCategory);

  // Criar marcadores para o mapa
  const markers = filteredLocations.map(loc => ({
    position: loc.coords,
    title: loc.name,
    info: loc.address,
    label: loc.category === 'store' ? '🏪' : loc.category === 'office' ? '🏢' : '🏠',
  }));

  // Calcular centro do mapa baseado nos locais filtrados
  const mapCenter = selectedLocation?.coords || { lat: -23.5505, lng: -46.6333 };

  const getCategoryIcon = (category: string) => {
    switch (category) {
      case 'store':
        return <Store className="w-4 h-4" />;
      case 'office':
        return <Building2 className="w-4 h-4" />;
      case 'home':
        return <Home className="w-4 h-4" />;
      default:
        return <MapPin className="w-4 h-4" />;
    }
  };

  const getCategoryLabel = (category: string) => {
    switch (category) {
      case 'store':
        return 'Loja';
      case 'office':
        return 'Escritório';
      case 'home':
        return 'Residência';
      default:
        return 'Local';
    }
  };

  return (
    <div className="space-y-6 max-w-6xl mx-auto">
      <div className="space-y-2">
        <h2 className="text-2xl">Encontre uma Localização</h2>
        <p className="text-muted-foreground">
          Selecione um local para ver mais informações e como chegar
        </p>
      </div>

      <Tabs defaultValue="all" onValueChange={setActiveCategory}>
        <TabsList className="w-full grid grid-cols-4">
          <TabsTrigger value="all">
            <MapPin className="w-4 h-4 mr-2" />
            Todos ({mockLocations.length})
          </TabsTrigger>
          <TabsTrigger value="store">
            <Store className="w-4 h-4 mr-2" />
            Lojas ({mockLocations.filter(l => l.category === 'store').length})
          </TabsTrigger>
          <TabsTrigger value="office">
            <Building2 className="w-4 h-4 mr-2" />
            Escritórios ({mockLocations.filter(l => l.category === 'office').length})
          </TabsTrigger>
          <TabsTrigger value="home">
            <Home className="w-4 h-4 mr-2" />
            Outros ({mockLocations.filter(l => l.category === 'home').length})
          </TabsTrigger>
        </TabsList>

        <TabsContent value={activeCategory} className="mt-6">
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            {/* Lista de Locais */}
            <div className="lg:col-span-1 space-y-3">
              <h3 className="text-sm font-medium text-muted-foreground">
                {filteredLocations.length} {filteredLocations.length === 1 ? 'local' : 'locais'}{' '}
                encontrado{filteredLocations.length !== 1 ? 's' : ''}
              </h3>

              <div className="space-y-2 max-h-[600px] overflow-y-auto pr-2">
                {filteredLocations.map(location => (
                  <Card
                    key={location.id}
                    className={`cursor-pointer transition-all hover:shadow-md ${
                      selectedLocation?.id === location.id ? 'ring-2 ring-primary bg-primary/5' : ''
                    }`}
                    onClick={() => setSelectedLocation(location)}
                  >
                    <CardHeader className="p-4">
                      <div className="flex items-start justify-between gap-2">
                        <div className="flex-1">
                          <CardTitle className="text-base flex items-center gap-2">
                            {getCategoryIcon(location.category)}
                            {location.name}
                          </CardTitle>
                          <CardDescription className="text-xs mt-1">
                            {location.address}
                          </CardDescription>
                        </div>
                        {location.isOpen !== undefined && (
                          <Badge
                            variant={location.isOpen ? 'success' : 'secondary'}
                            className="text-xs"
                          >
                            {location.isOpen ? 'Aberto' : 'Fechado'}
                          </Badge>
                        )}
                      </div>
                    </CardHeader>
                  </Card>
                ))}
              </div>
            </div>

            {/* Mapa e Detalhes */}
            <div className="lg:col-span-2 space-y-4">
              {/* Mapa */}
              <Card>
                <CardContent className="p-4">
                  <Map
                    center={mapCenter}
                    zoom={selectedLocation ? 15 : 12}
                    markers={markers}
                    height="400px"
                    zoomControl={true}
                    fullscreenControl={true}
                  />
                </CardContent>
              </Card>

              {/* Informações do Local Selecionado */}
              {selectedLocation && (
                <Card>
                  <CardHeader>
                    <div className="flex items-start justify-between">
                      <div className="space-y-1">
                        <div className="flex items-center gap-2">
                          {getCategoryIcon(selectedLocation.category)}
                          <CardTitle>{selectedLocation.name}</CardTitle>
                        </div>
                        <CardDescription>
                          {getCategoryLabel(selectedLocation.category)}
                        </CardDescription>
                      </div>
                      {selectedLocation.isOpen !== undefined && (
                        <Badge variant={selectedLocation.isOpen ? 'success' : 'secondary'}>
                          {selectedLocation.isOpen ? 'Aberto agora' : 'Fechado'}
                        </Badge>
                      )}
                    </div>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div className="space-y-2">
                      <div className="flex items-start gap-2 text-sm">
                        <MapPin className="w-4 h-4 text-muted-foreground mt-0.5 shrink-0" />
                        <span>{selectedLocation.address}</span>
                      </div>
                      {selectedLocation.phone && (
                        <div className="flex items-center gap-2 text-sm">
                          <span className="text-muted-foreground">📞</span>
                          <span>{selectedLocation.phone}</span>
                        </div>
                      )}
                    </div>

                    <p className="text-sm text-muted-foreground">{selectedLocation.description}</p>
                  </CardContent>
                  <CardFooter className="flex gap-2">
                    <Button className="flex-1">
                      <Navigation className="w-4 h-4 mr-2" />
                      Como Chegar
                    </Button>
                    <Button variant="outline" className="flex-1">
                      Mais Informações
                    </Button>
                  </CardFooter>
                </Card>
              )}
            </div>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}

/**
 * VARIAÇÃO: Seletor de Endereço de Entrega
 */
export function DeliveryAddressSelector() {
  const [selectedAddress, setSelectedAddress] = useState<string | null>(null);

  const addresses = [
    {
      id: '1',
      label: 'Casa',
      address: 'Rua das Flores, 123',
      coords: { lat: -23.5505, lng: -46.6333 },
    },
    {
      id: '2',
      label: 'Trabalho',
      address: 'Av. Paulista, 1000',
      coords: { lat: -23.5615, lng: -46.656 },
    },
    {
      id: '3',
      label: 'Outro',
      address: 'Rua Augusta, 2000',
      coords: { lat: -23.5558, lng: -46.66 },
    },
  ];

  const selectedCoords =
    addresses.find(a => a.id === selectedAddress)?.coords || addresses[0].coords;

  return (
    <Card className="max-w-2xl">
      <CardHeader>
        <CardTitle>Selecione o Endereço de Entrega</CardTitle>
        <CardDescription>Escolha onde deseja receber seu pedido</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="space-y-2">
          {addresses.map(addr => (
            <button
              key={addr.id}
              onClick={() => setSelectedAddress(addr.id)}
              className={`w-full p-4 rounded-lg border-2 text-left transition-all ${
                selectedAddress === addr.id
                  ? 'border-primary bg-primary/5'
                  : 'border-border hover:border-primary/50'
              }`}
            >
              <div className="flex items-start gap-3">
                <Home className="w-5 h-5 text-muted-foreground mt-0.5" />
                <div className="flex-1">
                  <p className="font-medium">{addr.label}</p>
                  <p className="text-sm text-muted-foreground">{addr.address}</p>
                </div>
                {selectedAddress === addr.id && (
                  <div className="w-5 h-5 rounded-full bg-primary flex items-center justify-center">
                    <span className="text-xs text-primary-foreground">✓</span>
                  </div>
                )}
              </div>
            </button>
          ))}
        </div>

        <Map
          center={selectedCoords}
          zoom={15}
          markers={[
            {
              position: selectedCoords,
              title: 'Endereço de Entrega',
            },
          ]}
          height="300px"
        />
      </CardContent>
      <CardFooter>
        <Button className="w-full" disabled={!selectedAddress}>
          Confirmar Endereço
        </Button>
      </CardFooter>
    </Card>
  );
}
