import { useState, useEffect } from 'react';
import { Button, Space, Typography } from 'antd';
import { MapContainer, useMap } from 'react-leaflet';
import { api } from '@/lib/api';
import type { Cut, MapSettings } from '@/types/api';
import CutDrawingMode from './CutDrawingMode';
import CutOverlays from './CutOverlays';
import DynamicTileLayer from './DynamicTileLayer';
import TileLayerToggle from './TileLayerToggle';
import { getPersistedTileLayer, persistTileLayer, getTileConfig } from './tileLayers';
import 'leaflet/dist/leaflet.css';

interface Props {
  cuts: Cut[];
  onFinishDraw: (geojson: string, bounds: string) => void;
}

function InvalidateOnMount() {
  const map = useMap();
  useEffect(() => {
    const timer = setTimeout(() => map.invalidateSize(), 100);
    return () => clearTimeout(timer);
  }, [map]);
  return null;
}

function CenterOnSettings({ settings }: { settings: MapSettings | null }) {
  const map = useMap();

  useEffect(() => {
    if (!settings?.latitude || !settings?.longitude) return;
    const lat = parseFloat(settings.latitude);
    const lng = parseFloat(settings.longitude);
    const zoom = settings.zoom ?? 12;

    // Use setView to imperatively update map center
    map.setView([lat, lng], zoom);
  }, [map, settings]);

  return null;
}

export default function CutEditorMap({ cuts, onFinishDraw }: Props) {
  const [settings, setSettings] = useState<MapSettings | null>(null);
  const [drawing, setDrawing] = useState(false);
  const [tileKey, setTileKey] = useState(getPersistedTileLayer);

  useEffect(() => {
    api.get<MapSettings>('/map/settings').then(({ data }) => setSettings(data)).catch(() => {});
  }, []);

  const center: [number, number] = settings?.latitude && settings?.longitude
    ? [parseFloat(settings.latitude), parseFloat(settings.longitude)]
    : [45.4215, -75.6972];
  const zoom = settings?.zoom ?? 12;

  const allCutIds = new Set(cuts.map((c) => c.id));

  return (
    <div style={{ position: 'relative', width: '100%', height: 'calc(100vh - 64px)' }}>
      {/* Drawing toolbar */}
      <div
        style={{
          position: 'absolute',
          top: 10,
          left: '50%',
          transform: 'translateX(-50%)',
          zIndex: 1001,
          background: 'rgba(26, 16, 37, 0.95)',
          borderRadius: 8,
          padding: '8px 16px',
          backdropFilter: 'blur(8px)',
          border: '1px solid rgba(255,255,255,0.12)',
        }}
      >
        {!drawing ? (
          <Button type="primary" onClick={() => setDrawing(true)}>
            Draw Cut
          </Button>
        ) : (
          <Space>
            <Typography.Text style={{ color: 'rgba(255,255,255,0.85)', fontSize: 12 }}>
              Click vertices on map. Click first vertex to close.
            </Typography.Text>
            <Button
              size="small"
              onClick={() => setDrawing(false)}
            >
              Cancel
            </Button>
            <Typography.Text type="secondary" style={{ fontSize: 11 }}>
              Esc: cancel | Ctrl+Z: undo
            </Typography.Text>
          </Space>
        )}
      </div>

      <style>{`
        .cut-editor-map .leaflet-popup-content-wrapper {
          background: #1a1025;
          color: rgba(255,255,255,0.85);
          border: 1px solid rgba(255,255,255,0.12);
          border-radius: 8px;
        }
        .cut-editor-map .leaflet-popup-tip {
          background: #1a1025;
        }
      `}</style>

      <MapContainer
        center={center}
        zoom={zoom}
        style={{ width: '100%', height: '100%', borderRadius: 8 }}
        scrollWheelZoom={true}
        className="cut-editor-map"
      >
        <InvalidateOnMount />
        <CenterOnSettings settings={settings} />
        <DynamicTileLayer config={getTileConfig(tileKey)} />
        <CutOverlays cuts={cuts} visibleCutIds={allCutIds} />
        <CutDrawingMode
          active={drawing}
          color="#3388ff"
          opacity={0.3}
          onFinish={(geojson, bounds) => {
            setDrawing(false);
            onFinishDraw(geojson, bounds);
          }}
          onCancel={() => setDrawing(false)}
        />
      </MapContainer>

      <TileLayerToggle
        activeKey={tileKey}
        onChange={(key) => { setTileKey(key); persistTileLayer(key); }}
        position="bottom-right"
      />
    </div>
  );
}
