// app/components/admin/audit-logs/AuditLogsTable.tsx
'use client';

import { useState } from 'react';
import Image from 'next/image';
import { AuditLog } from '@/types/audit-log';
import DataTable from '@/app/components/admin/CommonComponents/DataTable';
import TablePagination from '@/app/components/admin/CommonComponents/TablePagination';
import TableFilters from '@/app/components/admin/CommonComponents/TableFilters';
import { BaseTableItem, FilterConfig, FilterValues, TableColumn, TableAction } from '@/types/admin-table';

interface Pagination {
  page: number;
  limit: number;
  total: number;
  pages: number;
}

interface FilterOptions {
  actions: string[];
  resourceTypes: string[];
}

interface AuditLogsTableProps {
  logs: AuditLog[];
  loading: boolean;
  pagination: Pagination;
  filterOptions: FilterOptions;
  onPageChange: (page: number) => void;
  onFilterChange: (filters: FilterValues) => void;
  onViewLog: (log: AuditLog) => void;
}

interface AuditLogItem extends AuditLog, BaseTableItem {
  id: string;
}

export default function AuditLogsTable({
  logs,
  loading,
  pagination,
  filterOptions,
  onPageChange,
  onFilterChange,
  onViewLog
}: AuditLogsTableProps) {
  const [currentFilters, setCurrentFilters] = useState<FilterValues>({});
  const [filtersVisible, setFiltersVisible] = useState(false);

  const formatDate = (dateString: string) => new Date(dateString).toLocaleString();

  const getActionColor = (action: string): string => {
    const colors: Record<string, string> = {
      CREATE: 'bg-var-success-bg text-var-success-text border border-var-success-border',
      UPDATE: 'bg-var-primary-muted text-var-primary-text border border-var-primary',
      DELETE: 'bg-var-danger-bg text-var-danger-text border border-var-danger-border',
      READ: 'bg-var-surface-hover text-var-text-muted border border-var-border',
      LOGIN: 'bg-var-info-bg text-var-info-text border border-var-info-border',
      LOGOUT: 'bg-var-info-bg text-var-info-text border border-var-info-border',
    };
    return colors[action] || 'bg-var-surface-hover text-var-text-muted border border-var-border';
  };

  const handleFilterChange = (newFilters: FilterValues) => {
    setCurrentFilters(newFilters);
    onFilterChange(newFilters);
  };

  const filterConfigs: FilterConfig[] = [
    { key: 'search', label: 'Search', type: 'search', placeholder: 'Search by Email...' },
    {
      key: 'action', label: 'Action', type: 'select',
      options: filterOptions.actions.map(action => ({ value: action, label: action }))
    },
    {
      key: 'resourceType', label: 'Resource Type', type: 'select',
      options: filterOptions.resourceTypes.map(resourceType => ({ value: resourceType, label: resourceType }))
    },
    { key: 'startDate', label: 'Start Date', type: 'date' },
    { key: 'endDate', label: 'End Date', type: 'date' }
  ];

  const columns: TableColumn<AuditLogItem>[] = [
    {
      key: 'user',
      label: 'User',
      render: (log) => (
        <div className="flex items-center">
          <div className="shrink-0 h-10 w-10">
            {log.user_avatar ? (
              <Image className="h-10 w-10 rounded-full object-cover" src={log.user_avatar} alt="User avatar" width={40} height={40} />
            ) : (
              <div className="h-10 w-10 rounded-full bg-var-primary flex items-center justify-center text-white font-semibold text-sm">
                {log.user_first_name?.[0]}{log.user_last_name?.[0]}
              </div>
            )}
          </div>
          <div className="ml-4">
            <div className="text-sm font-medium text-var-text">{log.user_first_name} {log.user_last_name}</div>
            <div className="text-sm text-var-text-muted">{log.user_email}</div>
          </div>
        </div>
      )
    },
    {
      key: 'action',
      label: 'Action',
      render: (log) => (
        <span className={`inline-flex px-3 py-1 text-xs font-semibold rounded-full ${getActionColor(log.action)}`}>
          {log.action}
        </span>
      )
    },
    {
      key: 'resourceType',
      label: 'Resource Type',
      render: (log) => (
        <span className="text-sm text-var-text capitalize">
          {log.resource_type?.replace(/_/g, ' ') || '-'}
        </span>
      )
    },
    {
      key: 'ipAddress',
      label: 'IP Address',
      render: (log) => (
        <span className="text-var-text-muted font-mono text-xs">{log.ip_address}</span>
      )
    },
    {
      key: 'timestamp',
      label: 'Timestamp',
      render: (log) => (
        <span className="text-sm text-var-text-muted">{formatDate(log.created_at)}</span>
      )
    }
  ];

  const actions: TableAction<AuditLogItem>[] = [
    {
      key: 'view',
      icon: (
        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
        </svg>
      ),
      onClick: (log) => onViewLog(log),
      className: 'text-var-primary hover:text-var-primary-hover hover:bg-var-primary-muted',
      title: 'View Details'
    }
  ];

  const toggleFilters = () => setFiltersVisible(!filtersVisible);

  return (
    <div className="bg-var-surface rounded-2xl shadow-var-card border border-var-border overflow-hidden">
      <div className="px-6 py-4 border-b border-var-border bg-var-surface-hover/50">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h2 className="text-lg font-semibold text-var-text">Audit Logs</h2>
            <p className="text-sm text-var-text-secondary mt-1">Track all system activities and user actions</p>
          </div>
          <button
            onClick={toggleFilters}
            className="inline-flex items-center px-3 py-2 bg-var-surface border border-var-border text-var-text-secondary font-medium rounded-xl hover:bg-var-surface-hover hover:text-var-text transition-all duration-200 shadow-var-button"
            title={filtersVisible ? "Hide filters" : "Show filters"}
          >
            <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
            </svg>
            {filtersVisible ? 'Hide Filters' : 'Show Filters'}
          </button>
        </div>

        {filtersVisible && (
          <TableFilters
            filters={filterConfigs}
            onFilterChange={handleFilterChange}
            initialValues={currentFilters}
            showApplyButton={true}
            showResetButton={true}
          />
        )}
      </div>

      <DataTable
        data={logs as AuditLogItem[]}
        columns={columns}
        actions={actions}
        loading={loading}
        emptyMessage="No audit logs found"
        emptyDescription="Try adjusting your filters or search criteria"
        keyExtractor={(log) => log.id}
      />

      <TablePagination pagination={pagination} onPageChange={onPageChange} />
    </div>
  );
}