// frontend/src/pages/AdminDashboard.jsx
import { useState, useEffect } from 'react';
import { useAuth } from '../context/AuthContext.jsx';
import { useT } from '../i18n/translations.js';
import { api } from '../context/AuthContext.jsx';
import { Card, Button, Badge, StatusBadge, Modal, Input, Select, Spinner, EmptyState } from '../components/ui/index.jsx';
import { Users, DollarSign, Zap, FileText, Search, Shield } from 'lucide-react';
import toast from 'react-hot-toast';
import { formatDistanceToNow } from 'date-fns';
import { Navigate } from 'react-router-dom';

export default function AdminDashboard() {
  const { user } = useAuth();
  const t = useT(user?.locale);
  const [tab, setTab] = useState('overview');
  const [overview, setOverview] = useState(null);
  const [users, setUsers] = useState([]);
  const [search, setSearch] = useState('');
  const [filterStatus, setFilterStatus] = useState('');
  const [filterPlan, setFilterPlan] = useState('');
  const [loading, setLoading] = useState(true);
  const [selectedUser, setSelectedUser] = useState(null);
  const [confirmModal, setConfirmModal] = useState(null);

  if (user?.role !== 'superadmin') return <Navigate to="/dashboard" replace />;

  useEffect(() => {
    fetchOverview();
    fetchUsers();
  }, []);

  useEffect(() => {
    const timer = setTimeout(fetchUsers, 300);
    return () => clearTimeout(timer);
  }, [search, filterStatus, filterPlan]);

  async function fetchOverview() {
    try {
      const { data } = await api.get('/admin/dashboard');
      setOverview(data);
    } catch {}
  }

  async function fetchUsers() {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (search) params.set('search', search);
      if (filterStatus) params.set('status', filterStatus);
      if (filterPlan) params.set('plan', filterPlan);
      const { data } = await api.get(`/admin/users?${params}`);
      setUsers(data.users || []);
    } catch {}
    setLoading(false);
  }

  async function handleAction(action, userId, extra = {}) {
    try {
      if (action === 'status') await api.patch(`/admin/users/${userId}/status`, { status: extra.status });
      if (action === 'plan') await api.patch(`/admin/users/${userId}/plan`, { planId: extra.planId });
      if (action === 'delete') await api.delete(`/admin/users/${userId}`);
      toast.success('Done!');
      fetchUsers();
      fetchOverview();
      setConfirmModal(null);
    } catch (err) {
      toast.error(err.response?.data?.error || 'Action failed');
    }
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-3">
        <div className="w-9 h-9 bg-red-100 rounded-xl flex items-center justify-center">
          <Shield size={18} className="text-red-600" />
        </div>
        <h1 className="text-2xl font-semibold text-gray-900">{t('admin.title')}</h1>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 bg-gray-100 p-1 rounded-xl w-fit">
        {['overview', 'users', 'audit'].map(tab_ => (
          <button
            key={tab_}
            onClick={() => setTab(tab_)}
            className={`px-4 py-1.5 rounded-lg text-sm font-medium transition-all capitalize ${
              tab === tab_ ? 'bg-white text-gray-900 shadow-sm' : 'text-gray-500 hover:text-gray-700'
            }`}
          >
            {t(`admin.${tab_ === 'overview' ? 'overview' : tab_ === 'users' ? 'users' : 'auditLog'}`)}
          </button>
        ))}
      </div>

      {/* Overview tab */}
      {tab === 'overview' && overview && (
        <div className="space-y-6">
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
            {[
              { icon: DollarSign, label: t('admin.mrr'), value: `$${overview.revenue?.mrr?.toLocaleString() || 0}`, color: 'text-emerald-500' },
              { icon: Users, label: t('admin.totalUsers'), value: overview.users?.total || 0, color: 'text-blue-500' },
              { icon: Users, label: t('admin.activeUsers'), value: overview.users?.active || 0, color: 'text-brand-500' },
              { icon: Zap, label: t('admin.totalRuns'), value: overview.runs?.total_runs || 0, color: 'text-purple-500' },
            ].map(({ icon: Icon, label, value, color }) => (
              <Card key={label} className="p-5">
                <Icon size={18} className={`${color} mb-3`} />
                <p className="text-2xl font-semibold text-gray-900">{value}</p>
                <p className="text-xs text-gray-500 mt-0.5">{label}</p>
              </Card>
            ))}
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* By plan */}
            <Card className="p-5">
              <h3 className="text-sm font-semibold text-gray-900 mb-4">Active by plan</h3>
              <div className="space-y-3">
                {[
                  { plan: 'Starter', key: 'starter_active', price: '$29' },
                  { plan: 'Pro', key: 'pro_active', price: '$79' },
                  { plan: 'Agency', key: 'agency_active', price: '$199' },
                ].map(({ plan, key, price }) => {
                  const count = overview.users?.[key] || 0;
                  const total = (overview.users?.active || 1);
                  return (
                    <div key={key} className="flex items-center gap-3">
                      <span className="text-sm text-gray-600 w-20">{plan}</span>
                      <div className="flex-1 bg-gray-100 rounded-full h-2">
                        <div className="bg-brand-500 h-2 rounded-full" style={{ width: `${(count / total) * 100}%` }} />
                      </div>
                      <span className="text-sm font-medium text-gray-900 w-8 text-right">{count}</span>
                      <span className="text-xs text-gray-400 w-10">{price}</span>
                    </div>
                  );
                })}
              </div>
            </Card>

            {/* By status */}
            <Card className="p-5">
              <h3 className="text-sm font-semibold text-gray-900 mb-4">Users by status</h3>
              <div className="space-y-2">
                {[
                  { label: 'Active', key: 'active' },
                  { label: 'Trial', key: 'trial' },
                  { label: 'Past due', key: 'past_due' },
                  { label: 'Canceled', key: 'canceled' },
                  { label: 'Banned', key: 'banned' },
                ].map(({ label, key }) => (
                  <div key={key} className="flex items-center justify-between">
                    <StatusBadge status={key} />
                    <span className="text-sm font-medium text-gray-900">{overview.users?.[key] || 0}</span>
                  </div>
                ))}
              </div>
            </Card>
          </div>
        </div>
      )}

      {/* Users tab */}
      {tab === 'users' && (
        <div className="space-y-4">
          {/* Filters */}
          <div className="flex gap-3 flex-wrap">
            <div className="relative flex-1 min-w-56">
              <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
              <input
                type="text"
                placeholder={t('admin.search')}
                value={search}
                onChange={e => setSearch(e.target.value)}
                className="w-full pl-8 pr-3 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500"
              />
            </div>
            <select
              value={filterStatus}
              onChange={e => setFilterStatus(e.target.value)}
              className="px-3 py-2 text-sm border border-gray-200 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-brand-500"
            >
              <option value="">{t('admin.filterStatus')}</option>
              {['active', 'trial', 'past_due', 'canceled', 'banned'].map(s => (
                <option key={s} value={s}>{s}</option>
              ))}
            </select>
            <select
              value={filterPlan}
              onChange={e => setFilterPlan(e.target.value)}
              className="px-3 py-2 text-sm border border-gray-200 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-brand-500"
            >
              <option value="">{t('admin.filterPlan')}</option>
              {['starter', 'pro', 'agency'].map(p => (
                <option key={p} value={p}>{p}</option>
              ))}
            </select>
          </div>

          {/* Table */}
          <Card className="overflow-hidden">
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-gray-100 bg-gray-50">
                    {['User', 'Plan', 'Status', 'Runs', 'Joined', 'Actions'].map(h => (
                      <th key={h} className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-50">
                  {loading ? (
                    <tr><td colSpan={6} className="py-12 text-center"><Spinner /></td></tr>
                  ) : users.length === 0 ? (
                    <tr><td colSpan={6} className="py-12 text-center text-gray-400">No users found</td></tr>
                  ) : users.map(u => (
                    <tr key={u.id} className="hover:bg-gray-50 transition-colors">
                      <td className="px-4 py-3">
                        <div>
                          <p className="font-medium text-gray-900">{u.full_name}</p>
                          <p className="text-gray-400 text-xs">{u.email}</p>
                        </div>
                      </td>
                      <td className="px-4 py-3">
                        <Badge variant="default">{u.plan_id || '—'}</Badge>
                      </td>
                      <td className="px-4 py-3"><StatusBadge status={u.status} /></td>
                      <td className="px-4 py-3 text-gray-600">{u.total_runs || 0}</td>
                      <td className="px-4 py-3 text-gray-400 text-xs">
                        {formatDistanceToNow(new Date(u.created_at), { addSuffix: true })}
                      </td>
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-1">
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => setSelectedUser(u)}
                          >
                            View
                          </Button>
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => setConfirmModal({
                              title: u.status === 'banned' ? 'Activate user' : 'Ban user',
                              message: t(u.status === 'banned' ? 'admin.activate' : 'admin.confirmBan'),
                              onConfirm: () => handleAction('status', u.id, { status: u.status === 'banned' ? 'active' : 'banned' })
                            })}
                            className={u.status === 'banned' ? 'text-emerald-600' : 'text-red-600'}
                          >
                            {u.status === 'banned' ? t('admin.activate') : t('admin.ban')}
                          </Button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </Card>
        </div>
      )}

      {/* Confirm modal */}
      <Modal
        open={!!confirmModal}
        onClose={() => setConfirmModal(null)}
        title={confirmModal?.title}
        footer={
          <>
            <Button variant="secondary" onClick={() => setConfirmModal(null)}>{t('common.cancel')}</Button>
            <Button variant="danger" onClick={confirmModal?.onConfirm}>{t('common.confirm')}</Button>
          </>
        }
      >
        <p className="text-gray-600">{confirmModal?.message}</p>
      </Modal>
    </div>
  );
}
