import React from 'react';
import { supabase } from '@/lib/supabase';

// Simple Haversine distance calculator
function getDistance(lat1, lon1, lat2, lon2) {
  if (!lat1 || !lon1 || !lat2 || !lon2) return 0;
  const R = 6371000; // meters
  const phi1 = (lat1 * Math.PI) / 180;
  const phi2 = (lat2 * Math.PI) / 180;
  const deltaPhi = ((lat2 - lat1) * Math.PI) / 180;
  const deltaLambda = ((lon2 - lon1) * Math.PI) / 180;

  const a =
    Math.sin(deltaPhi / 2) * Math.sin(deltaPhi / 2) +
    Math.cos(phi1) * Math.cos(phi2) * Math.sin(deltaLambda / 2) * Math.sin(deltaLambda / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

  return R * c; // in meters
}

export default function DelegationQueueModal({
  showDelegationModal,
  setShowDelegationModal,
  households,
  hubs,
  myHub,
  selectedPhotoUrl,
  setSelectedPhotoUrl,
  onFocusHousehold,
  fetchData,
  showToastNotification
}) {
  if (!showDelegationModal || !myHub) return null;

  // Filter incoming transfers targeted to myHub
  const incomingDelegations = households.filter(hh => hh.pending_transfer_hub_id === myHub.id);

  const handleAccept = async (hh) => {
    try {
      const { error } = await supabase
        .from('households')
        .update({
          assigned_hub_id: myHub.id,
          pending_transfer_hub_id: null,
          manual_override_assigned_hub: true
        })
        .eq('id', hh.id);

      if (error) throw error;

      showToastNotification(`Warga ${hh.head_of_family} berhasil diterima dan dialihkan ke Hub Anda!`, 'success');
      fetchData();
    } catch (err) {
      console.error(err);
      showToastNotification(`Gagal menerima delegasi: ${err.message}`, 'danger');
    }
  };

  const handleReject = async (hh) => {
    try {
      const { error } = await supabase
        .from('households')
        .update({
          pending_transfer_hub_id: null
        })
        .eq('id', hh.id);

      if (error) throw error;

      showToastNotification(`Delegasi warga ${hh.head_of_family} berhasil ditolak.`, 'success');
      fetchData();
    } catch (err) {
      console.error(err);
      showToastNotification(`Gagal menolak delegasi: ${err.message}`, 'danger');
    }
  };

  return (
    <>
      <div className="modal-overlay active">
        <div className="modal-content" style={{ maxWidth: '950px', width: '90%' }}>
          <div className="modal-header">
            <h2>
              <i className="fas fa-exchange-alt text-primary" style={{ marginRight: '8px' }}></i>
              Permohonan Delegasi Masuk
            </h2>
            <button className="close-btn" onClick={() => setShowDelegationModal(false)}>
              &times;
            </button>
          </div>
          <div className="modal-body" style={{ maxHeight: '60vh', overflowY: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.9rem' }}>
              <thead>
                <tr style={{ background: '#f1f5f9', textAlign: 'left' }}>
                  <th style={{ padding: '12px 10px', borderBottom: '2px solid #e2e8f0' }}>Kepala Keluarga</th>
                  <th style={{ padding: '12px 10px', borderBottom: '2px solid #e2e8f0' }}>Jumlah Anggota</th>
                  <th style={{ padding: '12px 10px', borderBottom: '2px solid #e2e8f0' }}>Hub Asal</th>
                  <th style={{ padding: '12px 10px', borderBottom: '2px solid #e2e8f0' }}>Jarak ke Hub Anda</th>
                  <th style={{ padding: '12px 10px', borderBottom: '2px solid #e2e8f0' }}>Verifikasi Media</th>
                  <th style={{ padding: '12px 10px', borderBottom: '2px solid #e2e8f0', textAlign: 'right' }}>Aksi Keputusan</th>
                </tr>
              </thead>
              <tbody>
                {incomingDelegations.length === 0 ? (
                  <tr>
                    <td colSpan="6" style={{ textAlign: 'center', padding: '30px', color: '#64748b' }}>
                      Tidak ada permohonan delegasi masuk untuk Hub Anda.
                    </td>
                  </tr>
                ) : (
                  incomingDelegations.map((hh) => {
                    const originHubName = hubs.find((h) => String(h.id) === String(hh.db_assigned_hub_id))?.name || 'Hub Tidak Dikenal';
                    const distanceMeters = getDistance(hh.lat, hh.lng, myHub.lat, myHub.lng);
                    const formattedDistance =
                      distanceMeters > 1000
                        ? `${(distanceMeters / 1000).toFixed(2)} km`
                        : `${Math.round(distanceMeters)} m`;

                    return (
                      <tr key={hh.id} style={{ borderBottom: '1px solid #e2e8f0' }}>
                        <td style={{ padding: '12px 10px' }}>
                          <span style={{ fontWeight: 'bold' }}>{hh.head_of_family}</span>
                          <br />
                          <small style={{ color: '#64748b' }}>NIK: {hh.nik || '-'}</small>
                        </td>
                        <td style={{ padding: '12px 10px' }}>{hh.family_size} Jiwa</td>
                        <td style={{ padding: '12px 10px', color: '#4b5563', fontWeight: '500' }}>
                          {originHubName}
                        </td>
                        <td style={{ padding: '12px 10px' }}>
                          <span
                            style={{
                              padding: '2px 6px',
                              borderRadius: '4px',
                              background: distanceMeters > (myHub.radius || 500) ? '#fef3c7' : '#dcfce7',
                              color: distanceMeters > (myHub.radius || 500) ? '#d97706' : '#15803d',
                              fontWeight: '600',
                              fontSize: '0.8rem'
                            }}
                          >
                            {formattedDistance}
                          </span>
                        </td>
                        <td style={{ padding: '12px 10px' }}>
                          <div style={{ display: 'flex', gap: '8px' }}>
                            <button
                              onClick={async () => {
                                if (hh.photo_url && !hh.photo_url.startsWith('http')) {
                                  const { data } = await supabase.storage.from('geotagging-photo').createSignedUrl(hh.photo_url, 3600);
                                  if (data && data.signedUrl) setSelectedPhotoUrl(data.signedUrl);
                                } else {
                                  setSelectedPhotoUrl(hh.photo_url || 'https://via.placeholder.com/150');
                                }
                              }}
                              className="btn btn-outline"
                              style={{ padding: '4px 8px', fontSize: '0.8rem' }}
                            >
                              Foto
                            </button>
                            <button
                              onClick={() => {
                                onFocusHousehold(hh);
                                setShowDelegationModal(false);
                              }}
                              className="btn btn-outline"
                              style={{
                                padding: '4px 8px',
                                fontSize: '0.8rem',
                                color: 'var(--primary)',
                                borderColor: 'rgba(59, 130, 246, 0.3)'
                              }}
                              title="Fokus Peta ke Lokasi KK"
                            >
                              <i className="fas fa-crosshairs"></i> Peta
                            </button>
                          </div>
                        </td>
                        <td style={{ padding: '12px 10px', textAlign: 'right' }}>
                          <button
                            onClick={() => handleAccept(hh)}
                            className="btn btn-primary"
                            style={{
                              padding: '4px 10px',
                              fontSize: '0.8rem',
                              background: '#10b981',
                              borderColor: '#10b981',
                              color: 'white',
                              marginRight: '6px'
                            }}
                          >
                            Terima
                          </button>
                          <button
                            onClick={() => handleReject(hh)}
                            className="btn btn-outline"
                            style={{
                              padding: '4px 10px',
                              fontSize: '0.8rem',
                              color: '#ef4444',
                              borderColor: '#ef4444'
                            }}
                          >
                            Tolak
                          </button>
                        </td>
                      </tr>
                    );
                  })
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {/* Photo Preview Overlay */}
      {selectedPhotoUrl && (
        <div className="modal-overlay active" style={{ zIndex: 9999 }} onClick={() => setSelectedPhotoUrl('')}>
          <div style={{ position: 'relative', maxWidth: '90%', maxHeight: '90%' }}>
            <button
              onClick={() => setSelectedPhotoUrl('')}
              style={{
                position: 'absolute',
                top: '-40px',
                right: '0',
                background: 'none',
                border: 'none',
                color: 'white',
                fontSize: '2rem',
                cursor: 'pointer'
              }}
            >
              &times;
            </button>
            <img
              src={selectedPhotoUrl}
              alt="Bukti Foto"
              style={{
                maxWidth: '100%',
                maxHeight: '90vh',
                borderRadius: '8px',
                boxShadow: '0 4px 20px rgba(0,0,0,0.5)'
              }}
            />
          </div>
        </div>
      )}
    </>
  );
}
