import React, { useState, useCallback, useEffect, useRef } from 'react';
import { MapContainer, TileLayer, CircleMarker, useMapEvents } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import './RegionPinPicker.css';

/* ─────────────────────────────────────────────
   ClickHandler — captures map clicks
───────────────────────────────────────────── */
function ClickHandler({ onClickLatLng }) {
  useMapEvents({
    click(e) {
      onClickLatLng([e.latlng.lng, e.latlng.lat]); // [lng, lat]
    },
  });
  return null;
}

/* ─────────────────────────────────────────────
   RegionPinPicker — modal for picking a
   location on the map
───────────────────────────────────────────── */
export default function RegionPinPicker({
  regionId,
  regionName,
  initialCoords,   // [lng, lat] or null
  accent,
  onSave,          // (coords: [lng, lat]) => void
  onClose,
}) {
  const [coords, setCoords] = useState(initialCoords || null);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  const backdropRef = useRef(null);

  /* ESC to close */
  useEffect(() => {
    const handler = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [onClose]);

  const handleMapClick = useCallback((lngLat) => {
    setCoords(lngLat);
    setError('');
  }, []);

  const handleSave = useCallback(async () => {
    if (!coords) return;
    setSaving(true);
    setError('');
    try {
      const res = await fetch(`/api/travel/regions/${encodeURIComponent(regionId)}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ coordinates: coords }),
      });
      if (!res.ok) throw new Error(`${res.status}`);
      onSave?.(coords);
      onClose();
    } catch (e) {
      setError(`저장 실패: ${e.message}`);
    } finally {
      setSaving(false);
    }
  }, [coords, regionId, onSave, onClose]);

  const handleBackdrop = useCallback(
    (e) => { if (e.target === backdropRef.current) onClose(); },
    [onClose],
  );

  const center = coords
    ? [coords[1], coords[0]]
    : initialCoords
      ? [initialCoords[1], initialCoords[0]]
      : [30, 125];
  const zoom = coords || initialCoords ? 4 : 2;

  return (
    <div className="pin-picker" ref={backdropRef} onClick={handleBackdrop}>
      <div className="pin-picker__panel">
        {/* Header */}
        <div className="pin-picker__header">
          <div className="pin-picker__title">
            <span className="pin-picker__label">위치 지정</span>
            <span className="pin-picker__region" style={{ color: accent }}>
              {regionName || regionId}
            </span>
          </div>
          <button className="pin-picker__close" onClick={onClose}>✕</button>
        </div>

        {/* Instruction */}
        <p className="pin-picker__hint">지도를 클릭하여 핀을 놓으세요</p>

        {/* Map */}
        <div className="pin-picker__map-wrap">
          <MapContainer
            center={center}
            zoom={zoom}
            minZoom={2}
            maxZoom={12}
            zoomControl={true}
            attributionControl={false}
            className="pin-picker__map"
            style={{ width: '100%', height: '100%' }}
          >
            <TileLayer
              url="https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png"
              attribution=""
            />
            <ClickHandler onClickLatLng={handleMapClick} />
            {coords && (
              <CircleMarker
                center={[coords[1], coords[0]]}
                radius={8}
                pathOptions={{
                  fillColor: accent || '#c8905e',
                  fillOpacity: 0.9,
                  color: '#fff',
                  weight: 2,
                }}
              />
            )}
          </MapContainer>
        </div>

        {/* Coords display */}
        {coords && (
          <p className="pin-picker__coords">
            {coords[1].toFixed(4)}, {coords[0].toFixed(4)}
          </p>
        )}

        {error && <p className="pin-picker__error">{error}</p>}

        {/* Actions */}
        <div className="pin-picker__actions">
          <button className="pin-picker__cancel" onClick={onClose}>취소</button>
          <button
            className="pin-picker__save"
            onClick={handleSave}
            disabled={!coords || saving}
            style={{ '--accent': accent || '#c8905e' }}
          >
            {saving ? '저장 중…' : '핀 저장'}
          </button>
        </div>
      </div>
    </div>
  );
}
