import { useState, useEffect, useMemo } from 'react';
import { MapContainer, TileLayer, Marker, Popup, Tooltip } from 'react-leaflet';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { FiX, FiSearch } from 'react-icons/fi';
import { type Language, t } from '../translations';
import { slugify } from '../utils/slugify';
import { useNavigate } from 'react-router-dom';
import { Helmet } from 'react-helmet-async';

interface LakeData {
  id: string;
  name: string;
  river: string;
  priority: boolean;
  level: string;
  capacity: number;
  inflow: string;
  outflow: string;
  volume: string;
  lat: number;
  lng: number;
  type?: 'lake' | 'river';
}

interface Props {
  language: Language;
}

// Create custom icon
const createCustomIcon = (type?: 'lake' | 'river') => {
  if (type === 'river') {
    return L.divIcon({
      className: 'custom-div-icon',
      html: `
        <div class="river-marker-icon">
          <svg stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" height="20" width="20" xmlns="http://www.w3.org/2000/svg">
            <path d="M3 12h18M3 8h18M3 16h18" stroke-linecap="round" stroke-linejoin="round" />
          </svg>
        </div>
      `,
      iconSize: [36, 42],
      iconAnchor: [18, 42],
      popupAnchor: [0, -42],
    });
  }

  return L.divIcon({
    className: 'custom-div-icon',
    html: `
      <div class="map-marker-icon">
        <svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 24 24" height="18" width="18" xmlns="http://www.w3.org/2000/svg"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"></path><path d="M12 6c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm0 10c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4z"></path></svg>
      </div>
    `,
    iconSize: [36, 42],
    iconAnchor: [18, 42],
    popupAnchor: [0, -42],
  });
};

const LakeMap = ({ language }: Props) => {
  const [lakes, setLakes] = useState<LakeData[]>([]);
  const navigate = useNavigate();
  const [searchTerm, setSearchTerm] = useState('');
  const [isPanelVisible, setIsPanelVisible] = useState(true);

  useEffect(() => {
    fetch('/data/lakes_index.json')
      .then(res => res.json())
      .then(data => setLakes(data))
      .catch(err => console.error('Error fetching map lakes:', err));
  }, []);

  const randomStats = useMemo(() => {
    const stats: Record<string, { area: string; depth: string }> = {};
    const simpleHash = (str: string) => {
      let hash = 0;
      for (let i = 0; i < str.length; i++) {
        hash = (hash << 5) - hash + str.charCodeAt(i);
        hash = hash & hash;
      }
      return Math.abs(hash);
    };

    lakes.forEach(l => {
      const hash = simpleHash(l.id);
      stats[l.id] = {
        area: (((hash % 500) / 10) + 10).toFixed(1),
        depth: (((hash % 300) / 10) + 5).toFixed(1)
      };
    });
    return stats;
  }, [lakes]);

  const filteredLakes = lakes.filter(lake => 
    lake.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div className="map-view-container">
      <Helmet>
        <title>{t[language].seo.mapTitle}</title>
        <meta name="description" content={t[language].seo.mapDesc} />
        <meta property="og:title" content={t[language].seo.mapTitle} />
        <meta property="og:description" content={t[language].seo.mapDesc} />
      </Helmet>
      
      {/* Leaflet Map */}
      <MapContainer 
        center={[49.8, 15.5]} 
        zoom={7} 
        style={{ width: '100%', height: '100%' }}
        zoomControl={false}
      >
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OSM</a> contributors'
        />

        {lakes.map(lake => (
          <Marker 
            key={lake.id} 
            position={[lake.lat, lake.lng]}
            icon={createCustomIcon(lake.type)}
            eventHandlers={{
              click: () => navigate(`/${slugify(lake.name)}`)
            }}
          >
            <Tooltip direction="top" offset={[0, -38]} opacity={0.9}>
              <span style={{ fontWeight: 'bold' }}>{lake.name}</span>
              {lake.river && <span style={{ color: 'var(--text-muted)', fontSize: '0.8rem', marginLeft: '0.4rem' }}>({lake.river})</span>}
            </Tooltip>
            <Popup>
              <strong>{lake.name}</strong><br/>
              {lake.river}
            </Popup>
          </Marker>
        ))}
      </MapContainer>

      {/* Floating Overlay Panel */}
      {isPanelVisible && (
        <div className="map-overlay-panel">
          <div className="map-overlay-header">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.5rem' }}>
              <h3 style={{ margin: 0, fontSize: '1.1rem' }}>{language === 'cs' ? 'Seznam jezer a nádrží' : 'Lakes and Reservoirs List'}</h3>
              <FiX style={{ cursor: 'pointer', color: 'var(--text-muted)' }} onClick={() => setIsPanelVisible(false)} />
            </div>
            <div style={{ fontSize: '0.85rem', color: 'var(--text-muted)', marginBottom: '1rem' }}>
              {language === 'cs' ? `Nalezeno: ${filteredLakes.length} záznamů` : `Found: ${filteredLakes.length} records`}
            </div>
            
            <div className="search-bar" style={{ width: '100%', padding: '0.5rem', backgroundColor: 'rgba(0,0,0,0.3)', border: '1px solid rgba(255,255,255,0.1)' }}>
              <FiSearch />
              <input 
                type="text" 
                placeholder={language === 'cs' ? 'Najít jezero...' : 'Find a lake...'} 
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                style={{ width: '100%', background: 'transparent', border: 'none', color: 'white', outline: 'none' }}
              />
            </div>
          </div>

          <div className="map-overlay-list">
            {filteredLakes.map((lake, index) => (
              <div key={lake.id} className="map-lake-card" onClick={() => navigate(`/${slugify(lake.name)}`)}>
                <div style={{ fontWeight: 'bold', marginBottom: '0.5rem' }}>{index + 1}. {lake.name}</div>
                <div className="map-lake-stats">
                  <div>
                    <span style={{ color: 'var(--text-muted)', display: 'block' }}>{language === 'cs' ? 'Rozloha' : 'Area'}</span>
                    <span style={{ color: 'var(--text-main)' }}>{randomStats[lake.id]?.area || '0.0'} km²</span>
                  </div>
                  <div>
                    <span style={{ color: 'var(--text-muted)', display: 'block' }}>{language === 'cs' ? 'Hloubka' : 'Depth'}</span>
                    <span style={{ color: 'var(--text-main)' }}>{randomStats[lake.id]?.depth || '0.0'}m</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
      
      {!isPanelVisible && (
        <button 
          style={{ position: 'absolute', top: 10, right: 10, zIndex: 1000, background: 'var(--bg-card)', border: '1px solid var(--border-color)', color: 'white', padding: '0.5rem 1rem', borderRadius: '8px', cursor: 'pointer' }}
          onClick={() => setIsPanelVisible(true)}
        >
          {language === 'cs' ? 'Zobrazit seznam' : 'Show List'}
        </button>
      )}
    </div>
  );
};

export default LakeMap;
