'use client';

import { useEffect, useState } from 'react';

interface UserRow {
  id: string;
  current_page: string;
  progress: number;
  status: 'in_progress' | 'completed' | 'purchased';
  plan: string | null;
  utm_ad: string | null;
  created_at: string;
  updated_at: string;
}

const statusLabel = (row: UserRow): string => {
  if (row.status === 'purchased') return `purchased: ${row.plan ?? '?'}`;
  if (row.status === 'completed') return 'onb completed';
  return `${row.progress}%`;
};

const statusColor = (status: string): string => {
  if (status === 'purchased') return '#22c55e';
  if (status === 'completed') return '#3b82f6';
  return '#f59e0b';
};

export default function DashboardAyaPage() {
  const [users, setUsers] = useState<UserRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchData = () => {
    setLoading(true);
    fetch('/api/dashboard_aya')
      .then((r) => r.json())
      .then((data) => {
        setUsers(data.users ?? []);
        setError(null);
      })
      .catch(() => setError('Failed to load data'))
      .finally(() => setLoading(false));
  };

  useEffect(() => {
    fetchData();
    const interval = setInterval(fetchData, 15000);
    return () => clearInterval(interval);
  }, []);

  const totalUsers = users.length;
  const completed = users.filter((u) => u.status === 'completed' || u.status === 'purchased').length;
  const purchased = users.filter((u) => u.status === 'purchased').length;
  const avgProgress = totalUsers > 0
    ? Math.round(users.reduce((sum, u) => sum + u.progress, 0) / totalUsers)
    : 0;

  return (
    <main style={styles.page}>
      <h1 style={styles.title}>Ayatique Onboarding Dashboard</h1>

      <div style={styles.statsRow}>
        <div style={styles.statCard}>
          <span style={styles.statNumber}>{totalUsers}</span>
          <span style={styles.statLabel}>Total Users</span>
        </div>
        <div style={styles.statCard}>
          <span style={styles.statNumber}>{avgProgress}%</span>
          <span style={styles.statLabel}>Avg Progress</span>
        </div>
        <div style={styles.statCard}>
          <span style={styles.statNumber}>{completed}</span>
          <span style={styles.statLabel}>Completed</span>
        </div>
        <div style={styles.statCard}>
          <span style={styles.statNumber}>{purchased}</span>
          <span style={styles.statLabel}>Purchased</span>
        </div>
      </div>

      <div style={styles.toolbar}>
        <button type="button" onClick={fetchData} style={styles.refreshBtn}>
          Refresh
        </button>
        {loading && <span style={styles.loadingText}>Loading...</span>}
        {error && <span style={styles.errorText}>{error}</span>}
      </div>

      <div style={styles.tableWrapper}>
        <table style={styles.table}>
          <thead>
            <tr>
              <th style={styles.th}>ID</th>
              <th style={styles.th}>Action</th>
              <th style={styles.th}>Current Page</th>
              <th style={styles.th}>UTM Ad</th>
              <th style={styles.th}>Created</th>
              <th style={styles.th}>Last Active</th>
            </tr>
          </thead>
          <tbody>
            {users.map((user) => (
              <tr key={user.id} style={styles.tr}>
                <td style={styles.td}>
                  <code style={styles.userId}>{user.id.slice(0, 8)}</code>
                </td>
                <td style={styles.td}>
                  <span style={{ ...styles.badge, backgroundColor: statusColor(user.status) }}>
                    {statusLabel(user)}
                  </span>
                </td>
                <td style={styles.td}>{user.current_page}</td>
                <td style={styles.td}>{user.utm_ad ?? '-'}</td>
                <td style={styles.td}>{new Date(user.created_at).toLocaleString()}</td>
                <td style={styles.td}>{new Date(user.updated_at).toLocaleString()}</td>
              </tr>
            ))}
            {users.length === 0 && !loading && (
              <tr>
                <td colSpan={6} style={{ ...styles.td, textAlign: 'center', opacity: 0.5 }}>
                  No users tracked yet
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </main>
  );
}

const styles: Record<string, React.CSSProperties> = {
  page: {
    maxWidth: 1100,
    margin: '0 auto',
    padding: '40px 20px',
    fontFamily: "'Plus Jakarta Sans', system-ui, sans-serif",
  },
  title: {
    fontSize: 28,
    fontWeight: 700,
    marginBottom: 24,
  },
  statsRow: {
    display: 'grid',
    gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))',
    gap: 16,
    marginBottom: 24,
  },
  statCard: {
    background: '#111629',
    borderRadius: 12,
    padding: '20px 16px',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    gap: 4,
  },
  statNumber: {
    fontSize: 32,
    fontWeight: 700,
  },
  statLabel: {
    fontSize: 13,
    color: '#b3bacd',
  },
  toolbar: {
    display: 'flex',
    alignItems: 'center',
    gap: 12,
    marginBottom: 16,
  },
  refreshBtn: {
    padding: '8px 20px',
    borderRadius: 8,
    border: 'none',
    background: '#3b82f6',
    color: '#fff',
    fontWeight: 600,
    cursor: 'pointer',
    fontSize: 14,
  },
  loadingText: { color: '#b3bacd', fontSize: 13 },
  errorText: { color: '#ef4444', fontSize: 13 },
  tableWrapper: {
    overflowX: 'auto',
    borderRadius: 12,
    border: '1px solid rgba(255,255,255,0.08)',
  },
  table: {
    width: '100%',
    borderCollapse: 'collapse',
  },
  th: {
    textAlign: 'left',
    padding: '12px 16px',
    fontSize: 12,
    fontWeight: 600,
    textTransform: 'uppercase',
    letterSpacing: '0.05em',
    color: '#b3bacd',
    borderBottom: '1px solid rgba(255,255,255,0.08)',
    background: '#111629',
  },
  tr: {
    borderBottom: '1px solid rgba(255,255,255,0.04)',
  },
  td: {
    padding: '10px 16px',
    fontSize: 14,
    whiteSpace: 'nowrap',
  },
  userId: {
    fontFamily: 'monospace',
    fontSize: 13,
    color: '#93a3bf',
  },
  badge: {
    display: 'inline-block',
    padding: '3px 10px',
    borderRadius: 6,
    fontSize: 12,
    fontWeight: 600,
    color: '#fff',
  },
};
