'use client';

import React, { useState, useEffect, useCallback } from 'react';
import AppLayout from '@/components/AppLayout';
import { Search, Filter, Download, RefreshCw, Shield, AlertTriangle, Info, ChevronDown, X, Clock, User, Activity } from 'lucide-react';
import { getAuditLog, AuditEntry, AuditActionType } from '@/lib/auditLogger';

const ACTION_LABELS: Record<AuditActionType, string> = {
  LOGIN: 'Login',
  LOGOUT: 'Logout',
  ROLE_CHANGE: 'Role Change',
  PERMISSION_EDIT: 'Permission Edit',
  USER_CREATE: 'User Created',
  USER_DELETE: 'User Deleted',
  USER_BLOCK: 'User Blocked',
  USER_UNBLOCK: 'User Unblocked',
  ITEM_DELETE: 'Item Deleted',
  STOCK_ADJUSTMENT: 'Stock Adjustment',
  STOCK_IN: 'Stock In',
  SALE_COMPLETE: 'Sale Completed',
  PURCHASE_CREATE: 'Purchase Created',
  SETTINGS_CHANGE: 'Settings Changed',
  PRODUCT_CREATE: 'Product Created',
  PRODUCT_EDIT: 'Product Edited',
  PRODUCT_DELETE: 'Product Deleted',
};

const SEVERITY_CONFIG = {
  info: { label: 'Info', className: 'bg-info-bg text-info border-info/20', icon: Info, dot: 'bg-info' },
  warning: { label: 'Warning', className: 'bg-warning-bg text-warning border-warning/20', icon: AlertTriangle, dot: 'bg-warning' },
  critical: { label: 'Critical', className: 'bg-danger-bg text-danger border-danger/20', icon: Shield, dot: 'bg-danger' },
};

const ALL_MODULES = ['Auth', 'Users & Roles', 'POS Terminal', 'Inventory', 'Sales', 'Purchases', 'Products', 'Settings', 'Finance'];
const ALL_SEVERITIES = ['info', 'warning', 'critical'] as const;

function formatTimestamp(iso: string): { date: string; time: string } {
  const d = new Date(iso);
  const date = d.toLocaleDateString('en-KE', { day: '2-digit', month: 'short', year: 'numeric' });
  const time = d.toLocaleTimeString('en-KE', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false });
  return { date, time };
}

export default function AuditTrailPage() {
  const [logs, setLogs] = useState<AuditEntry[]>([]);
  const [search, setSearch] = useState('');
  const [moduleFilter, setModuleFilter] = useState('');
  const [severityFilter, setSeverityFilter] = useState('');
  const [actionFilter, setActionFilter] = useState('');
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');
  const [showFilters, setShowFilters] = useState(false);
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const PAGE_SIZE = 25;

  const loadLogs = useCallback(() => {
    setLogs(getAuditLog());
  }, []);

  useEffect(() => {
    loadLogs();
  }, [loadLogs]);

  const filtered = logs.filter((entry) => {
    const searchLower = search.toLowerCase();
    const matchesSearch =
      !search ||
      entry.user.toLowerCase().includes(searchLower) ||
      entry.userEmail.toLowerCase().includes(searchLower) ||
      entry.details.toLowerCase().includes(searchLower) ||
      ACTION_LABELS[entry.actionType].toLowerCase().includes(searchLower);

    const matchesModule = !moduleFilter || entry.module === moduleFilter;
    const matchesSeverity = !severityFilter || entry.severity === severityFilter;
    const matchesAction = !actionFilter || entry.actionType === actionFilter;

    let matchesDate = true;
    if (dateFrom) {
      matchesDate = matchesDate && new Date(entry.timestamp) >= new Date(dateFrom);
    }
    if (dateTo) {
      const toDate = new Date(dateTo);
      toDate.setHours(23, 59, 59, 999);
      matchesDate = matchesDate && new Date(entry.timestamp) <= toDate;
    }

    return matchesSearch && matchesModule && matchesSeverity && matchesAction && matchesDate;
  });

  const totalPages = Math.ceil(filtered.length / PAGE_SIZE);
  const paginated = filtered.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);

  const handleExport = () => {
    const headers = ['ID', 'Timestamp', 'User', 'Email', 'Action', 'Module', 'Severity', 'Details'];
    const rows = filtered.map((e) => [
      e.id,
      e.timestamp,
      e.user,
      e.userEmail,
      ACTION_LABELS[e.actionType],
      e.module,
      e.severity,
      `"${e.details.replace(/"/g, '""')}"`,
    ]);
    const csv = [headers.join(','), ...rows.map((r) => r.join(','))].join('\n');
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `audit-trail-${new Date().toISOString().split('T')[0]}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const clearFilters = () => {
    setSearch('');
    setModuleFilter('');
    setSeverityFilter('');
    setActionFilter('');
    setDateFrom('');
    setDateTo('');
    setPage(1);
  };

  const hasActiveFilters = search || moduleFilter || severityFilter || actionFilter || dateFrom || dateTo;

  const stats = {
    total: logs.length,
    critical: logs.filter((l) => l.severity === 'critical').length,
    warning: logs.filter((l) => l.severity === 'warning').length,
    today: logs.filter((l) => new Date(l.timestamp).toDateString() === new Date().toDateString()).length,
  };

  return (
    <AppLayout>
      <div className="p-6 xl:p-8 max-w-screen-2xl mx-auto space-y-6">
        {/* Header */}
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div>
            <h1 className="text-xl font-700 text-foreground">Audit Trail</h1>
            <p className="text-sm text-muted-foreground mt-0.5">Complete log of all user actions for compliance and accountability</p>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={loadLogs}
              className="flex items-center gap-2 px-3 py-2 rounded-md border border-border text-sm text-muted-foreground hover:bg-muted transition-colors"
            >
              <RefreshCw size={14} />
              Refresh
            </button>
            <button
              onClick={handleExport}
              className="flex items-center gap-2 px-3 py-2 rounded-md border border-border text-sm text-muted-foreground hover:bg-muted transition-colors"
            >
              <Download size={14} />
              Export CSV
            </button>
          </div>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          {[
            { label: 'Total Events', value: stats.total, icon: Activity, color: 'text-primary', bg: 'bg-primary/10' },
            { label: 'Today\'s Events', value: stats.today, icon: Clock, color: 'text-info', bg: 'bg-info-bg' },
            { label: 'Warnings', value: stats.warning, icon: AlertTriangle, color: 'text-warning', bg: 'bg-warning-bg' },
            { label: 'Critical Events', value: stats.critical, icon: Shield, color: 'text-danger', bg: 'bg-danger-bg' },
          ].map((stat) => {
            const StatIcon = stat.icon;
            return (
              <div key={stat.label} className="card-elevated rounded-xl p-4 flex items-center gap-3">
                <div className={`w-10 h-10 rounded-lg ${stat.bg} flex items-center justify-center flex-shrink-0`}>
                  <StatIcon size={18} className={stat.color} />
                </div>
                <div>
                  <p className="text-2xl font-700 text-foreground">{stat.value}</p>
                  <p className="text-xs text-muted-foreground">{stat.label}</p>
                </div>
              </div>
            );
          })}
        </div>

        {/* Search & Filter Bar */}
        <div className="card-elevated rounded-xl p-4 space-y-3">
          <div className="flex flex-col sm:flex-row gap-3">
            <div className="flex items-center gap-2 bg-muted border border-border rounded-md px-3 h-9 flex-1">
              <Search size={14} className="text-muted-foreground flex-shrink-0" />
              <input
                type="text"
                placeholder="Search by user, email, action, or details…"
                value={search}
                onChange={(e) => { setSearch(e.target.value); setPage(1); }}
                className="bg-transparent text-sm text-foreground placeholder:text-muted-foreground outline-none w-full"
              />
              {search && (
                <button onClick={() => setSearch('')} className="text-muted-foreground hover:text-foreground">
                  <X size={12} />
                </button>
              )}
            </div>
            <button
              onClick={() => setShowFilters(!showFilters)}
              className={`flex items-center gap-2 px-3 h-9 rounded-md border text-sm font-600 transition-colors ${showFilters || hasActiveFilters ? 'border-primary text-primary bg-primary/5' : 'border-border text-muted-foreground hover:bg-muted'}`}
            >
              <Filter size={14} />
              Filters
              {hasActiveFilters && <span className="w-4 h-4 rounded-full bg-primary text-white text-xs flex items-center justify-center">!</span>}
              <ChevronDown size={12} className={`transition-transform ${showFilters ? 'rotate-180' : ''}`} />
            </button>
            {hasActiveFilters && (
              <button onClick={clearFilters} className="flex items-center gap-1.5 px-3 h-9 rounded-md border border-border text-sm text-muted-foreground hover:bg-muted transition-colors">
                <X size={12} />
                Clear
              </button>
            )}
          </div>

          {showFilters && (
            <div className="grid grid-cols-2 md:grid-cols-4 gap-3 pt-2 border-t border-border">
              <div>
                <label className="text-xs font-600 text-muted-foreground mb-1 block">Module</label>
                <select
                  value={moduleFilter}
                  onChange={(e) => { setModuleFilter(e.target.value); setPage(1); }}
                  className="w-full h-8 rounded-md border border-border bg-background text-sm text-foreground px-2 outline-none"
                >
                  <option value="">All Modules</option>
                  {ALL_MODULES.map((m) => <option key={m} value={m}>{m}</option>)}
                </select>
              </div>
              <div>
                <label className="text-xs font-600 text-muted-foreground mb-1 block">Severity</label>
                <select
                  value={severityFilter}
                  onChange={(e) => { setSeverityFilter(e.target.value); setPage(1); }}
                  className="w-full h-8 rounded-md border border-border bg-background text-sm text-foreground px-2 outline-none"
                >
                  <option value="">All Severities</option>
                  {ALL_SEVERITIES.map((s) => <option key={s} value={s}>{s.charAt(0).toUpperCase() + s.slice(1)}</option>)}
                </select>
              </div>
              <div>
                <label className="text-xs font-600 text-muted-foreground mb-1 block">Date From</label>
                <input
                  type="date"
                  value={dateFrom}
                  onChange={(e) => { setDateFrom(e.target.value); setPage(1); }}
                  className="w-full h-8 rounded-md border border-border bg-background text-sm text-foreground px-2 outline-none"
                />
              </div>
              <div>
                <label className="text-xs font-600 text-muted-foreground mb-1 block">Date To</label>
                <input
                  type="date"
                  value={dateTo}
                  onChange={(e) => { setDateTo(e.target.value); setPage(1); }}
                  className="w-full h-8 rounded-md border border-border bg-background text-sm text-foreground px-2 outline-none"
                />
              </div>
            </div>
          )}
        </div>

        {/* Results count */}
        <div className="flex items-center justify-between text-sm text-muted-foreground">
          <span>
            Showing <span className="font-600 text-foreground">{Math.min((page - 1) * PAGE_SIZE + 1, filtered.length)}–{Math.min(page * PAGE_SIZE, filtered.length)}</span> of <span className="font-600 text-foreground">{filtered.length}</span> events
          </span>
          {totalPages > 1 && (
            <div className="flex items-center gap-1">
              <button
                disabled={page === 1}
                onClick={() => setPage(page - 1)}
                className="px-2 py-1 rounded border border-border text-xs disabled:opacity-40 hover:bg-muted transition-colors"
              >
                ‹ Prev
              </button>
              <span className="px-2 text-xs">Page {page} of {totalPages}</span>
              <button
                disabled={page === totalPages}
                onClick={() => setPage(page + 1)}
                className="px-2 py-1 rounded border border-border text-xs disabled:opacity-40 hover:bg-muted transition-colors"
              >
                Next ›
              </button>
            </div>
          )}
        </div>

        {/* Audit Log Table */}
        <div className="card-elevated rounded-xl overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="bg-muted/50 border-b border-border">
                  <th className="text-left px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Timestamp</th>
                  <th className="text-left px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">User</th>
                  <th className="text-left px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Action</th>
                  <th className="text-left px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Module</th>
                  <th className="text-left px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Severity</th>
                  <th className="text-left px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Details</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {paginated.length === 0 ? (
                  <tr>
                    <td colSpan={6} className="px-4 py-12 text-center text-muted-foreground text-sm">
                      <Activity size={32} className="mx-auto mb-2 opacity-30" />
                      No audit events found matching your filters
                    </td>
                  </tr>
                ) : (
                  paginated.map((entry) => {
                    const sev = SEVERITY_CONFIG[entry.severity];
                    const SevIcon = sev.icon;
                    const { date, time } = formatTimestamp(entry.timestamp);
                    const isExpanded = expandedId === entry.id;

                    return (
                      <React.Fragment key={entry.id}>
                        <tr
                          className={`hover:bg-muted/30 transition-colors cursor-pointer ${isExpanded ? 'bg-muted/20' : ''}`}
                          onClick={() => setExpandedId(isExpanded ? null : entry.id)}
                        >
                          <td className="px-4 py-3 whitespace-nowrap">
                            <p className="text-xs font-600 text-foreground">{date}</p>
                            <p className="text-xs text-muted-foreground font-mono">{time}</p>
                          </td>
                          <td className="px-4 py-3">
                            <div className="flex items-center gap-2">
                              <div className="w-7 h-7 rounded-full bg-primary/10 flex items-center justify-center flex-shrink-0">
                                <User size={12} className="text-primary" />
                              </div>
                              <div>
                                <p className="text-xs font-600 text-foreground">{entry.user}</p>
                                <p className="text-xs text-muted-foreground">{entry.userEmail}</p>
                              </div>
                            </div>
                          </td>
                          <td className="px-4 py-3 whitespace-nowrap">
                            <span className="text-xs font-600 text-foreground">{ACTION_LABELS[entry.actionType]}</span>
                          </td>
                          <td className="px-4 py-3 whitespace-nowrap">
                            <span className="text-xs text-muted-foreground bg-muted px-2 py-0.5 rounded-full">{entry.module}</span>
                          </td>
                          <td className="px-4 py-3 whitespace-nowrap">
                            <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-600 border ${sev.className}`}>
                              <span className={`w-1.5 h-1.5 rounded-full ${sev.dot}`} />
                              {sev.label}
                            </span>
                          </td>
                          <td className="px-4 py-3 max-w-xs">
                            <p className="text-xs text-muted-foreground truncate">{entry.details}</p>
                          </td>
                        </tr>
                        {isExpanded && (
                          <tr className="bg-muted/10">
                            <td colSpan={6} className="px-4 py-3">
                              <div className="flex flex-wrap gap-4 text-xs">
                                <div>
                                  <span className="text-muted-foreground font-600">Event ID: </span>
                                  <span className="font-mono text-foreground">{entry.id}</span>
                                </div>
                                <div>
                                  <span className="text-muted-foreground font-600">Full Timestamp: </span>
                                  <span className="font-mono text-foreground">{entry.timestamp}</span>
                                </div>
                                <div className="flex-1 min-w-0">
                                  <span className="text-muted-foreground font-600">Full Details: </span>
                                  <span className="text-foreground">{entry.details}</span>
                                </div>
                              </div>
                            </td>
                          </tr>
                        )}
                      </React.Fragment>
                    );
                  })
                )}
              </tbody>
            </table>
          </div>
        </div>

        {/* Bottom pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-center gap-1">
            <button disabled={page === 1} onClick={() => setPage(1)} className="px-2 py-1 rounded border border-border text-xs disabled:opacity-40 hover:bg-muted transition-colors">«</button>
            <button disabled={page === 1} onClick={() => setPage(page - 1)} className="px-2 py-1 rounded border border-border text-xs disabled:opacity-40 hover:bg-muted transition-colors">‹ Prev</button>
            {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
              const p = Math.max(1, Math.min(page - 2, totalPages - 4)) + i;
              return (
                <button
                  key={p}
                  onClick={() => setPage(p)}
                  className={`w-8 h-7 rounded border text-xs transition-colors ${p === page ? 'border-primary bg-primary text-white' : 'border-border hover:bg-muted'}`}
                >
                  {p}
                </button>
              );
            })}
            <button disabled={page === totalPages} onClick={() => setPage(page + 1)} className="px-2 py-1 rounded border border-border text-xs disabled:opacity-40 hover:bg-muted transition-colors">Next ›</button>
            <button disabled={page === totalPages} onClick={() => setPage(totalPages)} className="px-2 py-1 rounded border border-border text-xs disabled:opacity-40 hover:bg-muted transition-colors">»</button>
          </div>
        )}
      </div>
    </AppLayout>
  );
}
