import { useState } from 'react';
import { Marker, Popup } from 'react-map-gl/maplibre';
import { HAZARD_FACILITIES } from '../../data/hazardFacilities';
import type { HazardFacility, HazardType } from '../../data/hazardFacilities';

interface Props {
  type: HazardType;
}

const TYPE_META: Record<HazardType, { icon: string; color: string; label: string; bgColor: string }> = {
  petrochemical: { icon: '🏭', color: '#f97316', label: '석유화학단지',  bgColor: 'rgba(249,115,22,0.15)' },
  lng:           { icon: '🔵', color: '#06b6d4', label: 'LNG저장기지',   bgColor: 'rgba(6,182,212,0.15)' },
  oilTank:       { icon: '🛢️',  color: '#eab308', label: '유류저장탱크', bgColor: 'rgba(234,179,8,0.15)' },
  hazardPort:    { icon: '⚠️',  color: '#ef4444', label: '위험물하역시설', bgColor: 'rgba(239,68,68,0.15)' },
  nuclear:       { icon: '☢️',  color: '#a855f7', label: '원자력발전소',   bgColor: 'rgba(168,85,247,0.15)' },
  thermal:       { icon: '🔥', color: '#64748b', label: '화력발전소',     bgColor: 'rgba(100,116,139,0.15)' },
  shipyard:      { icon: '🚢', color: '#0ea5e9', label: '조선소 도장시설', bgColor: 'rgba(14,165,233,0.15)' },
  wastewater:    { icon: '💧', color: '#10b981', label: '폐수처리장',      bgColor: 'rgba(16,185,129,0.15)' },
  heavyIndustry: { icon: '⚙️',  color: '#94a3b8', label: '시멘트/제철소',  bgColor: 'rgba(148,163,184,0.15)' },
};

export function HazardFacilityLayer({ type }: Props) {
  const [selected, setSelected] = useState<HazardFacility | null>(null);
  const meta = TYPE_META[type];
  const facilities = HAZARD_FACILITIES.filter(f => f.type === type);

  return (
    <>
      {facilities.map(f => (
        <Marker key={f.id} longitude={f.lng} latitude={f.lat} anchor="center"
          onClick={(e) => { e.originalEvent.stopPropagation(); setSelected(f); }}>
          <div
            className="flex flex-col items-center cursor-pointer"
            style={{ filter: `drop-shadow(0 0 4px ${meta.color}99)` }}
          >
            <div style={{
              width: 20, height: 20, borderRadius: 4,
              background: 'rgba(0,0,0,0.75)',
              border: `1.5px solid ${meta.color}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 11,
            }}>
              {meta.icon}
            </div>
            <div style={{
              fontSize: 5, color: meta.color, marginTop: 1,
              textShadow: '0 0 3px #000, 0 0 3px #000',
              whiteSpace: 'nowrap', fontWeight: 700,
            }}>
              {f.nameKo.length > 12 ? f.nameKo.slice(0, 12) + '..' : f.nameKo}
            </div>
          </div>
        </Marker>
      ))}

      {selected && (
        <Popup
          longitude={selected.lng} latitude={selected.lat}
          onClose={() => setSelected(null)} closeOnClick={false}
          anchor="bottom" maxWidth="300px" className="gl-popup"
        >
          <div className="popup-body-sm" style={{ minWidth: 230 }}>
            <div className="popup-header" style={{
              background: meta.color, color: '#fff', gap: 6, padding: '6px 10px',
            }}>
              <span style={{ fontSize: 16 }}>{meta.icon}</span>
              <strong style={{ fontSize: 13 }}>{selected.nameKo}</strong>
            </div>

            <div style={{ display: 'flex', gap: 4, marginBottom: 6 }}>
              <span style={{
                background: meta.color, color: '#fff',
                padding: '2px 8px', borderRadius: 3, fontSize: 10, fontWeight: 700,
              }}>
                {meta.label}
              </span>
              <span style={{
                background: 'rgba(239,68,68,0.2)', color: '#ef4444', border: '1px solid #ef4444',
                padding: '2px 8px', borderRadius: 3, fontSize: 10, fontWeight: 700,
              }}>
                ⚠️ 위험시설
              </span>
            </div>

            <div style={{ fontSize: 11, color: '#cbd5e1', marginBottom: 6, lineHeight: 1.5 }}>
              {selected.description}
            </div>

            <div className="popup-grid" style={{ gap: '2px 12px' }}>
              {selected.address && (
                <div><span className="popup-label">주소 : </span><strong>{selected.address}</strong></div>
              )}
              {selected.operator && (
                <div><span className="popup-label">운영자 : </span><strong>{selected.operator}</strong></div>
              )}
              {selected.capacity && (
                <div><span className="popup-label">처리규모 : </span><strong>{selected.capacity}</strong></div>
              )}
              <div><span className="popup-label">시설명(EN) : </span>{selected.name}</div>
            </div>

            <div style={{ marginTop: 6, fontSize: 10, color: '#64748b' }}>
              {selected.lat.toFixed(4)}°N, {selected.lng.toFixed(4)}°E
            </div>
          </div>
        </Popup>
      )}
    </>
  );
}
