'use client';

import { useEffect, useMemo, useState } from 'react';
import { motion } from 'framer-motion';
import { Activity, AlertCircle, ChevronDown, Clock, FolderKanban, Loader2 } from 'lucide-react';

interface TokenLog {
  id: number;
  companyId: string;
  userId: string;
  userName: string;
  userEmail: string | null;
  projectId: string;
  projectName: string;
  stepName: string;
  tokensConsumed: number;
  createdAt: string;
}

export default function AdminActivityLogs() {
  const [logs, setLogs] = useState<TokenLog[]>([]);
  const [allProjects, setAllProjects] = useState<Array<{ id: string; name: string; userId: string }>>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [openProjects, setOpenProjects] = useState<Set<string>>(new Set());

  useEffect(() => {
    fetch('/api/admin/activity', { credentials: 'include' })
      .then(async (res) => {
        if (!res.ok) {
          const data = await res.json().catch(() => null);
          throw new Error(data?.error || 'Failed to load activity logs');
        }
        return res.json();
      })
      .then((data) => {
        setLogs(Array.isArray(data.logs) ? data.logs : []);
        setAllProjects(Array.isArray(data.allProjects) ? data.allProjects : []);
      })
      .catch((err) => {
        setError(err instanceof Error ? err.message : 'Failed to load activity logs');
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  const grouped = useMemo(() => {
    const map = new Map<string, { projectId: string; projectName: string; totalTokens: number; logs: TokenLog[] }>();
    for (const log of logs) {
      const existing = map.get(log.projectId);
      if (existing) {
        existing.totalTokens += log.tokensConsumed;
        existing.logs.push(log);
      } else {
        map.set(log.projectId, {
          projectId: log.projectId,
          projectName: log.projectName,
          totalTokens: log.tokensConsumed,
          logs: [log],
        });
      }
    }
    // Include projects with no token activity
    for (const p of allProjects) {
      if (!map.has(p.id)) {
        map.set(p.id, { projectId: p.id, projectName: p.name, totalTokens: 0, logs: [] });
      }
    }
    return Array.from(map.values()).sort((a, b) => b.totalTokens - a.totalTokens);
  }, [logs, allProjects]);

  const toggle = (projectId: string) => {
    setOpenProjects((prev) => {
      const next = new Set(prev);
      next.has(projectId) ? next.delete(projectId) : next.add(projectId);
      return next;
    });
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="w-8 h-8 animate-spin text-accent" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <AlertCircle className="w-12 h-12 text-red-400 mx-auto mb-3" />
          <p className="text-red-400">{error}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-5">
      <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }}>
        <h2 className="text-2xl font-bold text-foreground flex items-center gap-2">
          <Activity className="w-6 h-6 text-accent-light" /> Activity Logs
        </h2>
        <p className="text-sm text-muted mt-1">System-wide token activity across all companies and projects</p>
      </motion.div>

      <motion.div
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        className="glass rounded-xl overflow-hidden"
      >
        <div className="px-5 py-4 border-b border-border">
          <h3 className="text-sm font-semibold text-foreground flex items-center gap-2">
            <Clock className="w-4 h-4 text-accent-light" /> Token Activity Log
          </h3>
          <p className="text-[10px] text-muted mt-0.5">{logs.length} events · {grouped.length} project{grouped.length !== 1 ? 's' : ''}</p>
        </div>

        {grouped.length === 0 ? (
          <div className="py-12 text-center text-sm text-muted">No activity logs yet</div>
        ) : (
          <div>
            {grouped.map((group, gi) => {
              const isOpen = openProjects.has(group.projectId);
              const hasLogs = group.logs.length > 0;
              return (
                <div key={group.projectId} className={gi > 0 ? 'border-t border-border' : ''}>
                  <button
                    onClick={() => hasLogs ? toggle(group.projectId) : undefined}
                    disabled={!hasLogs}
                    className={`w-full flex items-center gap-3 px-5 py-3.5 text-left transition-colors ${hasLogs ? 'hover:bg-surface/40 cursor-pointer' : 'cursor-default opacity-60'}`}
                  >
                    <ChevronDown
                      className={`w-4 h-4 text-muted flex-shrink-0 transition-transform duration-200 ${isOpen ? 'rotate-180' : ''} ${!hasLogs ? 'invisible' : ''}`}
                    />
                    <FolderKanban className="w-4 h-4 text-accent-light flex-shrink-0" />
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-foreground truncate">{group.projectName}</p>
                      <p className="text-[10px] text-muted truncate">
                        {hasLogs
                          ? <>{group.logs[0]?.userName}{group.logs[0]?.userEmail ? ` · ${group.logs[0].userEmail}` : ''}</>
                          : 'No activity yet'}
                      </p>
                    </div>
                    <span className="text-[10px] text-muted mr-3 flex-shrink-0">
                      {hasLogs ? `${group.logs.length} step${group.logs.length !== 1 ? 's' : ''}` : '—'}
                    </span>
                    <span className={`text-xs font-semibold tabular-nums flex-shrink-0 ${hasLogs ? 'text-red-400' : 'text-muted'}`}>
                      {hasLogs ? `-${group.totalTokens.toLocaleString()}` : '0'}
                    </span>
                  </button>

                  {isOpen && (
                    <div className="border-t border-border/50 bg-surface/20">
                      <div className="grid grid-cols-[1fr_140px_90px] gap-3 px-8 py-2 text-[10px] text-muted uppercase tracking-wider font-semibold border-b border-border/40">
                        <span>Step · User</span>
                        <span className="text-center">Date &amp; Time</span>
                        <span className="text-right">Tokens</span>
                      </div>
                      {group.logs.map((log, i) => {
                        const date = new Date(log.createdAt);
                        const dateStr = date.toLocaleDateString(undefined, { day: '2-digit', month: 'short', year: 'numeric' });
                        const timeStr = date.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
                        return (
                          <div
                            key={log.id}
                            className={`grid grid-cols-[1fr_140px_90px] gap-3 px-8 py-2.5 items-center text-xs border-t border-border/30 ${
                              i % 2 !== 0 ? 'bg-surface/30' : ''
                            }`}
                          >
                            <div className="min-w-0">
                              <p className="text-foreground truncate">{log.stepName}</p>
                              <p className="text-[10px] text-muted truncate">{log.userName} · {log.userEmail}</p>
                            </div>
                            <div className="text-center tabular-nums">
                              <p className="text-foreground">{dateStr}</p>
                              <p className="text-[10px] text-muted">{timeStr}</p>
                            </div>
                            <span className="text-right font-medium text-red-400 tabular-nums">
                              -{log.tokensConsumed.toLocaleString()}
                            </span>
                          </div>
                        );
                      })}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </motion.div>
    </div>
  );
}
