'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { 
  Users, 
  Mail, 
  Calendar, 
  ArrowLeft,
  CheckCircle,
  XCircle,
  ToggleLeft,
  ToggleRight,
  AlertCircle
} from 'lucide-react';

interface Subscriber {
  id: number;
  email: string;
  isActive: boolean;
  createdAt: string;
}

interface Stats {
  total: number;
  active: number;
  inactive: number;
}

export default function SubscribersPage() {
  const [subscribers, setSubscribers] = useState<Subscriber[]>([]);
  const [stats, setStats] = useState<Stats>({ total: 0, active: 0, inactive: 0 });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [toggling, setToggling] = useState<number | null>(null);
  const router = useRouter();

  useEffect(() => {
    // Check if user is authenticated
    const token = localStorage.getItem('adminToken');
    if (!token) {
      router.push('/admin');
      return;
    }

    fetchSubscribers();
  }, [router]);

  const fetchSubscribers = async () => {
    try {
      const token = localStorage.getItem('adminToken');
      const response = await fetch('/api/subscriptions', {
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });

      if (!response.ok) {
        throw new Error('Failed to fetch subscribers');
      }

      const data = await response.json();
      setSubscribers(data.subscribers || []);
      setStats(data.stats || { total: 0, active: 0, inactive: 0 });
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An error occurred');
    } finally {
      setLoading(false);
    }
  };

  const toggleSubscriber = async (subscriberId: number) => {
    setToggling(subscriberId);
    try {
      const token = localStorage.getItem('adminToken');
      const response = await fetch(`/api/subscriptions/${subscriberId}/toggle`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });

      if (response.ok) {
        await fetchSubscribers(); // Refresh the list
      } else {
        const data = await response.json();
        alert(data.message || 'Toggle failed');
      }
    } catch (error) {
      alert('Network error. Please try again.');
    } finally {
      setToggling(null);
    }
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="w-8 h-8 border-2 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
      </div>
    );
  }

  return (
    <div style={{ minHeight: '100vh', backgroundColor: '#6E6362' }}>
      {/* Header */}
      <header style={{
        backgroundColor: 'rgba(57, 64, 83, 0.95)',
        boxShadow: '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)',
        borderBottom: '1px solid #4E4A59'
      }}>
        <div style={{ maxWidth: '80rem', margin: '0 auto', padding: '0 1rem' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '1.5rem 0' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
              <button
                onClick={() => router.push('/admin/dashboard')}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '0.5rem',
                  padding: '0.5rem',
                  color: '#7CAE7A',
                  backgroundColor: 'transparent',
                  border: 'none',
                  cursor: 'pointer'
                }}
              >
                <ArrowLeft style={{ width: '1.25rem', height: '1.25rem' }} />
              </button>
              <div>
                <h1 style={{ fontSize: '1.5rem', fontWeight: 'bold', color: 'white' }}>Email Subscribers</h1>
                <p style={{ fontSize: '0.875rem', color: '#7CAE7A' }}>Manage email notification subscriptions</p>
              </div>
            </div>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main style={{ maxWidth: '80rem', margin: '0 auto', padding: '0 1rem 2rem 1rem' }}>
        {/* Stats Cards */}
        <div style={{ 
          display: 'grid', 
          gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', 
          gap: '1.5rem', 
          marginBottom: '2rem',
          marginTop: '2rem'
        }}>
          <div style={{
            backgroundColor: 'white',
            borderRadius: '0.5rem',
            boxShadow: '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)',
            padding: '1.5rem'
          }}>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <div style={{ flexShrink: 0 }}>
                <Users style={{ height: '2rem', width: '2rem', color: '#394053' }} />
              </div>
              <div style={{ marginLeft: '1rem' }}>
                <p style={{ fontSize: '0.875rem', fontWeight: '500', color: '#6b7280' }}>Total Subscribers</p>
                <p style={{ fontSize: '1.5rem', fontWeight: '600', color: '#111827' }}>{stats.total}</p>
              </div>
            </div>
          </div>

          <div style={{
            backgroundColor: 'white',
            borderRadius: '0.5rem',
            boxShadow: '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)',
            padding: '1.5rem'
          }}>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <div style={{ flexShrink: 0 }}>
                <CheckCircle style={{ height: '2rem', width: '2rem', color: '#059669' }} />
              </div>
              <div style={{ marginLeft: '1rem' }}>
                <p style={{ fontSize: '0.875rem', fontWeight: '500', color: '#6b7280' }}>Active</p>
                <p style={{ fontSize: '1.5rem', fontWeight: '600', color: '#111827' }}>{stats.active}</p>
              </div>
            </div>
          </div>

          <div style={{
            backgroundColor: 'white',
            borderRadius: '0.5rem',
            boxShadow: '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)',
            padding: '1.5rem'
          }}>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <div style={{ flexShrink: 0 }}>
                <XCircle style={{ height: '2rem', width: '2rem', color: '#dc2626' }} />
              </div>
              <div style={{ marginLeft: '1rem' }}>
                <p style={{ fontSize: '0.875rem', fontWeight: '500', color: '#6b7280' }}>Inactive</p>
                <p style={{ fontSize: '1.5rem', fontWeight: '600', color: '#111827' }}>{stats.inactive}</p>
              </div>
            </div>
          </div>
        </div>

        {/* Subscribers List */}
        <div style={{
          backgroundColor: 'white',
          borderRadius: '0.5rem',
          boxShadow: '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)',
          overflow: 'hidden'
        }}>
          <div style={{ padding: '1.5rem', borderBottom: '1px solid #e5e7eb' }}>
            <h2 style={{ fontSize: '1.125rem', fontWeight: '600', color: '#111827' }}>All Subscribers</h2>
            <p style={{ fontSize: '0.875rem', color: '#6b7280', marginTop: '0.25rem' }}>
              Manage email notification subscriptions
            </p>
          </div>

          {error ? (
            <div style={{ padding: '3rem 1.5rem', textAlign: 'center' }}>
              <AlertCircle style={{ width: '3rem', height: '3rem', margin: '0 auto 1rem auto', color: '#dc2626' }} />
              <p style={{ color: '#dc2626', marginBottom: '1rem' }}>{error}</p>
              <button
                onClick={fetchSubscribers}
                style={{
                  padding: '0.5rem 1rem',
                  backgroundColor: '#394053',
                  color: 'white',
                  borderRadius: '0.375rem',
                  border: 'none',
                  cursor: 'pointer'
                }}
              >
                Try Again
              </button>
            </div>
          ) : subscribers.length === 0 ? (
            <div style={{ padding: '3rem 1.5rem', textAlign: 'center' }}>
              <Mail style={{ width: '3rem', height: '3rem', margin: '0 auto 1rem auto', color: '#d1d5db' }} />
              <p style={{ color: '#6b7280' }}>No subscribers found.</p>
            </div>
          ) : (
            <div style={{ overflow: 'auto' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                <thead style={{ backgroundColor: '#f9fafb' }}>
                  <tr>
                    <th style={{ 
                      padding: '0.75rem 1.5rem', 
                      textAlign: 'left', 
                      fontSize: '0.75rem', 
                      fontWeight: '500', 
                      color: '#6b7280', 
                      textTransform: 'uppercase',
                      letterSpacing: '0.05em'
                    }}>
                      Email Address
                    </th>
                    <th style={{ 
                      padding: '0.75rem 1.5rem', 
                      textAlign: 'left', 
                      fontSize: '0.75rem', 
                      fontWeight: '500', 
                      color: '#6b7280', 
                      textTransform: 'uppercase',
                      letterSpacing: '0.05em'
                    }}>
                      Status
                    </th>
                    <th style={{ 
                      padding: '0.75rem 1.5rem', 
                      textAlign: 'left', 
                      fontSize: '0.75rem', 
                      fontWeight: '500', 
                      color: '#6b7280', 
                      textTransform: 'uppercase',
                      letterSpacing: '0.05em'
                    }}>
                      Subscribed
                    </th>
                    <th style={{ 
                      padding: '0.75rem 1.5rem', 
                      textAlign: 'right', 
                      fontSize: '0.75rem', 
                      fontWeight: '500', 
                      color: '#6b7280', 
                      textTransform: 'uppercase',
                      letterSpacing: '0.05em'
                    }}>
                      Actions
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {subscribers.map((subscriber, index) => (
                    <tr 
                      key={subscriber.id}
                      style={{ 
                        borderBottom: index < subscribers.length - 1 ? '1px solid #e5e7eb' : 'none'
                      }}
                    >
                      <td style={{ padding: '1rem 1.5rem' }}>
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                          <Mail style={{ width: '1rem', height: '1rem', color: '#6b7280', marginRight: '0.75rem' }} />
                          <span style={{ fontSize: '0.875rem', color: '#111827' }}>{subscriber.email}</span>
                        </div>
                      </td>
                      <td style={{ padding: '1rem 1.5rem' }}>
                        <span style={{
                          display: 'inline-flex',
                          alignItems: 'center',
                          padding: '0.25rem 0.75rem',
                          borderRadius: '9999px',
                          fontSize: '0.75rem',
                          fontWeight: '500',
                          backgroundColor: subscriber.isActive ? '#dcfce7' : '#fef2f2',
                          color: subscriber.isActive ? '#166534' : '#991b1b'
                        }}>
                          {subscriber.isActive ? 'Active' : 'Inactive'}
                        </span>
                      </td>
                      <td style={{ padding: '1rem 1.5rem' }}>
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                          <Calendar style={{ width: '1rem', height: '1rem', color: '#6b7280', marginRight: '0.5rem' }} />
                          <span style={{ fontSize: '0.875rem', color: '#6b7280' }}>
                            {formatDate(subscriber.createdAt)}
                          </span>
                        </div>
                      </td>
                      <td style={{ padding: '1rem 1.5rem', textAlign: 'right' }}>
                        <button
                          onClick={() => toggleSubscriber(subscriber.id)}
                          disabled={toggling === subscriber.id}
                          style={{
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: '0.5rem',
                            padding: '0.5rem 0.75rem',
                            backgroundColor: subscriber.isActive ? '#fef2f2' : '#dcfce7',
                            color: subscriber.isActive ? '#991b1b' : '#166534',
                            border: `1px solid ${subscriber.isActive ? '#fecaca' : '#bbf7d0'}`,
                            borderRadius: '0.375rem',
                            fontSize: '0.75rem',
                            fontWeight: '500',
                            cursor: toggling === subscriber.id ? 'not-allowed' : 'pointer',
                            opacity: toggling === subscriber.id ? 0.5 : 1
                          }}
                        >
                          {subscriber.isActive ? (
                            <ToggleRight style={{ width: '1rem', height: '1rem' }} />
                          ) : (
                            <ToggleLeft style={{ width: '1rem', height: '1rem' }} />
                          )}
                          {toggling === subscriber.id 
                            ? 'Updating...' 
                            : subscriber.isActive 
                              ? 'Deactivate' 
                              : 'Activate'
                          }
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </main>
    </div>
  );
}
