'use client';
import { createContext, useContext, useState, ReactNode } from 'react';

export type AuditAction = 'Create' | 'Read' | 'Update' | 'Delete' | 'Login' | 'Logout' | 'Export' | 'Import' | 'Approve' | 'Reject';
export type AuditModule = 'Employees' | 'Leave' | 'Training' | 'Disciplinary' | 'Termination' | 'Performance' | 'Payroll' | 'Grading' | 'Recruitment' | 'Setup' | 'Auth' | 'Documents' | 'Reports';

export interface AuditEntry {
  id: string;
  timestamp: string;
  user: string;
  userId: string;
  role: string;
  module: AuditModule;
  action: AuditAction;
  recordId: string;
  description: string;
  oldValue?: string;
  newValue?: string;
  ipAddress: string;
  severity: 'low' | 'medium' | 'high';
}

interface AuditLogContextType {
  entries: AuditEntry[];
  log: (entry: Omit<AuditEntry, 'id' | 'timestamp' | 'ipAddress'>) => void;
  clearLog: () => void;
}

const INITIAL_ENTRIES: AuditEntry[] = [
  { id: 'a1', timestamp: '2026-04-14 09:15:32', user: 'System Administrator', userId: 'admin-001', role: 'HR Super Admin', module: 'Auth', action: 'Login', recordId: 'admin-001', description: 'Admin logged in successfully', ipAddress: '196.201.214.10', severity: 'low' },
  { id: 'a2', timestamp: '2026-04-14 09:18:05', user: 'System Administrator', userId: 'admin-001', role: 'HR Super Admin', module: 'Employees', action: 'Create', recordId: 'UF012', description: 'Created employee record for Brian Omondi (UF012)', newValue: '{"name":"Brian Omondi","dept":"ICT","position":"ICT Officer"}', ipAddress: '196.201.214.10', severity: 'medium' },
  { id: 'a3', timestamp: '2026-04-14 09:45:11', user: 'HR Manager', userId: 'hr-001', role: 'HR Manager', module: 'Leave', action: 'Approve', recordId: 'LV-2026-038', description: 'Approved Annual Leave for Jane Mwangi (April 14-18)', oldValue: '{"status":"Pending"}', newValue: '{"status":"Approved"}', ipAddress: '196.201.214.22', severity: 'medium' },
  { id: 'a4', timestamp: '2026-04-13 14:30:22', user: 'System Administrator', userId: 'admin-001', role: 'HR Super Admin', module: 'Grading', action: 'Update', recordId: 'GR-005', description: 'Updated grade scale Job Group F salary range', oldValue: '{"min":85000,"max":110000}', newValue: '{"min":90000,"max":120000}', ipAddress: '196.201.214.10', severity: 'high' },
  { id: 'a5', timestamp: '2026-04-13 11:05:44', user: 'HR Manager', userId: 'hr-001', role: 'HR Manager', module: 'Disciplinary', action: 'Create', recordId: 'DISC-2026-007', description: 'Created new disciplinary case: Insubordination complaint against Samuel Kipchoge', ipAddress: '196.201.214.22', severity: 'high' },
  { id: 'a6', timestamp: '2026-04-13 10:20:18', user: 'System Administrator', userId: 'admin-001', role: 'HR Super Admin', module: 'Training', action: 'Approve', recordId: 'TR-REQ-2026-014', description: 'Approved training request: Advanced Excel for Finance team', oldValue: '{"status":"Under Review"}', newValue: '{"status":"Approved"}', ipAddress: '196.201.214.10', severity: 'medium' },
  { id: 'a7', timestamp: '2026-04-12 16:55:33', user: 'HR Manager', userId: 'hr-001', role: 'HR Manager', module: 'Performance', action: 'Update', recordId: 'APPR-2026-Q1-003', description: 'Updated supervisor evaluation for Alice Odhiambo Q1 2026', ipAddress: '196.201.214.22', severity: 'medium' },
  { id: 'a8', timestamp: '2026-04-12 14:10:07', user: 'System Administrator', userId: 'admin-001', role: 'HR Super Admin', module: 'Setup', action: 'Update', recordId: 'SYS-CONFIG', description: 'Updated numbering rules for disciplinary case prefix', oldValue: '{"prefix":"DISC"}', newValue: '{"prefix":"DISC-2026"}', ipAddress: '196.201.214.10', severity: 'high' },
  { id: 'a9', timestamp: '2026-04-11 09:30:15', user: 'System Administrator', userId: 'admin-001', role: 'HR Super Admin', module: 'Termination', action: 'Create', recordId: 'TERM-2026-003', description: 'Initiated termination process for contract end: Grace Wanjiku', ipAddress: '196.201.214.10', severity: 'high' },
  { id: 'a10', timestamp: '2026-04-10 15:45:28', user: 'HR Manager', userId: 'hr-001', role: 'HR Manager', module: 'Employees', action: 'Export', recordId: 'BULK-EXPORT', description: 'Exported employee register (42 records) to Excel', ipAddress: '196.201.214.22', severity: 'medium' },
  { id: 'a11', timestamp: '2026-04-09 11:20:44', user: 'System Administrator', userId: 'admin-001', role: 'HR Super Admin', module: 'Reports', action: 'Export', recordId: 'RPT-2026-Q1', description: 'Generated and exported Q1 2026 turnover analytics report (PDF)', ipAddress: '196.201.214.10', severity: 'low' },
  { id: 'a12', timestamp: '2026-04-09 08:55:12', user: 'System Administrator', userId: 'admin-001', role: 'HR Super Admin', module: 'Auth', action: 'Update', recordId: 'UF007', description: 'Reset password for employee Fatuma Hassan (UF007)', ipAddress: '196.201.214.10', severity: 'high' },
  { id: 'a13', timestamp: '2026-04-08 16:30:51', user: 'HR Manager', userId: 'hr-001', role: 'HR Manager', module: 'Training', action: 'Create', recordId: 'TRN-2026-005', description: 'Created training event: Leadership Skills Workshop (April 22-23)', ipAddress: '196.201.214.22', severity: 'low' },
  { id: 'a14', timestamp: '2026-04-08 13:15:38', user: 'System Administrator', userId: 'admin-001', role: 'HR Super Admin', module: 'Documents', action: 'Delete', recordId: 'DOC-2026-031', description: 'Deleted expired policy document: Old Procurement Policy v1.2', ipAddress: '196.201.214.10', severity: 'high' },
  { id: 'a15', timestamp: '2026-04-07 10:05:22', user: 'HR Manager', userId: 'hr-001', role: 'HR Manager', module: 'Payroll', action: 'Read', recordId: 'PAY-APR-2026', description: 'Accessed April 2026 payroll records', ipAddress: '196.201.214.22', severity: 'low' },
];

const AuditLogContext = createContext<AuditLogContextType | null>(null);

export function AuditLogProvider({ children }: { children: ReactNode }) {
  const [entries, setEntries] = useState<AuditEntry[]>(INITIAL_ENTRIES);

  const log = (entry: Omit<AuditEntry, 'id' | 'timestamp' | 'ipAddress'>) => {
    const now = new Date();
    const ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
    const newEntry: AuditEntry = { ...entry, id: `a${Date.now()}`, timestamp: ts, ipAddress: '196.201.214.10' };
    setEntries(prev => [newEntry, ...prev]);
  };

  const clearLog = () => setEntries([]);

  return (
    <AuditLogContext.Provider value={{ entries, log, clearLog }}>
      {children}
    </AuditLogContext.Provider>
  );
}

export function useAuditLog() {
  const ctx = useContext(AuditLogContext);
  if (!ctx) throw new Error('useAuditLog must be used within AuditLogProvider');
  return ctx;
}
