import React, { useState, useEffect } from 'react';
import { supabase } from '../../../lib/supabase';

export default function CapacityApprovalModal({
  showApprovalModal,
  setShowApprovalModal,
  hubs,
  households,
  showToastNotification,
  onSuccess
}) {
  const [selectedHub, setSelectedHub] = useState(null);
  const [hubDonations, setHubDonations] = useState([]);
  const [isLoadingFinancials, setIsLoadingFinancials] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Filter hubs that have pending requests
  const pendingHubs = hubs.filter(h => h.pending_capacity_status !== null && h.pending_capacity_status !== undefined);

  // Auto-select first pending hub
  useEffect(() => {
    if (pendingHubs.length > 0 && !selectedHub) {
      setSelectedHub(pendingHubs[0]);
    } else if (pendingHubs.length === 0) {
      setSelectedHub(null);
    }
  }, [hubs, pendingHubs, selectedHub]);

  // Fetch selected hub's financials
  useEffect(() => {
    if (selectedHub) {
      const fetchHubFinancials = async () => {
        setIsLoadingFinancials(true);
        const { data, error } = await supabase
          .from('donations')
          .select('*')
          .eq('hub_id', selectedHub.id)
          .order('transaction_date', { ascending: false });
        if (error) {
          console.error('Error fetching hub donations:', error);
        } else {
          setHubDonations(data || []);
        }
        setIsLoadingFinancials(false);
      };
      fetchHubFinancials();
    } else {
      setHubDonations([]);
    }
  }, [selectedHub]);

  if (!showApprovalModal) return null;

  // Calculations for selected hub
  const servedKkCount = selectedHub 
    ? households.filter(hh => hh.db_assigned_hub_id === selectedHub.id).length 
    : 0;

  const totalBalance = hubDonations.reduce((acc, curr) => {
    if (curr.type === 'IN') return acc + Number(curr.amount);
    return acc - Number(curr.amount);
  }, 0);

  const ratioPerKk = servedKkCount > 0 ? totalBalance / servedKkCount : totalBalance;

  // Determine critical state warning and recommendations
  let recommendationText = 'Kondisi Aman';
  let recommendationColor = '#10b981';
  let recommendationIcon = 'fa-check-circle';
  
  if (ratioPerKk < 100000) {
    recommendationText = 'SANGAT KRITIS (Rekomendasi Setujui: Valid)';
    recommendationColor = '#ef4444';
    recommendationIcon = 'fa-exclamation-triangle';
  } else if (ratioPerKk < 300000) {
    recommendationText = 'KRITIS / SEDANG (Rekomendasi Setujui: Cukup Valid)';
    recommendationColor = '#f59e0b';
    recommendationIcon = 'fa-circle-info';
  } else {
    recommendationText = 'KONDISI SEHAT (Rekomendasi Tolak: Dana Cukup)';
    recommendationColor = '#3b82f6';
    recommendationIcon = 'fa-shield-halved';
  }

  // Handle decisions
  const handleDecision = async (hubId, approve) => {
    if (isSubmitting) return;
    setIsSubmitting(true);
    
    try {
      if (approve) {
        // Overwrite main status and reset pending status
        const { error } = await supabase
          .from('hubs')
          .update({ 
            capacity_status: selectedHub.pending_capacity_status,
            pending_capacity_status: null 
          })
          .eq('id', hubId);

        if (error) {
          alert(`Gagal menyetujui pengajuan: ${error.message}`);
        } else {
          showToastNotification(`Berhasil menyetujui perubahan kapasitas menjadi overloaded!`);
          setSelectedHub(null);
          onSuccess();
        }
      } else {
        // Just reject by resetting pending status
        const { error } = await supabase
          .from('hubs')
          .update({ pending_capacity_status: null })
          .eq('id', hubId);

        if (error) {
          alert(`Gagal menolak pengajuan: ${error.message}`);
        } else {
          showToastNotification(`Pengajuan perubahan kapasitas ditolak.`);
          setSelectedHub(null);
          onSuccess();
        }
      }
    } catch (e) {
      console.error(e);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="modal-overlay active">
      <div className="modal-content" style={{ maxWidth: '950px', width: '95%' }}>
        <div className="modal-header">
          <h2><i className="fas fa-list-check text-primary"></i> Antrean Verifikasi Kapasitas Hub</h2>
          <button className="close-btn" onClick={() => setShowApprovalModal(false)}>&times;</button>
        </div>
        
        <div className="modal-body" style={{ display: 'grid', gridTemplateColumns: '300px 1fr', gap: '20px', maxHeight: '70vh', overflowY: 'auto' }}>
          
          {/* Left Column: Pending Hubs List */}
          <div style={{ borderRight: '1px solid #e2e8f0', paddingRight: '15px' }}>
            <h3 style={{ margin: '0 0 15px 0', fontSize: '1rem', color: 'var(--text-muted)' }}>Daftar Pengajuan ({pendingHubs.length})</h3>
            {pendingHubs.length === 0 ? (
              <p style={{ textAlign: 'center', color: '#94a3b8', fontSize: '0.9rem', padding: '40px 10px' }}>
                Tidak ada pengajuan perubahan kapasitas saat ini.
              </p>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
                {pendingHubs.map(hub => {
                  const isSelected = selectedHub?.id === hub.id;
                  return (
                    <div 
                      key={hub.id}
                      onClick={() => setSelectedHub(hub)}
                      style={{
                        padding: '12px',
                        borderRadius: '8px',
                        border: isSelected ? '2px solid var(--primary)' : '1px solid #e2e8f0',
                        background: isSelected ? 'rgba(59, 130, 246, 0.05)' : 'white',
                        cursor: 'pointer',
                        transition: 'all 0.2s'
                      }}
                    >
                      <strong style={{ display: 'block', fontSize: '0.9rem', color: '#1e293b' }}>{hub.name}</strong>
                      <span style={{ fontSize: '0.75rem', color: '#64748b' }}>{hub.type}</span>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '8px' }}>
                        <span style={{ fontSize: '0.7rem', padding: '2px 6px', background: '#fef3c7', color: '#d97706', borderRadius: '4px', fontWeight: 'bold' }}>
                          Minta: {hub.pending_capacity_status === 'overloaded' ? 'Overloaded' : 'Normal'}
                        </span>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>

          {/* Right Column: Selected Hub Details and Ratio Analysis */}
          <div>
            {selectedHub ? (
              <div>
                {/* Hub Header */}
                <div style={{ marginBottom: '20px' }}>
                  <h3 style={{ margin: '0 0 4px 0', fontSize: '1.25rem', color: '#1e293b' }}>{selectedHub.name}</h3>
                  <p style={{ margin: 0, fontSize: '0.8rem', color: '#64748b' }}>
                    <i className="fas fa-map-marker-alt" style={{ marginRight: '6px' }}></i>{selectedHub.address || 'Alamat belum diatur'}
                  </p>
                </div>

                {/* Metrics Cards Grid */}
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '15px', marginBottom: '20px' }}>
                  
                  {/* Card 1: Assigned KK */}
                  <div style={{ background: '#f8fafc', padding: '15px', borderRadius: '8px', border: '1px solid #e2e8f0' }}>
                    <span style={{ display: 'block', fontSize: '0.75rem', color: '#64748b', fontWeight: 'bold', textTransform: 'uppercase' }}>KK Terlayani</span>
                    <strong style={{ fontSize: '1.5rem', color: '#1e293b' }}>{servedKkCount} <span style={{ fontSize: '0.85rem', fontWeight: 'normal' }}>Keluarga</span></strong>
                  </div>

                  {/* Card 2: Donation Balance */}
                  <div style={{ background: '#f8fafc', padding: '15px', borderRadius: '8px', border: '1px solid #e2e8f0' }}>
                    <span style={{ display: 'block', fontSize: '0.75rem', color: '#64748b', fontWeight: 'bold', textTransform: 'uppercase' }}>Saldo Kas</span>
                    {isLoadingFinancials ? (
                      <span style={{ fontSize: '0.9rem', color: '#94a3b8' }}>Memuat data...</span>
                    ) : (
                      <strong style={{ fontSize: '1.5rem', color: totalBalance >= 0 ? '#10b981' : '#ef4444' }}>
                        Rp{totalBalance.toLocaleString('id-ID')}
                      </strong>
                    )}
                  </div>

                  {/* Card 3: Financial Ratio */}
                  <div style={{ background: '#f8fafc', padding: '15px', borderRadius: '8px', border: '1px solid #e2e8f0' }}>
                    <span style={{ display: 'block', fontSize: '0.75rem', color: '#64748b', fontWeight: 'bold', textTransform: 'uppercase' }}>Rasio Dana / KK</span>
                    {isLoadingFinancials ? (
                      <span style={{ fontSize: '0.9rem', color: '#94a3b8' }}>Memuat data...</span>
                    ) : (
                      <strong style={{ fontSize: '1.25rem', color: ratioPerKk < 100000 ? '#ef4444' : '#1e293b' }}>
                        Rp{Math.round(ratioPerKk).toLocaleString('id-ID')} <span style={{ fontSize: '0.75rem', fontWeight: 'normal', color: '#64748b' }}>/ KK</span>
                      </strong>
                    )}
                  </div>

                </div>

                {/* Audit & Recommendation Box */}
                <div style={{ 
                  background: 'rgba(0,0,0,0.02)', 
                  padding: '15px', 
                  borderRadius: '8px', 
                  borderLeft: `4px solid ${recommendationColor}`, 
                  marginBottom: '20px',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '12px'
                }}>
                  <i className={`fas ${recommendationIcon}`} style={{ color: recommendationColor, fontSize: '1.5rem' }}></i>
                  <div>
                    <strong style={{ display: 'block', fontSize: '0.85rem', color: '#1e293b' }}>Rekomendasi Analitis Pusat:</strong>
                    <span style={{ fontSize: '0.8rem', fontWeight: 'bold', color: recommendationColor }}>{recommendationText}</span>
                  </div>
                </div>

                {/* Last 5 Transactions List */}
                <div style={{ background: '#f8fafc', padding: '15px', borderRadius: '8px', border: '1px solid #e2e8f0', marginBottom: '25px' }}>
                  <h4 style={{ margin: '0 0 10px 0', fontSize: '0.9rem', color: '#1e293b' }}><i className="fas fa-history"></i> Riwayat Transaksi Terakhir</h4>
                  {isLoadingFinancials ? (
                    <p style={{ textAlign: 'center', color: '#94a3b8', fontSize: '0.85rem', padding: '10px 0' }}>Memuat data keuangan...</p>
                  ) : hubDonations.length === 0 ? (
                    <p style={{ textAlign: 'center', color: '#94a3b8', fontSize: '0.85rem', padding: '10px 0' }}>Tidak ada riwayat transaksi kas.</p>
                  ) : (
                    <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.8rem' }}>
                      <thead>
                        <tr style={{ background: '#e2e8f0', textAlign: 'left' }}>
                          <th style={{ padding: '6px', borderBottom: '1px solid #cbd5e1' }}>Tanggal</th>
                          <th style={{ padding: '6px', borderBottom: '1px solid #cbd5e1' }}>Keterangan</th>
                          <th style={{ padding: '6px', borderBottom: '1px solid #cbd5e1', textAlign: 'right' }}>Nominal</th>
                        </tr>
                      </thead>
                      <tbody>
                        {hubDonations.slice(0, 5).map(donation => (
                          <tr key={donation.id} style={{ borderBottom: '1px solid #e2e8f0' }}>
                            <td style={{ padding: '6px', color: '#475569' }}>{donation.transaction_date}</td>
                            <td style={{ padding: '6px', color: '#1e293b' }}>{donation.description}</td>
                            <td style={{ padding: '6px', textAlign: 'right', fontWeight: 'bold', color: donation.type === 'IN' ? '#10b981' : '#ef4444' }}>
                              {donation.type === 'IN' ? '+' : '-'} Rp{Number(donation.amount).toLocaleString('id-ID')}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  )}
                </div>

                {/* Actions Buttons */}
                <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '12px' }}>
                  <button 
                    className="btn btn-secondary"
                    onClick={() => handleDecision(selectedHub.id, false)}
                    disabled={isSubmitting}
                    style={{
                      padding: '10px 20px',
                      background: '#fee2e2',
                      color: '#b91c1c',
                      border: '1px solid #fecaca',
                      borderRadius: '6px',
                      cursor: 'pointer',
                      fontWeight: '600',
                      fontSize: '0.85rem'
                    }}
                  >
                    <i className="fas fa-times-circle"></i> Tolak Pengajuan
                  </button>
                  <button 
                    className="btn btn-primary"
                    onClick={() => handleDecision(selectedHub.id, true)}
                    disabled={isSubmitting}
                    style={{
                      padding: '10px 20px',
                      background: '#10b981',
                      color: 'white',
                      border: 'none',
                      borderRadius: '6px',
                      cursor: 'pointer',
                      fontWeight: '600',
                      fontSize: '0.85rem'
                    }}
                  >
                    <i className="fas fa-check-circle"></i> Setujui Pengajuan
                  </button>
                </div>
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '40vh', color: '#94a3b8' }}>
                <i className="fas fa-arrow-left" style={{ fontSize: '2rem', marginBottom: '10px' }}></i>
                <p style={{ margin: 0 }}>Silakan pilih salah satu Hub dari antrean di sebelah kiri untuk diaudit.</p>
              </div>
            )}
          </div>

        </div>
      </div>
    </div>
  );
}
