'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { 
  getLeftColumnFields, 
  getRightColumnFields, 
  getStatusBadgeClass, 
  isCertificateDocument,
  hasDocumentContent,
  formatDate,
  formatDateTime,
  formatCurrency,
  type TransactionField
} from '@/lib/transactionHelpers';
import { apiClient } from '@/lib/api';

interface TransactionDetailsProps {
  transaction: any;
  onViewDocument: (documentNumber: string, documentId: number) => void;
  onViewAllPages: (transactionId: number) => void;
  onViewDocumentsGallery: (transactionId: number) => void;
  onViewParty: (partyId: number) => void;
  onViewProperty: (propertyNumber: string) => void;
}

type TabType = 'general' | 'history' | 'fees' | 'payment';

export default function TransactionDetails({ 
  transaction, 
  onViewDocument, 
  onViewAllPages,
  onViewDocumentsGallery,
  onViewParty,
  onViewProperty
}: TransactionDetailsProps) {
  const router = useRouter();
  const [activeTab, setActiveTab] = useState<TabType>('general');
  const [payments, setPayments] = useState<any>(null);
  const [fees, setFees] = useState<any>(null);
  const [history, setHistory] = useState<any>(null);
  const [loadingPayments, setLoadingPayments] = useState(false);
  const [loadingFees, setLoadingFees] = useState(false);
  const [loadingHistory, setLoadingHistory] = useState(false);

  // Handle property click - navigate to property page
  const handlePropertyClick = (propertyNumber: string) => {
    router.push(`/property/${propertyNumber}`);
  };

  // Fetch payments when Payment tab is active
  useEffect(() => {
    if (activeTab === 'payment' && transaction?.id && !payments) {
      fetchPayments();
    }
  }, [activeTab, transaction?.id]);

  // Fetch fees when Fees tab is active
  useEffect(() => {
    if (activeTab === 'fees' && transaction?.id && !fees) {
      fetchFees();
    }
  }, [activeTab, transaction?.id]);

  // Fetch history when History tab is active
  useEffect(() => {
    if (activeTab === 'history' && transaction?.id && !history) {
      fetchHistory();
    }
  }, [activeTab, transaction?.id]);

  const fetchPayments = async () => {
    setLoadingPayments(true);
    try {
      const response = await apiClient.get(`/transactions/${transaction.id}/payments`);
      setPayments(response.data);
    } catch (error) {
      console.error('Error fetching payments:', error);
    } finally {
      setLoadingPayments(false);
    }
  };

  const fetchFees = async () => {
    setLoadingFees(true);
    try {
      const response = await apiClient.get(`/transactions/${transaction.id}/fees`);
      setFees(response.data);
    } catch (error) {
      console.error('Error fetching fees:', error);
    } finally {
      setLoadingFees(false);
    }
  };

  const fetchHistory = async () => {
    setLoadingHistory(true);
    try {
      const response = await apiClient.get(`/transactions/${transaction.id}/history`);
      setHistory(response.data);
    } catch (error) {
      console.error('Error fetching history:', error);
    } finally {
      setLoadingHistory(false);
    }
  };

  if (!transaction) {
    return (
      <div className="empty-state" style={{ background: '#fef6e4' }}>
        <div className="empty-state-icon">📝</div>
        <div className="empty-state-text">No record selected</div>
        <div className="empty-state-subtext">Select a record from search results to view details</div>
      </div>
    );
  }

  const totalDocuments = transaction.summary?.total_documents || 0;
  const totalPages = transaction.summary?.total_pages || 0;
  const totalParties = transaction.summary?.total_parties || 0;
  const totalProperties = transaction.summary?.total_properties || 0;

  const leftFields = getLeftColumnFields(transaction);
  const rightFields = getRightColumnFields(transaction);
  
  // Debug logging for transaction data
  console.log('📊 Transaction Data:', {
    id: transaction.id,
    transaction_number: transaction.transaction_number,
    start_date: transaction.start_date,
    application_date: transaction.application_date,
    complete_date: transaction.complete_date,
    registration_date: transaction.registration_date,
  });
  console.log('📋 Right Column Fields:', rightFields);

  return (
    <div style={{ background: '#fef6e4', minHeight: '100vh', padding: '20px' }}>
      {/* Transaction Details Header */}
      <div className="search-card" style={{ marginBottom: '30px', background: '#ffffff', border: '2px solid #e8dcc4' }}>
        <h2 className="section-title" style={{ marginBottom: '25px', fontSize: '1.5em', color: '#1f2937' }}>
          📄 Transaction Details
        </h2>
        
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '40px' }}>
          <div>
            {leftFields.map((field, index) => (
              <DetailField key={index} field={field} isHighlight={index === 0} transaction={transaction} />
            ))}
          </div>
          <div>
            {rightFields.map((field, index) => (
              <DetailField key={index} field={field} transaction={transaction} />
            ))}
          </div>
        </div>
      </div>

      {/* Tabs Navigation */}
      <div style={{ 
        borderBottom: '3px solid #10b981', 
        marginBottom: '30px',
        display: 'flex',
        gap: '8px',
        background: '#ffffff',
        borderRadius: '12px 12px 0 0',
        padding: '10px 10px 0 10px'
      }}>
        <TabButton active={activeTab === 'general'} onClick={() => setActiveTab('general')} label="General" />
        <TabButton active={activeTab === 'history'} onClick={() => setActiveTab('history')} label="History" />
        <TabButton active={activeTab === 'fees'} onClick={() => setActiveTab('fees')} label="Fees" />
        <TabButton active={activeTab === 'payment'} onClick={() => setActiveTab('payment')} label="Payment" />
      </div>

      {/* Tab Content */}
      <div style={{ background: '#ffffff', borderRadius: '0 0 12px 12px', padding: '20px', border: '2px solid #e8dcc4' }}>
        {activeTab === 'general' && (
          <GeneralTab 
            transaction={transaction}
            totalDocuments={totalDocuments}
            totalPages={totalPages}
            totalParties={totalParties}
            totalProperties={totalProperties}
            onViewDocument={onViewDocument}
            onViewAllPages={onViewAllPages}
            onViewDocumentsGallery={onViewDocumentsGallery}
            onViewParty={onViewParty}
            onViewProperty={handlePropertyClick}
          />
        )}
        {activeTab === 'history' && <HistoryTab history={history} loading={loadingHistory} />}
        {activeTab === 'fees' && <FeesTab fees={fees} loading={loadingFees} />}
        {activeTab === 'payment' && <PaymentTab payments={payments} loading={loadingPayments} />}
      </div>
    </div>
  );
}

// Helper Components
function DetailField({ field, isHighlight, transaction }: { field: TransactionField; isHighlight?: boolean; transaction: any }) {
  const displayValue = field.formatter ? field.formatter(field.value) : (field.value || '');
  
  // Debug logging for Transaction Start Date
  if (field.label === 'Transaction Start Date') {
    console.log('🔍 Transaction Start Date Debug:', {
      label: field.label,
      rawValue: field.value,
      valueType: typeof field.value,
      hasFormatter: !!field.formatter,
      displayValue: displayValue,
      displayValueType: typeof displayValue,
      transaction_start_date_from_api: transaction?.start_date
    });
  }
  
  if (field.label === 'Status') {
    return (
      <div className="form-group" style={{ marginBottom: '18px' }}>
        <label className="form-label" style={{ fontWeight: '600', color: '#374151', fontSize: '0.875em', marginBottom: '6px', display: 'block' }}>
          {field.label}:
        </label>
        <div style={{ padding: '10px 0' }}>
          <span className={`badge ${getStatusBadgeClass(field.value)}`}>
            {displayValue}
          </span>
        </div>
      </div>
    );
  }

  return (
    <div className="form-group" style={{ marginBottom: '18px' }}>
      <label className="form-label" style={{ fontWeight: '600', color: '#374151', fontSize: '0.875em', marginBottom: '6px', display: 'block' }}>
        {field.label}:
      </label>
      <div style={{ 
        padding: '10px 14px', 
        background: isHighlight ? '#d1fae5' : '#f9fafb', 
        borderRadius: '8px',
        border: isHighlight ? '2px solid #10b981' : '1px solid #e5e7eb',
        fontWeight: isHighlight ? '600' : '400',
        color: displayValue ? '#111827' : '#9ca3af'
      }}>
        {displayValue || '—'}
      </div>
    </div>
  );
}

function TabButton({ active, onClick, label }: { active: boolean; onClick: () => void; label: string }) {
  return (
    <button
      onClick={onClick}
      style={{
        padding: '12px 24px',
        background: active ? '#10b981' : 'transparent',
        color: active ? 'white' : '#374151',
        border: 'none',
        borderBottom: active ? '4px solid #059669' : '4px solid transparent',
        fontWeight: active ? '600' : '500',
        fontSize: '0.95em',
        cursor: 'pointer',
        transition: 'all 0.2s ease',
        borderRadius: '8px 8px 0 0'
      }}
      onMouseOver={(e) => {
        if (!active) {
          e.currentTarget.style.background = '#fef6e4';
          e.currentTarget.style.color = '#10b981';
        }
      }}
      onMouseOut={(e) => {
        if (!active) {
          e.currentTarget.style.background = 'transparent';
          e.currentTarget.style.color = '#374151';
        }
      }}
    >
      {label}
    </button>
  );
}

// Tab Components
function GeneralTab({ transaction, totalDocuments, totalPages, totalParties, totalProperties, onViewDocument, onViewAllPages, onViewDocumentsGallery, onViewParty, onViewProperty }: any) {
  return (
    <div>
      {/* Summary Cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '20px', marginBottom: '30px' }}>
        <SummaryCard count={totalDocuments} label="Document" icon="📋" onClick={() => onViewDocumentsGallery(transaction.id)} clickable tooltip="Click to view document list" />
        <SummaryCard count={totalParties} label="Party" icon="👥" />
        <SummaryCard count={totalProperties} label="Property" icon="🏠" />
        <SummaryCard count={totalPages} label="Total Page" icon="🖼️" onClick={() => onViewAllPages(transaction.id)} clickable tooltip={`Click to view all ${totalPages} images combined into one multipage PDF`} />
      </div>

      {/* Parties Section */}
      {transaction.parties && transaction.parties.length > 0 && (
        <div className="search-section" style={{ marginBottom: '30px', background: '#fefdfb', border: '1px solid #e8dcc4' }}>
          <h3 className="section-title" style={{ color: '#1f2937' }}>👥 Parties ({transaction.parties.length})</h3>
          <div style={{ overflowX: 'auto' }}>
            <table className="results-table">
              <thead>
                <tr>
                  <th>Type</th>
                  <th>Role</th>
                  <th>Name</th>
                  <th>State</th>
                  <th>Local Government Area</th>
                  <th>State of Origin</th>
                  <th>Street Name</th>
                </tr>
              </thead>
              <tbody>
                {transaction.parties.map((party: any, index: number) => (
                  <tr key={index}>
                    <td>{party.person_type_label || ''}</td>
                    <td>{party.legal_role_label || ''}</td>
                    <td>
                      <strong 
                        style={{ color: '#10b981', cursor: 'pointer', textDecoration: 'underline' }}
                        onClick={() => party.id && onViewParty(party.id)}
                        title="Click to view full party details"
                      >
                        {party.full_name || ''}
                      </strong>
                    </td>
                    <td>{party.state_label || ''}</td>
                    <td>{party.lga || ''}</td>
                    <td>{party.state_origin_label || ''}</td>
                    <td>{party.street_name || ''}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Properties Section */}
      {transaction.properties && transaction.properties.length > 0 && (
        <div className="search-section" style={{ marginBottom: '30px', background: '#fefdfb', border: '1px solid #e8dcc4' }}>
          <h3 className="section-title" style={{ color: '#1f2937' }}>🏠 Properties ({transaction.properties.length})</h3>
          <div style={{ overflowX: 'auto' }}>
            <table className="results-table">
              <thead>
                <tr>
                  <th>Property No.</th>
                  <th>Property Type</th>
                  <th>Block Number</th>
                  <th>Plot Number</th>
                  <th>Tracing No.</th>
                  <th>Plan Number</th>
                  <th>Area</th>
                  <th>Measurement Unit</th>
                  <th>UPIN</th>
                  <th>Source/Target</th>
                </tr>
              </thead>
              <tbody>
                {transaction.properties.map((prop: any, index: number) => (
                  <tr key={index}>
                    <td>
                      <strong 
                        style={{ color: '#10b981', cursor: 'pointer', textDecoration: 'underline' }}
                        onClick={() => prop.property_no && onViewProperty(prop.property_no)}
                        title="Click to view full property details"
                      >
                        {prop.property_no || ''}
                      </strong>
                    </td>
                    <td>{prop.property_type_label || ''}</td>
                    <td>{prop.block_no || ''}</td>
                    <td>{prop.plot_no || ''}</td>
                    <td>{prop.tracing_no || ''}</td>
                    <td>{prop.plan_number || ''}</td>
                    <td>{prop.area_size ? prop.area_size.toLocaleString() : ''}</td>
                    <td>{prop.area_unit_label || ''}</td>
                    <td><strong>{prop.upin || ''}</strong></td>
                    <td><span className="badge badge-info">{prop.role || ''}</span></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Documents Section */}
      {transaction.documents && transaction.documents.length > 0 && (
        <div className="search-section" style={{ background: '#fefdfb', border: '1px solid #e8dcc4' }}>
          <h3 className="section-title" style={{ color: '#1f2937' }}>📋 Documents ({transaction.documents.length})</h3>
          <div style={{ overflowX: 'auto' }}>
            <table className="results-table">
              <thead>
                <tr>
                  <th>Document Type</th>
                  <th>Document No.</th>
                  <th>Date Issued</th>
                  <th>Pages</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {transaction.documents.map((doc: any, index: number) => {
                  const isCert = isCertificateDocument(doc.document_type_label);
                  const hasContent = hasDocumentContent(doc);
                  const isSupporting = !doc.document_number || doc.document_number === 'null';
                  
                  return (
                    <tr key={index} style={isCert ? { background: 'rgba(16, 185, 129, 0.08)' } : {}}>
                      <td>
                        <strong>{doc.document_type_label || ''}</strong>
                        {isCert && <span className="badge badge-success" style={{ marginLeft: '8px' }}>C of O</span>}
                        {isSupporting && (
                          <span 
                            className="badge" 
                            style={{ 
                              marginLeft: '8px', 
                              background: '#d1fae5', 
                              color: '#065f46',
                              fontSize: '0.75em',
                              padding: '2px 6px'
                            }}
                          >
                            Supporting
                          </span>
                        )}
                      </td>
                      <td>
                        {doc.document_number || (
                          <span style={{ color: '#9ca3af', fontSize: '0.85em', fontStyle: 'italic' }}>
                            —
                          </span>
                        )}
                      </td>
                      <td>{formatDate(doc.date_issued)}</td>
                      <td><span className="badge badge-info">{doc.page_count || 0}</span></td>
                      <td>
                        {hasContent ? (
                          <button 
                            className="btn btn-primary" 
                            onClick={() => onViewDocument(doc.document_number || '', doc.id)}
                            style={{ padding: '6px 14px', fontSize: '0.85em' }}
                            title={isSupporting ? 'View supporting document' : 'View document'}
                          >
                            <span>👁️</span> View
                          </button>
                        ) : (
                          <span style={{ color: '#9ca3af', fontSize: '0.85em' }}>No content</span>
                        )}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}

function HistoryTab({ history, loading }: any) {
  if (loading) {
    return (
      <div style={{ padding: '40px', textAlign: 'center' }}>
        <div className="loading-spinner" />
        <div style={{ marginTop: '20px', color: '#6b7280' }}>Loading transaction history...</div>
      </div>
    );
  }

  if (!history || history.history.length === 0) {
    return (
      <div className="search-section" style={{ background: '#fefdfb', border: '1px solid #e8dcc4' }}>
        <h3 className="section-title" style={{ color: '#1f2937' }}>📜 Transaction History</h3>
        <div style={{ padding: '40px', textAlign: 'center', color: '#6b7280' }}>
          <div style={{ fontSize: '3em', marginBottom: '20px' }}>🕒</div>
          <div style={{ fontSize: '1.1em', marginBottom: '10px' }}>No history data available</div>
        </div>
      </div>
    );
  }

  return (
    <div className="search-section" style={{ background: '#fefdfb', border: '1px solid #e8dcc4' }}>
      <h3 className="section-title" style={{ color: '#1f2937' }}>📜 Transaction History ({history.total_events})</h3>
      <div style={{ overflowX: 'auto' }}>
        <table className="results-table">
          <thead>
            <tr>
              <th style={{ width: '5%' }}>#</th>
              <th style={{ width: '20%' }}>Task</th>
              <th style={{ width: '12%' }}>Actor</th>
              <th style={{ width: '15%' }}>Started</th>
              <th style={{ width: '15%' }}>Completed</th>
              <th style={{ width: '10%' }}>Duration</th>
              <th style={{ width: '23%' }}>Next Transition</th>
            </tr>
          </thead>
          <tbody>
            {history.history.map((event: any, index: number) => {
              const durationHours = event.duration_minutes ? Math.round(event.duration_minutes / 60) : 0;
              const durationDays = Math.floor(durationHours / 24);
              const remainingHours = durationHours % 24;
              const durationText = durationDays > 0 
                ? `${durationDays}d ${remainingHours}h` 
                : `${remainingHours}h`;
              
              return (
                <tr key={event.id} style={{ 
                  background: index % 2 === 0 ? '#ffffff' : '#fafafa'
                }}>
                  <td style={{ fontWeight: '600', color: '#6b7280' }}>{index + 1}</td>
                  <td>
                    <strong style={{ color: '#111827' }}>{event.task_description}</strong>
                  </td>
                  <td>
                    <span style={{ 
                      padding: '4px 8px', 
                      background: '#e0f2fe', 
                      borderRadius: '6px',
                      fontSize: '0.85em',
                      color: '#0369a1'
                    }}>
                      {event.actor}
                    </span>
                  </td>
                  <td style={{ fontSize: '0.9em' }}>{formatDateTime(event.created_date)}</td>
                  <td style={{ fontSize: '0.9em', color: '#059669' }}>
                    {event.completed_date ? formatDateTime(event.completed_date) : '—'}
                  </td>
                  <td>
                    <span style={{ 
                      padding: '4px 8px', 
                      background: '#fef3c7', 
                      borderRadius: '6px',
                      fontSize: '0.85em',
                      color: '#92400e'
                    }}>
                      {durationText}
                    </span>
                  </td>
                  <td style={{ fontSize: '0.85em', color: '#6b7280' }}>
                    {event.transition || '—'}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function FeesTab({ fees, loading }: any) {
  if (loading) {
    return (
      <div style={{ padding: '40px', textAlign: 'center' }}>
        <div className="loading-spinner" />
        <div style={{ marginTop: '20px', color: '#6b7280' }}>Loading fee information...</div>
      </div>
    );
  }

  if (!fees || fees.fees.length === 0) {
    return (
      <div className="search-section" style={{ background: '#fefdfb', border: '1px solid #e8dcc4' }}>
        <h3 className="section-title" style={{ color: '#1f2937' }}>💰 Calculated Fee</h3>
        <div style={{ padding: '40px', textAlign: 'center', color: '#6b7280' }}>
          <div style={{ fontSize: '3em', marginBottom: '20px' }}>💵</div>
          <div style={{ fontSize: '1.1em', marginBottom: '10px' }}>No fees found for this transaction</div>
        </div>
      </div>
    );
  }

  return (
    <div className="search-section" style={{ background: '#fefdfb', border: '1px solid #e8dcc4' }}>
      <h3 className="section-title" style={{ color: '#1f2937' }}>💰 Calculated Fee ({fees.fees.length})</h3>
      <div style={{ overflowX: 'auto' }}>
        <table className="results-table">
          <thead>
            <tr>
              <th>Fee Type</th>
              <th>Fee</th>
              <th>Date of Calculation</th>
              <th>Comment</th>
            </tr>
          </thead>
          <tbody>
            {fees.fees.map((fee: any, index: number) => (
              <tr key={index} style={{ background: index % 2 === 0 ? '#ffffff' : '#fafafa' }}>
                <td><strong>{fee.fee_type}</strong></td>
                <td style={{ fontWeight: '600', color: '#059669' }}>{formatCurrency(fee.fee_amount)}</td>
                <td>{fee.date_calculated ? formatDate(fee.date_calculated) : ''}</td>
                <td style={{ color: '#6b7280', fontSize: '0.9em' }}>{fee.comment || ''}</td>
              </tr>
            ))}
            <tr style={{ background: '#d1fae5', fontWeight: 'bold', borderTop: '3px solid #10b981' }}>
              <td>Total Fees</td>
              <td style={{ color: '#059669', fontSize: '1.2em' }}>{formatCurrency(fees.total_fees)}</td>
              <td></td>
              <td></td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  );
}

function PaymentTab({ payments, loading }: any) {
  if (loading) {
    return (
      <div style={{ padding: '40px', textAlign: 'center' }}>
        <div className="loading-spinner" />
        <div style={{ marginTop: '20px', color: '#6b7280' }}>Loading payment records...</div>
      </div>
    );
  }

  if (!payments || payments.payments.length === 0) {
    return (
      <div className="search-section" style={{ background: '#fefdfb', border: '1px solid #e8dcc4' }}>
        <h3 className="section-title" style={{ color: '#1f2937' }}>💳 Payment</h3>
        <div style={{ padding: '40px', textAlign: 'center', color: '#6b7280' }}>
          <div style={{ fontSize: '3em', marginBottom: '20px' }}>💳</div>
          <div style={{ fontSize: '1.1em', marginBottom: '10px' }}>No payment records found</div>
        </div>
      </div>
    );
  }

  return (
    <div className="search-section" style={{ background: '#fefdfb', border: '1px solid #e8dcc4' }}>
      <h3 className="section-title" style={{ color: '#1f2937' }}>💳 Payment ({payments.payments.length})</h3>
      <div style={{ overflowX: 'auto' }}>
        <table className="results-table">
          <thead>
            <tr>
              <th>F.I. Receipt Number</th>
              <th>Date Paid</th>
              <th>Amount Paid</th>
              <th>Payment Type</th>
              <th>Comment</th>
            </tr>
          </thead>
          <tbody>
            {payments.payments.map((payment: any, index: number) => (
              <tr key={payment.id} style={{ background: index % 2 === 0 ? '#ffffff' : '#fafafa' }}>
                <td><strong>{payment.receipt_no}</strong></td>
                <td>{formatDate(payment.payment_date)}</td>
                <td style={{ fontWeight: '600', color: '#059669' }}>{formatCurrency(payment.amount_paid)}</td>
                <td>{payment.payment_type_label || ''}</td>
                <td style={{ color: '#6b7280', fontSize: '0.9em' }}>{payment.comment || ''}</td>
              </tr>
            ))}
            <tr style={{ background: '#d1fae5', fontWeight: 'bold', borderTop: '3px solid #10b981' }}>
              <td>Total Paid</td>
              <td></td>
              <td style={{ color: '#059669', fontSize: '1.2em' }}>{formatCurrency(payments.total_paid)}</td>
              <td></td>
              <td></td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  );
}

function SummaryCard({ count, label, icon, onClick, clickable, tooltip }: any) {
  const isPlural = count !== 1;
  const pluralLabel = label === 'Party' ? 'Parties' : (label === 'Property' ? 'Properties' : `${label}s`);
  const displayLabel = isPlural ? pluralLabel : label;

  return (
    <div 
      onClick={onClick}
      style={{ 
        background: 'linear-gradient(135deg, #10b981, #059669)', 
        color: 'white', 
        padding: '30px', 
        borderRadius: '12px', 
        boxShadow: '0 4px 15px rgba(16, 185, 129, 0.3)', 
        textAlign: 'center', 
        cursor: clickable ? 'pointer' : 'default',
        transition: 'all 0.3s ease',
        position: 'relative' as const
      }}
      onMouseOver={(e) => {
        if (clickable) {
          e.currentTarget.style.transform = 'translateY(-4px)';
          e.currentTarget.style.boxShadow = '0 8px 25px rgba(16, 185, 129, 0.4)';
        }
      }}
      onMouseOut={(e) => {
        if (clickable) {
          e.currentTarget.style.transform = 'translateY(0)';
          e.currentTarget.style.boxShadow = '0 4px 15px rgba(16, 185, 129, 0.3)';
        }
      }}
      title={tooltip || ''}
    >
      <div style={{ fontSize: '2.5em', fontWeight: 'bold', marginBottom: '5px' }}>{count}</div>
      <div style={{ fontSize: '1em', opacity: 0.9 }}>{displayLabel} {icon}</div>
      {clickable && (
        <div style={{ fontSize: '0.75em', opacity: 0.8, marginTop: '8px', background: 'rgba(255, 255, 255, 0.2)', padding: '4px 8px', borderRadius: '6px' }}>
          Click to view
        </div>
      )}
    </div>
  );
}
