import { useState, useEffect } from 'react'
import Navbar from '../components/common/Navbar'
import { usersAPI, activityLogsAPI } from '../api/endpoints'

// Brand palette
const TEAL = '#409CA4'
const GREEN = '#5cb85c'
const ORANGE = '#e8713a'
const YELLOW = '#f0ad4e'

const Dashboard = () => {
  const [statsData, setStatsData] = useState(null)
  const [recentLogs, setRecentLogs] = useState([])
  const [logsLimit, setLogsLimit] = useState(20)
  const [autoReload, setAutoReload] = useState(false)
  const [lastUpdated, setLastUpdated] = useState(new Date())
  const [logsLoading, setLogsLoading] = useState(false)

  useEffect(() => {
    const fetchStats = async () => {
      try {
        const response = await usersAPI.getStats()
        setStatsData(response.data.data)
      } catch (error) {
        console.error('Failed to fetch stats:', error)
      }
    }
    fetchStats()
  }, [])

  const fetchRecentLogs = async () => {
    setLogsLoading(true)
    try {
      const res = await activityLogsAPI.getDashboardLogs(logsLimit)
      setRecentLogs(res.data.data || [])
      setLastUpdated(new Date())
    } catch (e) {
      console.error('Failed to load activities', e)
    } finally {
      setLogsLoading(false)
    }
  }

  useEffect(() => {
    fetchRecentLogs()
  }, [logsLimit])

  useEffect(() => {
    let interval
    if (autoReload) {
      interval = setInterval(() => fetchRecentLogs(), 120000)
    }
    return () => clearInterval(interval)
  }, [autoReload, logsLimit])

  const handleExport = async (type) => {
    try {
      const response = await usersAPI.exportUsers(type)
      const url = window.URL.createObjectURL(new Blob([response.data]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', `users_${type}.csv`)
      document.body.appendChild(link)
      link.click()
      link.remove()
    } catch (error) {
      console.error('Export failed', error)
    }
  }

  const stats = [
    { title: 'All User', value: statsData?.user_accounts_role_1 || '0', icon: '👥', color: TEAL, bg: '#eaf5f6' },
    { title: 'All Active Users', value: statsData?.all_users_active || '0', icon: '✅', color: GREEN, bg: '#edf7ed' },
    { title: 'Total Subscriptions', value: statsData?.total_subs || '0', icon: '💳', color: ORANGE, bg: '#fdf0ea' },
    { title: 'Overall Report Counts', value: statsData?.overall_report_counts || '0', icon: '📦', color: TEAL, bg: '#eaf5f6' },
    { title: 'New Subs (Last 7 Days)', value: statsData?.new_subs_last_7_days || '0', icon: '🗓️', color: YELLOW, bg: '#fdf6e3' },
    { title: 'New Users (Yesterday)', value: statsData?.new_users_yesterday || '0', icon: '📅', color: TEAL, bg: '#eaf5f6', hasExport: true, exportType: 'new_users_yesterday' },
    { title: 'New Subs (Yesterday)', value: statsData?.new_subs_yesterday || '0', icon: '📅', color: GREEN, bg: '#edf7ed', hasExport: true, exportType: 'new_subs_yesterday' },
    { title: 'New Users (Last 7 Days)', value: statsData?.new_users_last_7_days || '0', icon: '🗓️', color: ORANGE, bg: '#fdf0ea', hasExport: true, exportType: 'new_users_last_7_days' },
    { title: 'Pers. Profiles & Yearly Forecasts', value: statsData?.subscription_type_1 || '0', icon: '1️⃣', color: TEAL, bg: '#eaf5f6' },
    { title: 'Relationship Comp Reports', value: statsData?.subscription_type_2 || '0', icon: '2️⃣', color: GREEN, bg: '#edf7ed' },
    { title: 'Both Packages Together', value: statsData?.subscription_type_3 || '0', icon: '3️⃣', color: ORANGE, bg: '#fdf0ea' },
    { title: 'Diamond Report Program', value: statsData?.subscription_type_4 || '0', icon: '4️⃣', color: YELLOW, bg: '#fdf6e3' },
    { title: 'Name Advisor Program', value: statsData?.subscription_type_5 || '0', icon: '5️⃣', color: TEAL, bg: '#eaf5f6' },
    { title: 'Lucky Numbers Program', value: statsData?.subscription_type_6 || '0', icon: '6️⃣', color: GREEN, bg: '#edf7ed' },
    { title: 'All Programs Combined', value: statsData?.subscription_type_7 || '0', icon: '7️⃣', color: ORANGE, bg: '#fdf0ea' },
  ]

  const getLogBadge = (logType) => {
    if (logType?.includes('failed') || logType?.includes('error'))
      return { bg: '#fdf0ea', color: ORANGE, border: '#f5c5aa' }
    if (logType?.includes('login'))
      return { bg: '#edf7ed', color: GREEN, border: '#b2dfb2' }
    if (logType?.includes('delete'))
      return { bg: '#fdf6e3', color: '#b07a10', border: '#f5d9a0' }
    return { bg: '#eaf5f6', color: TEAL, border: '#a2d4da' }
  }

  return (
    <div className="space-y-6 pb-10">
      <Navbar title="Dashboard" subtitle="Welcome to your admin dashboard" />

      {/* ── Stats Cards ── */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {stats.map((s, i) => (
          <div
            key={i}
            className="bg-white rounded-xl shadow-md hover:shadow-lg transition-shadow overflow-hidden"
            style={{ borderLeft: `4px solid ${s.color}` }}
          >
            <div className="p-4">
              <div className="flex justify-between items-start mb-2">
                <div
                  className="w-9 h-9 rounded-lg flex items-center justify-center text-lg"
                  style={{ backgroundColor: s.bg }}
                >
                  {s.icon}
                </div>
                {s.hasExport && (
                  <button
                    onClick={() => handleExport(s.exportType)}
                    className="text-[10px] text-white px-2 py-1 rounded-lg font-semibold shadow-sm hover:opacity-90 transition-opacity"
                    style={{ backgroundColor: s.color }}
                  >
                    📥 Export
                  </button>
                )}
              </div>
              <p className="text-xl text-gray-600 dark:text-gray-600 font-semibold mb-1 leading-tight">{s.title}</p>
              <p className="text-2xl font-extrabold" style={{ color: s.color }}>{s.value}</p>
            </div>
            <div className="h-1" style={{ backgroundColor: s.bg }} />
          </div>
        ))}
      </div>

      {/* ── Recent Activity (DataTables style) ── */}
      <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-xl border border-gray-100 dark:border-slate-700 overflow-hidden">
        {/* Header bar */}
        <div
          className="px-6 py-4 flex flex-col md:flex-row justify-between items-start md:items-center gap-3"
          style={{ borderBottom: `3px solid ${TEAL}`, background: 'linear-gradient(to right,#f0fafa,#fff)' }}
        >
          <div>
            <h2 className="text-lg font-bold text-gray-800 dark:text-white" style={{ color: TEAL }}>
              📈 Recent Activity
            </h2>
            <p className="text-xs text-gray-500 mt-0.5">Latest system events and user actions</p>
          </div>

          <div className="flex items-center gap-3 flex-wrap">
            {/* Auto‑reload toggle */}
            <div className="flex items-center gap-2 bg-gray-50 px-3 py-2 rounded-lg border border-gray-200 dark:border-slate-600 text-sm">
              <span className="text-gray-600 dark:text-gray-400 font-medium">Auto Reload</span>
              <button
                onClick={() => setAutoReload(v => !v)}
                className="w-10 h-5 rounded-full relative transition-colors"
                style={{ backgroundColor: autoReload ? GREEN : '#d1d5db' }}
              >
                <div className={`w-4 h-4 bg-white rounded-full absolute top-0.5 shadow transition-all ${autoReload ? 'left-5' : 'left-0.5'}`} />
              </button>
              <span className="text-xs font-semibold" style={{ color: autoReload ? GREEN : '#9ca3af' }}>
                {autoReload ? '✓ 2m' : '✗'}
              </span>
            </div>

            {/* Limit select */}
            <select
              className="px-3 py-2 rounded-lg border border-gray-200 dark:border-slate-600 text-sm bg-black text-gray-700 dark:text-gray-200 outline-none font-medium"
              value={logsLimit}
              onChange={e => setLogsLimit(Number(e.target.value))}
            >
              <option value={20}>20 items</option>
              <option value={50}>50 items</option>
              <option value={100}>100 items</option>
            </select>

            {/* Refresh btn */}
            <button
              onClick={fetchRecentLogs}
              className="px-4 py-2 rounded-lg text-sm font-bold text-white hover:opacity-90 transition-opacity"
              style={{ backgroundColor: TEAL }}
            >
              <span className={logsLoading ? 'animate-spin inline-block' : ''}>🔄</span> Refresh
            </button>
          </div>
        </div>

        {/* Table */}
        <div className="overflow-x-auto max-h-[600px] overflow-y-auto">
          {logsLoading ? (
            <div className="flex justify-center items-center gap-3 py-16">
              <span className="text-3xl animate-spin">⏳</span>
              <p className="text-gray-400 font-medium">Loading activities…</p>
            </div>
          ) : recentLogs.length > 0 ? (
            <table className="w-full text-sm border-collapse">
              <thead className="sticky top-0 z-10">
                <tr style={{ backgroundColor: TEAL }}>
                  {['#', 'Type', 'User / Email', 'Log Message', 'Date & Time'].map(h => (
                    <th key={h} className="px-4 py-3 text-left text-xs font-bold text-white uppercase tracking-wide whitespace-nowrap">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {recentLogs.map((log, idx) => {
                  const badge = getLogBadge(log.log_type)
                  return (
                    <tr
                      key={log.id}
                      style={{ backgroundColor: idx % 2 === 0 ? '#fff' : '#f7fbfc' }}
                      onMouseEnter={e => (e.currentTarget.style.backgroundColor = '#e6f4f5')}
                      onMouseLeave={e => (e.currentTarget.style.backgroundColor = idx % 2 === 0 ? '#fff' : '#f7fbfc')}
                    >
                      <td className="px-4 py-3 text-gray-400 font-mono text-xs">{idx + 1}</td>
                      <td className="px-4 py-3">
                        <span
                          className="px-2 py-0.5 rounded text-xs font-bold"
                          style={{ backgroundColor: badge.bg, color: badge.color, border: `1px solid ${badge.border}` }}
                        >
                          {log.log_type}
                        </span>
                      </td>
                      <td className="px-4 py-3 font-medium text-sm" style={{color:`#000`}}>
                        {log.email || 'Unknown'}
                      </td>
                      <td className="px-4 py-3 text-gray-600 dark:text-gray-400 max-w-xs">
                        <span className="line-clamp-1" title={log.logmessage}>{log.logmessage || '—'}</span>
                      </td>
                      <td className="px-4 py-3 text-gray-500 font-mono text-ls whitespace-nowrap">
                        {new Date(log.created).toLocaleString()}
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          ) : (
            <div className="text-center py-14">
              <p className="text-gray-400 text-lg">📭 No recent activity</p>
            </div>
          )}
        </div>

        {/* Footer */}
        <div
          className="px-6 py-3 flex justify-between items-center text-xs text-gray-400 font-medium"
          style={{ borderTop: '1px solid #e5f0f2', backgroundColor: '#f7fbfc' }}
        >
          <span>Showing last <strong>{logsLimit}</strong> activities</span>
          <span>Last updated: <strong style={{ color: TEAL }}>{lastUpdated.toLocaleTimeString()}</strong></span>
        </div>
      </div>
    </div>
  )
}

export default Dashboard
