import { useState, useEffect, useCallback } from 'react';

import { DATA_KEY_ACCESS_TOKEN } from '../constants/app';
import { tokenService } from '../services/TokenService';
import { contactApi } from '../api/contactApi';

import './ViewContact.css';

const ViewContact = ({ isOpen, onClose, title = 'View Contacts' }) => {
  const [contacts, setContacts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [lastUpdated, setLastUpdated] = useState(null);
  const [searchTerm, setSearchTerm] = useState('');

  // Fetch contacts when the popup opens
  const fetchContacts = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      const accessToken = localStorage.getItem(DATA_KEY_ACCESS_TOKEN);
      const userId = tokenService.getUserId();

      if (!accessToken) {
        throw new Error('Authentication required. Please log in again.');
      }

      const result = await contactApi.getContactsWithUserId(
        userId,
        tokenService.bearerToken()
      );

      if (result.data) {
        setContacts(result.data);
        setLastUpdated(new Date());
      } else {
        setLoading(false);
        throw new Error(result.message || 'Failed to load contacts');
      }
    } catch (err) {
      console.error('Error fetching contacts:', err);
      setError(err.message || 'Failed to load contacts. Please try again.');
      setContacts([]);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (isOpen) {
      console.log('This is when I would fetch contacts');
      fetchContacts();
    }
  }, [isOpen, fetchContacts]);

  // Handle refresh button click
  const handleRefresh = () => {
    fetchContacts();
  };

  // Filter contacts based on search term
  const filteredContacts = contacts.filter((contact) => {
    const searchLower = searchTerm.toLowerCase();
    return (
      (contact.phone_number &&
        contact.phone_number.toLowerCase().includes(searchLower)) ||
      (contact.first_name &&
        contact.first_name.toLowerCase().includes(searchLower)) ||
      (contact.last_name &&
        contact.last_name.toLowerCase().includes(searchLower)) ||
      (contact.id && contact.id.toString().includes(searchTerm))
    );
  });

  // Format phone number for display
  const formatPhoneNumber = (phone) => {
    if (!phone) return 'N/A';
    // Simple formatting - you can customize this
    const cleaned = phone.replace(/\D/g, '');
    if (cleaned.length === 10) {
      return `(${cleaned.slice(0, 3)}) ${cleaned.slice(3, 6)}-${cleaned.slice(6)}`;
    }
    return phone;
  };

  // Format timestamp
  const formatLastUpdated = () => {
    if (!lastUpdated) return 'Never';
    return lastUpdated.toLocaleTimeString([], {
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  if (!isOpen) return null;

  return (
    <div className="contact-modal-overlay" onClick={onClose}>
      <div className="contact-modal" onClick={(e) => e.stopPropagation()}>
        <div className="contact-card">
          <div className="contact-header">
            <h2 className="contact-title">{title}</h2>
            <button className="close-btn" onClick={onClose} aria-label="Close">
              ×
            </button>
          </div>

          <div className="contact-form">
            {error && (
              <div className="submit-error">
                <div style={{ marginBottom: '8px' }}>{error}</div>
                <button
                  onClick={handleRefresh}
                  style={{
                    background: '#ef4444',
                    color: 'white',
                    border: 'none',
                    borderRadius: '4px',
                    padding: '6px 12px',
                    cursor: 'pointer',
                    fontSize: '12px',
                  }}
                >
                  Retry Now
                </button>
              </div>
            )}

            {loading ? (
              <div style={{ textAlign: 'center', padding: '40px' }}>
                <div className="loading-spinner" />
                <p style={{ marginTop: '20px', color: '#4b5563' }}>
                  Loading contacts...
                </p>
              </div>
            ) : (
              <>
                {/* Controls */}
                <div
                  style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    marginBottom: '20px',
                    flexWrap: 'wrap',
                    gap: '10px',
                  }}
                >
                  <button
                    onClick={handleRefresh}
                    style={{
                      background: '#f3f4f6',
                      color: '#4b5563',
                      border: '1px solid #e5e7eb',
                      borderRadius: '6px',
                      padding: '8px 16px',
                      cursor: 'pointer',
                      fontSize: '14px',
                      display: 'flex',
                      alignItems: 'center',
                      gap: '8px',
                    }}
                  >
                    <span>⟳</span> Refresh
                  </button>

                  {/* Search Input */}
                  <input
                    type="text"
                    placeholder="Search contacts..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    style={{
                      flex: 1,
                      minWidth: '200px',
                      maxWidth: '300px',
                      padding: '8px 12px',
                      border: '1px solid #e5e7eb',
                      borderRadius: '6px',
                      fontSize: '14px',
                    }}
                  />

                  <div
                    style={{
                      fontSize: '12px',
                      color: '#6b7280',
                      display: 'flex',
                      alignItems: 'center',
                      gap: '8px',
                    }}
                  >
                    <span>Updated: {formatLastUpdated()}</span>
                    <span
                      style={{
                        display: 'inline-block',
                        width: '8px',
                        height: '8px',
                        borderRadius: '50%',
                        background: lastUpdated ? '#10b981' : '#9ca3af',
                      }}
                    />
                  </div>
                </div>

                {/* Contacts List */}
                {filteredContacts.length === 0 ? (
                  <div
                    style={{
                      textAlign: 'center',
                      padding: '40px',
                      color: '#4b5563',
                    }}
                  >
                    <div style={{ fontSize: '48px', marginBottom: '16px' }}>
                      📭
                    </div>
                    <p
                      style={{
                        fontSize: '18px',
                        fontWeight: '500',
                        marginBottom: '8px',
                      }}
                    >
                      {searchTerm
                        ? 'No matching contacts found'
                        : 'No contacts available'}
                    </p>
                    <p style={{ marginBottom: '20px' }}>
                      {searchTerm
                        ? 'Try a different search term'
                        : 'Add your first contact to get started'}
                    </p>
                    {searchTerm && (
                      <button
                        onClick={() => setSearchTerm('')}
                        style={{
                          background: '#f3f4f6',
                          color: '#4b5563',
                          border: '1px solid #e5e7eb',
                          borderRadius: '6px',
                          padding: '8px 16px',
                          cursor: 'pointer',
                          fontSize: '14px',
                          marginBottom: '10px',
                        }}
                      >
                        Clear Search
                      </button>
                    )}
                  </div>
                ) : (
                  <>
                    <div
                      style={{
                        maxHeight: '400px',
                        overflowY: 'auto',
                        border: '1px solid #e5e7eb',
                        borderRadius: '8px',
                        background: '#fafafa',
                      }}
                    >
                      <div style={{ padding: '4px' }}>
                        {filteredContacts.map((contact, index) => (
                          <div
                            key={contact.id}
                            style={{
                              padding: '16px',
                              borderBottom:
                                index < filteredContacts.length - 1
                                  ? '1px solid #e5e7eb'
                                  : 'none',
                              background: 'white',
                              transition: 'all 0.2s',
                            }}
                          >
                            <div
                              style={{
                                display: 'flex',
                                justifyContent: 'space-between',
                                alignItems: 'flex-start',
                                marginBottom: '8px',
                              }}
                            >
                              <div
                                style={{
                                  display: 'flex',
                                  alignItems: 'center',
                                  gap: '12px',
                                }}
                              >
                                <span
                                  style={{
                                    background: '#667eea',
                                    color: 'white',
                                    width: '28px',
                                    height: '28px',
                                    borderRadius: '50%',
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    fontSize: '12px',
                                    fontWeight: '600',
                                  }}
                                >
                                  {index + 1}
                                </span>
                                <div>
                                  <h4
                                    style={{
                                      margin: 0,
                                      color: '#111827',
                                      fontSize: '16px',
                                      fontWeight: '600',
                                    }}
                                  >
                                    {contact.first_name || contact.last_name
                                      ? `${contact.first_name || ''} ${contact.last_name || ''}`.trim()
                                      : 'Unnamed Contact'}
                                  </h4>
                                  <p
                                    style={{
                                      margin: '4px 0 0 0',
                                      color: '#6b7280',
                                      fontSize: '14px',
                                    }}
                                  >
                                    📱 {formatPhoneNumber(contact.phone_number)}
                                  </p>
                                </div>
                              </div>
                              <span
                                style={{
                                  fontSize: '12px',
                                  color: '#9ca3af',
                                  background: '#f3f4f6',
                                  padding: '2px 8px',
                                  borderRadius: '4px',
                                }}
                              >
                                ID: {contact.id}
                              </span>
                            </div>

                            {/* Additional info */}
                            <div
                              style={{
                                marginLeft: '40px',
                                fontSize: '13px',
                                color: '#6b7280',
                              }}
                            >
                              {contact.created_at && (
                                <div style={{ marginTop: '4px' }}>
                                  Created:{' '}
                                  {new Date(
                                    contact.created_at
                                  ).toLocaleDateString()}
                                </div>
                              )}
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>

                    {/* Summary */}
                    <div
                      style={{
                        marginTop: '20px',
                        padding: '12px 16px',
                        background: '#f0f9ff',
                        borderRadius: '6px',
                        border: '1px solid #bae6fd',
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                        fontSize: '14px',
                      }}
                    >
                      <div style={{ color: '#0369a1' }}>
                        <strong>{filteredContacts.length}</strong> contact
                        {filteredContacts.length !== 1 ? 's' : ''}
                        {searchTerm && ` (filtered from ${contacts.length})`}
                      </div>
                      <div style={{ color: '#0284c7', fontSize: '12px' }}>
                        {searchTerm
                          ? 'Showing search results'
                          : 'All contacts loaded'}
                      </div>
                    </div>
                  </>
                )}
              </>
            )}

            <div className="form-actions">
              <button
                type="button"
                className="cancel-btn"
                onClick={onClose}
                disabled={loading}
              >
                Close
              </button>
              <button
                type="button"
                className="submit-btn"
                onClick={handleRefresh}
                disabled={loading}
              >
                {loading ? 'Refreshing...' : 'Refresh List'}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ViewContact;
