import React, { useState } from 'react';
import { Map } from '../ui/map';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Badge } from '../ui/badge';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Alert, AlertDescription } from '../ui/alert';
import { Info, Layers, MapPin, MousePointer2, Pencil } from 'lucide-react';
import { Checkbox } from '../ui/checkbox';
import { Label } from '../ui/label';
import { Switch } from '../ui/switch';
import { FilterableMapExample } from './FilterableMapExample';
import { SimpleFilterableMap } from './SimpleFilterableMap';
import { DrawingMapExample } from './DrawingMapExample';
import { PageHeader } from '../ui/page-header';

/**
 * MapShowcase - Componente de demonstração completo e organizado
 *
 * Organizado em 3 abas principais conforme diretrizes do Design System:
 * 1. Mapas Simples (Padrão, Layers, Compacto)
 * 2. Marcadores (Pins, Áreas, Personalização)
 * 3. Controles (Filtros, Controles Nativos)
 */

export function MapShowcase() {
  const [activeTab, setActiveTab] = useState('simple');
  const [isTransitioning, setIsTransitioning] = useState(false);
  const [apiKey, setApiKey] = useState('');
  const [inputApiKey, setInputApiKey] = useState('');

  // Estados para Layers
  const [showTraffic, setShowTraffic] = useState(false);
  const [showTransit, setShowTransit] = useState(false);
  const [showBicycling, setShowBicycling] = useState(false);

  // Estados para Controles Nativos
  const [showZoomControl, setShowZoomControl] = useState(true);
  const [showMapTypeControl, setShowMapTypeControl] = useState(false);
  const [showStreetViewControl, setShowStreetViewControl] = useState(false);
  const [showFullscreenControl, setShowFullscreenControl] = useState(true);

  // Handler para troca de tabs com cleanup
  const handleTabChange = (value: string) => {
    if (value === activeTab) return;
    setIsTransitioning(true);
    setTimeout(() => {
      setActiveTab(value);
      setIsTransitioning(false);
    }, 50);
  };

  return (
    <div className="space-y-8">
      {/* Header */}
      {/* Header */}
      <PageHeader
        title="Mapas"
        subtitle="Biblioteca de componentes de mapa para visualização de dados geoespaciais. Utiliza a API do Google Maps com estilização personalizada do Xertica UI."
        actions={<Badge>Design System</Badge>}
      />

      {/* API Key Configuration */}
      <Card>
        <CardHeader>
          <CardTitle>Configuração da API Key</CardTitle>
          <CardDescription>
            Insira sua Google Maps API Key para renderizar os mapas abaixo.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex w-full max-w-md items-center space-x-2">
            <Input
              type="password"
              placeholder="Cole sua Google Maps API Key aqui"
              aria-label="Google Maps API Key"
              value={inputApiKey}
              onChange={e => setInputApiKey(e.target.value)}
              className="max-w-md h-10"
            />
            <Button onClick={() => setApiKey(inputApiKey)}>Salvar</Button>
          </div>
        </CardContent>
      </Card>

      {/* Tabs Principais */}
      <Tabs value={activeTab} onValueChange={handleTabChange} className="w-full">
        <TabsList className="grid w-full grid-cols-4 mb-8">
          <TabsTrigger value="simple">Mapas Simples</TabsTrigger>
          <TabsTrigger value="markers">Marcadores</TabsTrigger>
          <TabsTrigger value="controls">Controles</TabsTrigger>
          <TabsTrigger value="drawing" className="flex items-center gap-2">
            <Pencil className="w-3 h-3" /> Desenho
          </TabsTrigger>
        </TabsList>

        {/* 1. Mapas Simples */}
        <TabsContent value="simple" className="space-y-8">
          {!isTransitioning && activeTab === 'simple' && (
            <>
              {/* Mapa Padrão */}
              <Card>
                <CardHeader>
                  <CardTitle>Mapa Padrão</CardTitle>
                  <CardDescription>
                    Configuração básica do mapa centralizado em uma coordenada específica.
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <Map
                    center={{ lat: -23.5505, lng: -46.6333 }}
                    zoom={13}
                    height="400px"
                    apiKey={apiKey}
                  />
                </CardContent>
              </Card>

              {/* Mapa com Layers */}
              <Card>
                <CardHeader>
                  <CardTitle>Camadas (Layers)</CardTitle>
                  <CardDescription>
                    Sobreposição de informações como tráfego, transporte público e ciclovias.
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex flex-wrap gap-6 p-4 border rounded-lg bg-muted/50">
                    <div className="flex items-center space-x-2">
                      <Switch id="traffic" checked={showTraffic} onCheckedChange={setShowTraffic} />
                      <Label htmlFor="traffic" className="flex items-center gap-2">
                        <Layers className="w-4 h-4" /> Trânsito
                      </Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <Switch id="transit" checked={showTransit} onCheckedChange={setShowTransit} />
                      <Label htmlFor="transit" className="flex items-center gap-2">
                        <Layers className="w-4 h-4" /> Transporte
                      </Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <Switch
                        id="bicycling"
                        checked={showBicycling}
                        onCheckedChange={setShowBicycling}
                      />
                      <Label htmlFor="bicycling" className="flex items-center gap-2">
                        <Layers className="w-4 h-4" /> Ciclovias
                      </Label>
                    </div>
                  </div>

                  <Map
                    center={{ lat: -23.5505, lng: -46.6333 }}
                    zoom={12}
                    height="500px"
                    layers={{
                      traffic: showTraffic,
                      transit: showTransit,
                      bicycling: showBicycling,
                    }}
                    apiKey={apiKey}
                  />
                </CardContent>
              </Card>

              {/* Mapas Compactos */}
              <div className="grid md:grid-cols-3 gap-4">
                <Card>
                  <CardHeader className="p-4 pb-2">
                    <CardTitle className="text-sm">São Paulo</CardTitle>
                  </CardHeader>
                  <CardContent className="p-4 pt-0">
                    <Map
                      center={{ lat: -23.5505, lng: -46.6333 }}
                      zoom={11}
                      height="200px"
                      disableDefaultUI={true}
                      apiKey={apiKey}
                    />
                  </CardContent>
                </Card>
                <Card>
                  <CardHeader className="p-4 pb-2">
                    <CardTitle className="text-sm">Rio de Janeiro</CardTitle>
                  </CardHeader>
                  <CardContent className="p-4 pt-0">
                    <Map
                      center={{ lat: -22.9068, lng: -43.1729 }}
                      zoom={11}
                      height="200px"
                      disableDefaultUI={true}
                      apiKey={apiKey}
                    />
                  </CardContent>
                </Card>
                <Card>
                  <CardHeader className="p-4 pb-2">
                    <CardTitle className="text-sm">New York</CardTitle>
                  </CardHeader>
                  <CardContent className="p-4 pt-0">
                    <Map
                      center={{ lat: 40.7128, lng: -74.006 }}
                      zoom={11}
                      height="200px"
                      disableDefaultUI={true}
                      apiKey={apiKey}
                    />
                  </CardContent>
                </Card>
              </div>
            </>
          )}
        </TabsContent>

        {/* 2. Marcadores */}
        <TabsContent value="markers" className="space-y-8">
          {!isTransitioning && activeTab === 'markers' && (
            <>
              {/* Marcadores e Pins */}
              <Card>
                <CardHeader>
                  <CardTitle>Marcadores e Pins</CardTitle>
                  <CardDescription>
                    Exemplos de marcadores personalizados com diferentes cores e informações.
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <Map
                    center={{ lat: -23.5505, lng: -46.6333 }}
                    zoom={13}
                    height="500px"
                    apiKey={apiKey}
                    markers={[
                      {
                        position: { lat: -23.5505, lng: -46.6333 },
                        title: 'Principal',
                        info: 'Marcador padrão',
                        customColor: '#4F46E5',
                      },
                      {
                        position: { lat: -23.54, lng: -46.64 },
                        title: 'Secundário',
                        info: 'Marcador de alerta',
                        customColor: '#EF4444',
                        icon: '!',
                      },
                      {
                        position: { lat: -23.56, lng: -46.62 },
                        title: 'Loja',
                        info: 'Ponto de venda',
                        customColor: '#10B981',
                        icon: 'S',
                      },
                    ]}
                  />
                </CardContent>
              </Card>

              {/* Marcador com Conteúdo Rico */}
              <Card>
                <CardHeader>
                  <CardTitle>Marcador com Ações</CardTitle>
                  <CardDescription>
                    Marcador interativo que exibe conteúdo rico (texto, imagem, botões) ao ser
                    clicado.
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <Map
                    center={{ lat: -23.5505, lng: -46.6333 }}
                    zoom={13}
                    height="500px"
                    apiKey={apiKey}
                    markers={[
                      {
                        position: { lat: -23.5505, lng: -46.6333 },
                        label: '🏢',
                        richContent: (
                          <div className="p-4 max-w-[260px]">
                            <div className="flex items-center justify-between mb-2">
                              <h4 className="font-semibold text-base">Xertica HQ</h4>
                              <Badge variant="outline" className="text-[10px] h-5">
                                Open
                              </Badge>
                            </div>
                            <div className="w-full h-32 bg-muted rounded-md mb-3 overflow-hidden relative">
                              <div className="absolute inset-0 bg-[image:var(--gradient-diagonal)] opacity-80" />
                              <div className="absolute inset-0 flex items-center justify-center text-white font-medium">
                                Office View
                              </div>
                            </div>
                            <p className="text-sm text-muted-foreground mb-3 leading-relaxed">
                              Sede principal em São Paulo. Espaço moderno para reuniões e eventos.
                            </p>
                            <div className="grid grid-cols-2 gap-2">
                              <Button size="sm" className="w-full h-8 text-xs shadow-sm">
                                Navegar
                              </Button>
                              <Button
                                size="sm"
                                variant="outline"
                                className="w-full h-8 text-xs bg-background"
                              >
                                Detalhes
                              </Button>
                            </div>
                          </div>
                        ),
                      },
                    ]}
                  />
                </CardContent>
              </Card>

              {/* Áreas e Polígonos */}
              <Card>
                <CardHeader>
                  <CardTitle>Áreas e Zonas</CardTitle>
                  <CardDescription>
                    Delimitação de áreas geográficas usando círculos e polígonos.
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <Map
                    center={{ lat: -23.5505, lng: -46.6333 }}
                    zoom={12}
                    height="500px"
                    apiKey={apiKey}
                    markers={[
                      {
                        position: { lat: -23.5505, lng: -46.6333 },
                        title: 'Centro da Zona',
                        info: 'Raio de 3km',
                        customColor: '#6366F1',
                      },
                    ]}
                    circle={{
                      center: { lat: -23.5505, lng: -46.6333 },
                      radius: 3000,
                      fillColor: '#6366F1',
                      strokeColor: '#4F46E5',
                    }}
                    polygon={{
                      paths: [
                        [
                          { lat: -23.52, lng: -46.6 },
                          { lat: -23.52, lng: -46.66 },
                          { lat: -23.58, lng: -46.66 },
                          { lat: -23.58, lng: -46.6 },
                        ],
                      ],
                      fillColor: '#10B981',
                      strokeColor: '#059669',
                    }}
                  />
                </CardContent>
              </Card>
            </>
          )}
        </TabsContent>

        {/* 3. Controles */}
        <TabsContent value="controls" className="space-y-8">
          {!isTransitioning && activeTab === 'controls' && (
            <>
              {/* Controles Nativos */}
              <Card>
                <CardHeader>
                  <CardTitle>Controles do Mapa</CardTitle>
                  <CardDescription>
                    Personalize a interface do mapa ativando ou desativando controles nativos.
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4 p-4 border rounded-lg bg-muted/50">
                    <div className="flex items-center space-x-2">
                      <Checkbox
                        id="zoom"
                        checked={showZoomControl}
                        onCheckedChange={c => setShowZoomControl(!!c)}
                      />
                      <Label htmlFor="zoom">Zoom Control</Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <Checkbox
                        id="maptype"
                        checked={showMapTypeControl}
                        onCheckedChange={c => setShowMapTypeControl(!!c)}
                      />
                      <Label htmlFor="maptype">Map Type</Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <Checkbox
                        id="streetview"
                        checked={showStreetViewControl}
                        onCheckedChange={c => setShowStreetViewControl(!!c)}
                      />
                      <Label htmlFor="streetview">Street View</Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <Checkbox
                        id="fullscreen"
                        checked={showFullscreenControl}
                        onCheckedChange={c => setShowFullscreenControl(!!c)}
                      />
                      <Label htmlFor="fullscreen">Fullscreen</Label>
                    </div>
                  </div>

                  <Map
                    center={{ lat: -23.5505, lng: -46.6333 }}
                    zoom={13}
                    height="400px"
                    apiKey={apiKey}
                    zoomControl={showZoomControl}
                    mapTypeControl={showMapTypeControl}
                    streetViewControl={showStreetViewControl}
                    fullscreenControl={showFullscreenControl}
                  />
                </CardContent>
              </Card>

              {/* Filtros Customizados */}
              <Card>
                <CardHeader>
                  <CardTitle>Filtros Interativos</CardTitle>
                  <CardDescription>
                    Exemplo avançado de mapa com controles customizados para filtragem de
                    marcadores.
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <FilterableMapExample apiKey={apiKey} />
                </CardContent>
              </Card>
            </>
          )}
        </TabsContent>

        {/* 4. Desenho */}
        <TabsContent value="drawing" className="space-y-8">
          {!isTransitioning && activeTab === 'drawing' && <DrawingMapExample apiKey={apiKey} />}
        </TabsContent>
      </Tabs>

      {/* Footer Info */}
      <div className="grid md:grid-cols-3 gap-6 pt-8 border-t">
        <div className="space-y-2">
          <h4 className="font-semibold text-sm">Documentação</h4>
          <p className="text-xs text-muted-foreground">
            Verifique <code>MAP_SETUP.md</code> para configuração inicial e requisitos de API.
          </p>
        </div>
        <div className="space-y-2">
          <h4 className="font-semibold text-sm">Performance</h4>
          <p className="text-xs text-muted-foreground">
            Utiliza carregamento assíncrono e AdvancedMarkerElement para melhor desempenho.
          </p>
        </div>
        <div className="space-y-2">
          <h4 className="font-semibold text-sm">Design System</h4>
          <p className="text-xs text-muted-foreground">
            Componentes seguem estritamente as variáveis de tokens do <code>globals.css</code>.
          </p>
        </div>
      </div>
    </div>
  );
}
