'use client';

import React, { useState, useEffect, useCallback, useRef } from 'react';
import dynamic from 'next/dynamic';
import { HazardReport, HazardType, SeverityLevel, VillageData } from '@/types/hazard';
import { PULOKULON_VILLAGES } from '@/data/pulokulon';
import {
  AlertCircle,
  MapPin,
  Send,
  X,
  LocateFixed,
  Link2,
  CheckCircle2,
  Layers,
  Crosshair,
} from 'lucide-react';

const LocationPickerMap = dynamic(() => import('@/components/LocationPickerMap'), {
  ssr: false,
  loading: () => (
    <div className="w-full h-[210px] rounded-xl bg-zinc-950 border border-zinc-700 flex items-center justify-center text-xs text-zinc-400">
      Memuat peta penentu titik lokasi...
    </div>
  ),
});

interface HazardReportModalProps {
  isOpen: boolean;
  onClose: () => void;
  villages?: VillageData[];
  onSubmitReport: (
    report: Omit<HazardReport, 'id' | 'timestamp' | 'status'>
  ) => Promise<boolean> | void;
}

function parseCoordinatesFromUrl(url: string): { lat: number; lng: number } | null {
  const patterns = [
    /@(-?\d+\.\d+),(-?\d+\.\d+)/,
    /[?&]q=(-?\d+\.\d+),(-?\d+\.\d+)/,
    /[?&]ll=(-?\d+\.\d+),(-?\d+\.\d+)/,
    /!3d(-?\d+\.\d+)!4d(-?\d+\.\d+)/,
    /(-?\d+\.\d+),\s*(-?\d+\.\d+)/,
  ];
  for (const regex of patterns) {
    const match = url.match(regex);
    if (match) {
      const lat = Number(match[1]);
      const lng = Number(match[2]);
      if (!Number.isNaN(lat) && !Number.isNaN(lng) && Math.abs(lat) <= 90 && Math.abs(lng) <= 180) {
        return { lat: Number(lat.toFixed(6)), lng: Number(lng.toFixed(6)) };
      }
    }
  }
  return null;
}

function findNearestVillage(lat: number, lng: number, villages: VillageData[]): VillageData | null {
  if (!villages.length) return null;
  let nearest: VillageData | null = null;
  let minDist = Infinity;
  for (const v of villages) {
    const dLat = v.coordinates.lat - lat;
    const dLng = v.coordinates.lng - lng;
    const dist = dLat * dLat + dLng * dLng;
    if (dist < minDist) {
      minDist = dist;
      nearest = v;
    }
  }
  // Only auto-select if within ~20km of Pulokulon (~0.18 deg)
  return minDist < 0.04 ? nearest : null;
}

export default function HazardReportModal({
  isOpen,
  onClose,
  villages = PULOKULON_VILLAGES,
  onSubmitReport,
}: HazardReportModalProps) {
  const [title, setTitle] = useState('');
  const [type, setType] = useState<HazardType>('banjir');
  const [severity, setSeverity] = useState<SeverityLevel>('tinggi');
  const [village, setVillage] = useState(villages[8]?.name || villages[0]?.name || 'Desa Pulokulon');
  const [description, setDescription] = useState('');
  const [reporterName, setReporterName] = useState('');
  const [reporterPhone, setReporterPhone] = useState('');
  const [lat, setLat] = useState(-7.124288);
  const [lng, setLng] = useState(111.033263);
  const [accuracy, setAccuracy] = useState<number | null>(null);
  const [mapMode, setMapMode] = useState<'m' | 'y'>('y');
  const [locationUrl, setLocationUrl] = useState('https://www.google.com/maps?q=-7.124288,111.033263');
  const [gpsStatus, setGpsStatus] = useState<'idle' | 'loading' | 'success' | 'manual' | 'error'>('idle');
  const [gpsMessage, setGpsMessage] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [successMsg, setSuccessMsg] = useState(false);

  const watchIdRef = useRef<number | null>(null);
  const stopTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const bestAccuracyRef = useRef<number>(Infinity);

  const stopGpsWatch = useCallback(() => {
    if (watchIdRef.current !== null && typeof navigator !== 'undefined' && navigator.geolocation) {
      navigator.geolocation.clearWatch(watchIdRef.current);
      watchIdRef.current = null;
    }
    if (stopTimerRef.current) {
      clearTimeout(stopTimerRef.current);
      stopTimerRef.current = null;
    }
  }, []);

  const applyCoordinates = useCallback((nextLat: number, nextLng: number, acc: number | null, mode: 'success' | 'manual', msg: string) => {
    const fixedLat = Number(nextLat.toFixed(6));
    const fixedLng = Number(nextLng.toFixed(6));
    setLat(fixedLat);
    setLng(fixedLng);
    setAccuracy(acc);
    setLocationUrl(`https://www.google.com/maps?q=${fixedLat},${fixedLng}`);
    setGpsStatus(mode);
    setGpsMessage(msg);
  }, []);

  const detectReporterLocation = useCallback(() => {
    stopGpsWatch();
    if (typeof window === 'undefined' || !navigator.geolocation) {
      setGpsStatus('error');
      setGpsMessage('Browser tidak mendukung GPS. Klik/geser pin merah di peta untuk menentukan titik tepat.');
      return;
    }

    bestAccuracyRef.current = Infinity;
    setGpsStatus('loading');
    setGpsMessage('Mengunci sinyal GPS presisi tinggi (±8 detik)...');

    watchIdRef.current = navigator.geolocation.watchPosition(
      (position) => {
        const acc = Math.round(position.coords.accuracy);
        if (acc < bestAccuracyRef.current) {
          bestAccuracyRef.current = acc;
          const nextLat = Number(position.coords.latitude.toFixed(6));
          const nextLng = Number(position.coords.longitude.toFixed(6));

          const nearest = findNearestVillage(nextLat, nextLng, villages);
          if (nearest) {
            setVillage(nearest.name);
          }

          const qualityLabel =
            acc <= 30
              ? `GPS Sangat Akurat (±${acc} m)`
              : acc <= 150
                ? `GPS Cukup Akurat (±${acc} m) — bisa geser pin jika perlu`
                : `Akurasi rendah (±${acc} m, sinyal Wi-Fi/PC) — silakan klik/geser pin merah di peta ke titik tepat`;

          applyCoordinates(nextLat, nextLng, acc, 'success', qualityLabel);

          // Stop watching early once we achieve high precision (<= 20m)
          if (acc <= 20) {
            stopGpsWatch();
          }
        }
      },
      () => {
        stopGpsWatch();
        setGpsStatus('error');
        setGpsMessage(
          'Izin GPS tidak aktif. Pilih desa lalu klik/geser pin merah di peta atau tempel URL Google Maps.'
        );
      },
      { enableHighAccuracy: true, timeout: 12000, maximumAge: 0 }
    );

    // Stop refining after 8 seconds so battery/CPU stays clean
    stopTimerRef.current = setTimeout(() => {
      stopGpsWatch();
    }, 8000);
  }, [applyCoordinates, stopGpsWatch, villages]);

  useEffect(() => {
    if (isOpen) {
      detectReporterLocation();
    } else {
      stopGpsWatch();
    }
    return () => stopGpsWatch();
  }, [isOpen, detectReporterLocation, stopGpsWatch]);

  if (!isOpen) return null;

  const handlePinMoved = (nextLat: number, nextLng: number) => {
    stopGpsWatch();
    const nearest = findNearestVillage(nextLat, nextLng, villages);
    if (nearest) setVillage(nearest.name);
    applyCoordinates(
      nextLat,
      nextLng,
      null,
      'manual',
      'Titik lokasi tepat dipilih langsung pada peta (presisi manual).'
    );
  };

  const handleLocationUrlChange = (val: string) => {
    setLocationUrl(val);
    const parsed = parseCoordinatesFromUrl(val);
    if (parsed) {
      stopGpsWatch();
      const nearest = findNearestVillage(parsed.lat, parsed.lng, villages);
      if (nearest) setVillage(nearest.name);
      setLat(parsed.lat);
      setLng(parsed.lng);
      setAccuracy(null);
      setGpsStatus('manual');
      setGpsMessage('Koordinat presisi berhasil diekstrak dari URL Google Maps.');
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!title.trim() || !description.trim() || !reporterName.trim()) {
      alert('Mohon lengkapi judul, deskripsi, dan nama pelapor.');
      return;
    }

    stopGpsWatch();
    setSubmitting(true);
    try {
      const finalUrl = locationUrl.trim() || `https://www.google.com/maps?q=${lat},${lng}`;
      await onSubmitReport({
        title: title.trim(),
        type,
        severity,
        village,
        description: description.trim(),
        reporterName: reporterName.trim(),
        reporterPhone: reporterPhone.trim() || '081234567890',
        coordinates: { lat, lng },
        locationUrl: finalUrl,
        image: `https://picsum.photos/seed/hazard-${Date.now()}/600/400`,
      });

      setSuccessMsg(true);
      setTimeout(() => {
        setSuccessMsg(false);
        onClose();
        setTitle('');
        setDescription('');
        setReporterName('');
        setReporterPhone('');
      }, 1200);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 backdrop-blur-sm p-4">
      <div className="relative w-full max-w-2xl max-h-[92vh] overflow-y-auto p-6 bg-zinc-900 rounded-2xl shadow-2xl border border-zinc-800 text-zinc-100">
        <button
          onClick={() => {
            stopGpsWatch();
            onClose();
          }}
          className="absolute top-4 right-4 p-2 text-zinc-400 hover:text-zinc-200 rounded-full transition"
        >
          <X className="w-5 h-5" />
        </button>

        <div className="flex items-center gap-3 mb-5">
          <div className="p-3 bg-red-950/60 text-red-500 rounded-xl border border-red-900/50">
            <AlertCircle className="w-6 h-6" />
          </div>
          <div>
            <h2 className="text-xl font-bold">Laporkan Hazard / Darurat Baru</h2>
            <p className="text-xs text-zinc-400">
              Kunci GPS presisi tinggi atau klik/geser pin merah di peta ke titik tepat kejadian
            </p>
          </div>
        </div>

        {successMsg ? (
          <div className="py-12 text-center">
            <div className="w-16 h-16 bg-emerald-950 text-emerald-400 rounded-full flex items-center justify-center mx-auto mb-4 text-2xl font-bold border border-emerald-700">
              ✓
            </div>
            <h3 className="text-lg font-bold text-emerald-400">
              Laporan &amp; Titik Lokasi Presisi Berhasil Dikirim!
            </h3>
            <p className="text-sm text-zinc-400 mt-1">
              Posko Siaga Pulokulon kini dapat melacak koordinat tepat kejadian.
            </p>
          </div>
        ) : (
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-xs font-semibold mb-1 uppercase tracking-wider text-zinc-400">
                Judul Laporan / Kejadian
              </label>
              <input
                type="text"
                required
                placeholder="Contoh: Air meluap di jembatan Tuko / Kebakaran rumah"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                className="w-full px-3.5 py-2.5 bg-zinc-800 border border-zinc-700 rounded-xl text-sm text-white focus:outline-none focus:ring-2 focus:ring-red-600"
              />
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
              <div>
                <label className="block text-xs font-semibold mb-1 uppercase tracking-wider text-zinc-400">
                  Jenis Hazard
                </label>
                <select
                  value={type}
                  onChange={(e) => setType(e.target.value as HazardType)}
                  className="w-full px-3 py-2.5 bg-zinc-800 border border-zinc-700 rounded-xl text-sm text-white focus:outline-none focus:ring-2 focus:ring-red-600"
                >
                  <option value="banjir">Banjir / Genangan Air</option>
                  <option value="kebakaran">Kebakaran / Korsleting</option>
                  <option value="pencurian">Pencurian</option>
                  <option value="perampokan">Perampokan / Todongan</option>
                  <option value="kriminal_lain">Tindakan Kriminal Lain</option>
                  <option value="cuaca_ekstrem">Cuaca Ekstrem / Puting Beliung</option>
                </select>
              </div>

              <div>
                <label className="block text-xs font-semibold mb-1 uppercase tracking-wider text-zinc-400">
                  Tingkat Keparahan
                </label>
                <select
                  value={severity}
                  onChange={(e) => setSeverity(e.target.value as SeverityLevel)}
                  className="w-full px-3 py-2.5 bg-zinc-800 border border-zinc-700 rounded-xl text-sm text-white focus:outline-none focus:ring-2 focus:ring-red-600"
                >
                  <option value="rendah">Rendah (Informasi)</option>
                  <option value="sedang">Sedang (Waspada)</option>
                  <option value="tinggi">Tinggi (Siaga)</option>
                  <option value="darurat">Darurat (Awas / Evakuasi)</option>
                </select>
              </div>

              <div>
                <label className="block text-xs font-semibold mb-1 uppercase tracking-wider text-zinc-400">
                  Desa / Wilayah
                </label>
                <select
                  value={village}
                  onChange={(e) => {
                    setVillage(e.target.value);
                    const found = villages.find((v) => v.name === e.target.value);
                    if (found) {
                      stopGpsWatch();
                      applyCoordinates(
                        found.coordinates.lat,
                        found.coordinates.lng,
                        null,
                        'manual',
                        `Peta diarahkan ke ${found.name}. Klik/geser pin merah ke titik kejadian.`
                      );
                    }
                  }}
                  className="w-full px-3 py-2.5 bg-zinc-800 border border-zinc-700 rounded-xl text-sm text-white focus:outline-none focus:ring-2 focus:ring-red-600"
                >
                  {villages.map((v) => (
                    <option key={v.id} value={v.name}>
                      {v.name}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            {/* Interactive Precision Location Picker Box */}
            <div className="p-3.5 bg-zinc-800/50 border border-zinc-700/80 rounded-xl space-y-3">
              <div className="flex flex-wrap items-center justify-between gap-2">
                <span className="text-[11px] font-bold uppercase tracking-wider text-zinc-200 flex items-center gap-1.5">
                  <Crosshair className="w-3.5 h-3.5 text-red-400" />
                  Pilih Titik Lokasi Presisi (Klik / Geser Pin Merah)
                </span>
                <div className="flex items-center gap-1.5">
                  <button
                    type="button"
                    onClick={() => setMapMode(mapMode === 'y' ? 'm' : 'y')}
                    className="px-2.5 py-1 bg-zinc-800 hover:bg-zinc-700 border border-zinc-600 text-zinc-200 text-[11px] font-semibold rounded-lg inline-flex items-center gap-1 cursor-pointer"
                  >
                    <Layers className="w-3 h-3 text-red-400" />
                    {mapMode === 'y' ? 'Peta Jalan' : 'Satelit'}
                  </button>
                  <button
                    type="button"
                    onClick={detectReporterLocation}
                    className="px-2.5 py-1 bg-red-600 hover:bg-red-500 text-white text-[11px] font-bold rounded-lg inline-flex items-center gap-1 cursor-pointer"
                  >
                    <LocateFixed
                      className={`w-3 h-3 ${gpsStatus === 'loading' ? 'animate-spin' : ''}`}
                    />
                    Deteksi GPS Saya
                  </button>
                </div>
              </div>

              <LocationPickerMap
                lat={lat}
                lng={lng}
                accuracy={accuracy}
                mapMode={mapMode}
                onChangeLocation={handlePinMoved}
              />

              {/* Editable Lat / Lng + URL */}
              <div className="grid grid-cols-2 gap-2.5">
                <div>
                  <label className="block text-[10px] font-mono uppercase text-zinc-400 mb-1">
                    Latitude
                  </label>
                  <input
                    type="number"
                    step="0.000001"
                    value={lat}
                    onChange={(e) => {
                      const val = Number(e.target.value);
                      if (!Number.isNaN(val)) {
                        setLat(val);
                        setLocationUrl(`https://www.google.com/maps?q=${val},${lng}`);
                      }
                    }}
                    className="w-full px-2.5 py-1.5 bg-zinc-900 border border-zinc-700 rounded-lg text-xs font-mono text-zinc-100"
                  />
                </div>
                <div>
                  <label className="block text-[10px] font-mono uppercase text-zinc-400 mb-1">
                    Longitude
                  </label>
                  <input
                    type="number"
                    step="0.000001"
                    value={lng}
                    onChange={(e) => {
                      const val = Number(e.target.value);
                      if (!Number.isNaN(val)) {
                        setLng(val);
                        setLocationUrl(`https://www.google.com/maps?q=${lat},${val}`);
                      }
                    }}
                    className="w-full px-2.5 py-1.5 bg-zinc-900 border border-zinc-700 rounded-lg text-xs font-mono text-zinc-100"
                  />
                </div>
              </div>

              <div className="space-y-1">
                <label className="text-[10px] font-semibold uppercase tracking-wider text-zinc-400 flex items-center gap-1">
                  <Link2 className="w-3 h-3 text-red-400" />
                  URL Lokasi Google Maps (Otomatis / Tempel Link Lokasi)
                </label>
                <input
                  type="url"
                  placeholder="https://www.google.com/maps?q=-7.124288,111.033263"
                  value={locationUrl}
                  onChange={(e) => handleLocationUrlChange(e.target.value)}
                  className="w-full px-3 py-1.5 bg-zinc-900 border border-zinc-700 rounded-lg text-xs text-zinc-200 font-mono focus:outline-none focus:ring-2 focus:ring-red-600"
                />
              </div>

              {gpsMessage && (
                <div className="flex items-center gap-1.5 text-[11px]">
                  {gpsStatus === 'success' || gpsStatus === 'manual' ? (
                    <CheckCircle2 className="w-3.5 h-3.5 text-emerald-400 shrink-0" />
                  ) : (
                    <MapPin className="w-3.5 h-3.5 text-amber-400 shrink-0" />
                  )}
                  <span
                    className={
                      gpsStatus === 'success' || gpsStatus === 'manual'
                        ? accuracy && accuracy > 150
                          ? 'text-amber-300'
                          : 'text-emerald-400'
                        : gpsStatus === 'error'
                          ? 'text-amber-400'
                          : 'text-zinc-300'
                    }
                  >
                    {gpsMessage}
                  </span>
                </div>
              )}
            </div>

            <div>
              <label className="block text-xs font-semibold mb-1 uppercase tracking-wider text-zinc-400">
                Deskripsi Kejadian / Keterangan
              </label>
              <textarea
                required
                rows={3}
                placeholder="Jelaskan kondisi secara detail (situasi, korban, kebutuhan mendesak)..."
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                className="w-full px-3.5 py-2.5 bg-zinc-800 border border-zinc-700 rounded-xl text-sm text-white focus:outline-none focus:ring-2 focus:ring-red-600"
              />
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-semibold mb-1 uppercase tracking-wider text-zinc-400">
                  Nama Pelapor
                </label>
                <input
                  type="text"
                  required
                  placeholder="Nama lengkap atau ketua RT/RW"
                  value={reporterName}
                  onChange={(e) => setReporterName(e.target.value)}
                  className="w-full px-3.5 py-2.5 bg-zinc-800 border border-zinc-700 rounded-xl text-sm text-white focus:outline-none focus:ring-2 focus:ring-red-600"
                />
              </div>

              <div>
                <label className="block text-xs font-semibold mb-1 uppercase tracking-wider text-zinc-400">
                  Nomor Kontak / WhatsApp
                </label>
                <input
                  type="tel"
                  placeholder="081234567890"
                  value={reporterPhone}
                  onChange={(e) => setReporterPhone(e.target.value)}
                  className="w-full px-3.5 py-2.5 bg-zinc-800 border border-zinc-700 rounded-xl text-sm text-white focus:outline-none focus:ring-2 focus:ring-red-600"
                />
              </div>
            </div>

            <div className="pt-1">
              <button
                type="submit"
                disabled={submitting}
                className="w-full py-3.5 bg-red-600 hover:bg-red-500 disabled:opacity-50 text-white font-bold rounded-xl shadow-lg transition flex items-center justify-center gap-2 cursor-pointer"
              >
                <Send className="w-5 h-5" />
                {submitting ? 'Menyimpan ke Database...' : 'Kirim Laporan & Lokasi Presisi ke Posko'}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}
