@extends('layout.main')

@push('style')
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />

<style>
    .plant-marker {
        border: 2px solid #ffffff;
        border-radius: 50%;
        box-shadow: 0 0 5px rgba(0,0,0,0.6);
        animation: pulse 2s infinite;
    }
    @keyframes pulse {
        0% { box-shadow: 0 0 0 0 rgba(0,0,0, 0.4); }
        70% { box-shadow: 0 0 0 10px rgba(0,0,0, 0); }
        100% { box-shadow: 0 0 0 0 rgba(0,0,0, 0); }
    }
</style>
@endpush

@section('content')
<div class="container-xxl flex-grow-1 container-p-y">
    <div class="card">
        <div class="card-header border-bottom mb-4 d-flex justify-content-between align-items-center">
            <h5 class="card-title mb-0">Detail Map Lahan</h5>
            <a href="{{ route('lahan.index') }}" class="btn btn-sm btn-label-secondary">
                <i class="ti tabler-arrow-left me-1"></i> Kembali
            </a>
        </div>
        
        <div class="card-body">
            <form onsubmit="return false;">
                
                <div class="row">
                    <div class="col-lg-6 mb-4">
                        <h6 class="mb-3 text-primary"><i class="ti tabler-info-circle me-1"></i> Info Lahan</h6>
                        
                        <div class="mb-3">
                            <label class="form-label">Nama Lahan</label>
                            <input type="text" class="form-control bg-lighter" value="{{ $lahan->nama }}" readonly />
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Pemilik (Profile)</label>
                            <input type="text" class="form-control bg-lighter" value="{{ $lahan->profile->nama ?? '-' }}" readonly />
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Status Kepemilikan</label>
                                <input type="text" class="form-control bg-lighter" value="{{ $lahan->status_kepemilikan }}" readonly />
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Luas Lahan (Ha/m2)</label>
                                <input type="text" class="form-control bg-lighter" value="{{ $lahan->luas_lahan ?? '-' }}" readonly />
                            </div>
                        </div>

                        <hr class="my-4">
                        <h6 class="mb-3 text-primary"><i class="ti tabler-map-pin me-1"></i> Lokasi Wilayah</h6>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Provinsi</label>
                                <input type="text" class="form-control bg-lighter" value="{{ $lahan->desakelurahan->kecamatan->kabupatenkota->provinsi->nama ?? '-' }}" readonly />
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Kabupaten/Kota</label>
                                <input type="text" class="form-control bg-lighter" value="{{ $lahan->desakelurahan->kecamatan->kabupatenkota->nama ?? '-' }}" readonly />
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Kecamatan</label>
                                <input type="text" class="form-control bg-lighter" value="{{ $lahan->desakelurahan->kecamatan->nama ?? '-' }}" readonly />
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Desa/Kelurahan</label>
                                <input type="text" class="form-control bg-lighter" value="{{ $lahan->desakelurahan->nama ?? '-' }}" readonly />
                            </div>
                        </div>
                        
                        @if($lahan->status_kepemilikan === 'Tanah Adat')
                        <div class="mb-3">
                            <label class="form-label text-warning">Data Adat Pemilik</label>
                            <input type="text" class="form-control bg-lighter border-warning" value="{{ $lahan->adat_pemilik_id ?? 'Tidak ada data adat' }}" readonly />
                        </div>
                        @endif

                    </div>

                    <div class="col-lg-6 mb-4">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h6 class="text-primary mb-0"><i class="ti tabler-map me-1"></i> Visualisasi Peta Lahan</h6>
                            
                            <div class="form-check form-switch mb-0">
                                <input class="form-check-input" type="checkbox" id="toggleTanaman">
                                <label class="form-check-label text-nowrap fw-bold text-success" for="toggleTanaman"><i class="ti tabler-seeding me-1"></i>Tampilkan Tanaman</label>
                            </div>
                        </div>
                        
                        <div id="map" class="border rounded" style="height: 400px; width: 100%; background-color: #f8f9fa; z-index: 1;">
                            <div id="map-fallback" class="d-flex align-items-center justify-content-center h-100 text-muted d-none">
                                Memuat Peta...
                            </div>
                        </div>
                        
                        <div class="mt-3">
                            <label class="form-label">Raw Data Koordinat (JSON)</label>
                            <textarea class="form-control bg-lighter font-monospace" rows="3" readonly>{{ $lahan->path ?? 'Tidak ada data koordinat' }}</textarea>
                        </div>
                    </div>
                </div>

            </form>
        </div>
    </div>
</div>

<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
@endsection

@push('scripts')
<script>
    document.addEventListener("DOMContentLoaded", function() {

        let rawData = {!! $lahan->path ? $lahan->path : '[]' !!};
        let dataTanaman = {!! json_encode($lahan->tanaman ?? []) !!}; 
        
        let mapContainer = document.getElementById('map');
        let fallbackMsg = document.getElementById('map-fallback');

        const colorPalette = [
            '#FF33A8', '#3357FF', '#F3FF33', '#FF5733', '#33FFF5', 
            '#8A33FF', '#FF8F33', '#33FF8A', '#FF3333', '#33A8FF'
        ];

        if (Array.isArray(rawData) && rawData.length > 0) {
            
            let map = L.map('map').setView([rawData[0][1], rawData[0][0]], 16); 

            L.tileLayer('http://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}', {
                maxZoom: 22,
                subdomains: ['mt0', 'mt1', 'mt2', 'mt3'],
                attribution: '&copy; Google Maps Satellite'
            }).addTo(map);

            let latLngs = rawData.map(function(coord) {
                return [coord[1], coord[0]]; 
            });

            let polygon = L.polygon(latLngs, {
                color: '#28c76f',    
                fillColor: '#28c76f',
                fillOpacity: 0.3,
                weight: 2
            }).addTo(map);

            polygon.bindPopup("<b>{{ $lahan->nama }}</b><br>Luas: {{ $lahan->luas_lahan ?? '-' }} Ha");
            map.fitBounds(polygon.getBounds(), { padding: [20, 20] });

            let tanamanLayerGroup = L.layerGroup();

            dataTanaman.forEach(function(tanaman) {
                if(tanaman.latitude && tanaman.longitude) {
                    let komoditasId = tanaman.komoditas_id || 1;
                    let markerColor = colorPalette[komoditasId % colorPalette.length];
                    let komoditasNama = tanaman.komoditas ? tanaman.komoditas.nama : 'Unknown';

                    let badgeClass = 'bg-label-success';
                    if (tanaman.kondisi_tanaman === 'sakit') badgeClass = 'bg-label-warning';
                    if (tanaman.kondisi_tanaman === 'mati') badgeClass = 'bg-label-danger';

                    let customIcon = L.divIcon({
                        className: 'custom-div-icon',
                        html: `<div class="plant-marker" style="background-color:${markerColor}; width:16px; height:16px;"></div>`,
                        iconSize: [16, 16],
                        iconAnchor: [8, 8]
                    });

                    let popupContent = `
                        <div class="text-center" style="min-width: 120px;">
                            <h6 class="mb-1 fw-bold">${tanaman.nama}</h6>
                            <small class="text-muted d-block mb-1">${komoditasNama}</small>
                            <hr class="my-1">
                            <span class="badge ${badgeClass} w-100">Kondisi: ${tanaman.kondisi_tanaman.charAt(0).toUpperCase() + tanaman.kondisi_tanaman.slice(1)}</span>
                        </div>
                    `;

                    L.marker([tanaman.latitude, tanaman.longitude], { icon: customIcon })
                     .bindPopup(popupContent)
                     .addTo(tanamanLayerGroup);
                }
            });

            let toggleBtn = document.getElementById('toggleTanaman');
            toggleBtn.addEventListener('change', function() {
                if (this.checked) {
                    map.addLayer(tanamanLayerGroup);
                } else {
                    map.removeLayer(tanamanLayerGroup);
                }
            });

        } else {
            fallbackMsg.classList.remove('d-none');
            fallbackMsg.innerHTML = '<div class="text-center"><i class="ti tabler-map-off mb-2" style="font-size: 2rem;"></i><br>Tidak ada data koordinat polygon untuk lahan ini.</div>';
        }
    });
</script>
@endpush