'use client';

import { useState, useCallback, useEffect } from 'react';
import DataTable, { Column } from '@/components/ui/DataTable';
import Pagination from '@/components/ui/Pagination';
import FilterPanel from '@/components/ui/FilterPanel';
import Toolbar from '@/components/ui/Toolbar';
import { toast } from 'react-hot-toast';
import AuditLogDetailModal from './AuditLogDetailModal';

interface AuditLog {
  id: string;
  actor_id: string | null;
  actor_name: string;
  actor_email: string | null;
  action: string;
  entity_type: string | null;
  entity_id: string | null;
  table_name: string | null;
  old_values: Record<string, unknown> | null;
  new_values: Record<string, unknown> | null;
  ip_address: string | null;
  user_agent: string | null;
  created_at: string;
}

interface TableInfo {
  table_name: string;
  count: number;
}

interface ActionInfo {
  action: string;
  count: number;
}

interface PaginationData {
  page: number;
  limit: number;
  total: number;
  totalPages: number;
}

interface AuditLogsTableProps {
  initialLogs: {
    auditLogs: AuditLog[];
    pagination: PaginationData;
  };
  tables: TableInfo[];
  canViewDetails: boolean;
}

export default function AuditLogsTable({ initialLogs, tables, canViewDetails }: AuditLogsTableProps) {
  const [logs, setLogs] = useState<AuditLog[]>(initialLogs.auditLogs);
  const [pagination, setPagination] = useState<PaginationData>(initialLogs.pagination);
  const [loading, setLoading] = useState(false);
  const [showFilters, setShowFilters] = useState(false);
  const [selectedLogId, setSelectedLogId] = useState<string | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  
  // All available actions from API
  const [allActions, setAllActions] = useState<ActionInfo[]>([]);
  const [loadingActions, setLoadingActions] = useState(false);
  
  const [search, setSearch] = useState('');
  const [tableName, setTableName] = useState('');
  const [action, setAction] = useState('');
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  
  const [tempSearch, setTempSearch] = useState('');
  const [tempTableName, setTempTableName] = useState('');
  const [tempAction, setTempAction] = useState('');
  const [tempStartDate, setTempStartDate] = useState('');
  const [tempEndDate, setTempEndDate] = useState('');
  
  const [currentPage, setCurrentPage] = useState(1);

  // Fetch all unique actions on component mount
  useEffect(() => {
    const fetchAllActions = async () => {
        setLoadingActions(true);
        try {
        const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';
        const res = await fetch(`${baseUrl}/api/audit-logs/actions`, {
            cache: 'no-store',
        });
        
        if (!res.ok) throw new Error('Failed to fetch actions');
        
        const data = await res.json();
        if (data.success) {
            setAllActions(data.data);
        }
        } catch (error) {
        console.error('Failed to fetch actions:', error);
        } finally {
        setLoadingActions(false);
        }
    };
    fetchAllActions();
  }, []);

  

  // Table options for filter
  const tableOptions = tables.map(table => ({
    value: table.table_name,
    label: `${table.table_name} (${table.count})`,
  }));

  // Action options for filter - from all actions
  const actionOptions = allActions.map(action => ({
    value: action.action,
    label: `${action.action} (${action.count})`,
  }));

  const columns: Column<AuditLog>[] = [
    {
      key: 'action',
      header: 'Action',
      render: (log: AuditLog) => (
        <span 
          className="inline-flex px-2 py-1 text-xs font-medium rounded-md"
          style={{
            background: 'var(--color-info-light)',
            color: 'var(--color-info)',
          }}
        >
          {log.action}
        </span>
      )
    },
    {
      key: 'table_name',
      header: 'Table',
      render: (log: AuditLog) => (
        <span className="text-sm" style={{ color: 'var(--color-text-secondary)' }}>
          {log.table_name || 'N/A'}
        </span>
      )
    },
    {
      key: 'actor',
      header: 'Actor',
      render: (log: AuditLog) => (
        <div>
          <div className="text-sm font-medium" style={{ color: 'var(--color-text)' }}>
            {log.actor_name}
          </div>
          {log.actor_email && (
            <div className="text-xs" style={{ color: 'var(--color-text-muted)' }}>
              {log.actor_email}
            </div>
          )}
        </div>
      )
    },
    {
      key: 'entity',
      header: 'Entity',
      render: (log: AuditLog) => (
        <div>
          <div className="text-sm" style={{ color: 'var(--color-text)' }}>
            {log.entity_type || 'N/A'}
          </div>
          {log.entity_id && (
            <div className="text-xs font-mono" style={{ color: 'var(--color-text-muted)' }}>
              #{log.entity_id.substring(0, 8)}
            </div>
          )}
        </div>
      )
    },
    {
      key: 'created_at',
      header: 'Timestamp',
      render: (log: AuditLog) => (
        <div>
          <div className="text-sm" style={{ color: 'var(--color-text)' }}>
            {new Date(log.created_at).toLocaleDateString()}
          </div>
          <div className="text-xs" style={{ color: 'var(--color-text-muted)' }}>
            {new Date(log.created_at).toLocaleTimeString()}
          </div>
        </div>
      )
    }
  ];

  if (canViewDetails) {
    columns.push({
      key: 'actions',
      header: 'Actions',
      className: 'text-right',
      render: (log: AuditLog) => (
        <button
          onClick={() => {
            setSelectedLogId(log.id);
            setIsModalOpen(true);
          }}
          className="p-1 rounded hover:bg-surface-alt transition-colors"
          style={{ color: 'var(--color-info)' }}
          title="View Details"
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
            <circle cx="12" cy="12" r="3"/>
          </svg>
        </button>
      )
    });
  }

  const filterFields = [
    {
      name: 'search',
      label: 'Search',
      type: 'text' as const,
      placeholder: 'Search by email, entity, table...',
      value: tempSearch,
      onChange: setTempSearch
    },
    {
      name: 'table_name',
      label: 'Table',
      type: 'select' as const,
      placeholder: 'All Tables',
      options: tableOptions,
      value: tempTableName,
      onChange: setTempTableName
    },
    {
      name: 'action',
      label: 'Action',
      type: 'select' as const,
      placeholder: loadingActions ? 'Loading...' : 'All Actions',
      options: actionOptions,
      value: tempAction,
      onChange: setTempAction,
      disabled: loadingActions
    },
    {
      name: 'startDate',
      label: 'Start Date',
      type: 'date' as const,
      value: tempStartDate,
      onChange: setTempStartDate
    },
    {
      name: 'endDate',
      label: 'End Date',
      type: 'date' as const,
      value: tempEndDate,
      onChange: setTempEndDate
    }
  ];

  const fetchLogs = useCallback(async (page: number, filters?: {
    search?: string;
    table_name?: string;
    action?: string;
    startDate?: string;
    endDate?: string;
  }) => {
    setLoading(true);
    
    try {
      const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';
      const params = new URLSearchParams();
      
      params.append('page', page.toString());
      params.append('limit', '20');
      
      const searchValue = filters?.search !== undefined ? filters.search : search;
      const tableNameValue = filters?.table_name !== undefined ? filters.table_name : tableName;
      const actionValue = filters?.action !== undefined ? filters.action : action;
      const startDateValue = filters?.startDate !== undefined ? filters.startDate : startDate;
      const endDateValue = filters?.endDate !== undefined ? filters.endDate : endDate;
      
      if (searchValue && searchValue.trim()) params.append('search', searchValue);
      if (tableNameValue) params.append('table_name', tableNameValue);
      if (actionValue) params.append('action', actionValue);
      if (startDateValue) params.append('startDate', startDateValue);
      if (endDateValue) params.append('endDate', endDateValue);
      
      const res = await fetch(`${baseUrl}/api/audit-logs?${params.toString()}`, {
        cache: 'no-store',
      });
      
      if (!res.ok) throw new Error('Failed to fetch');
      
      const data = await res.json();
      setLogs(data.data.auditLogs);
      setPagination(data.data.pagination);
      setCurrentPage(page);
    } catch (error) {
      console.error('Failed to fetch audit logs:', error);
      toast.error('Failed to load audit logs');
    } finally {
      setLoading(false);
    }
  }, [search, tableName, action, startDate, endDate]);

  const handleToggleFilters = useCallback(() => {
    if (!showFilters) {
      setTempSearch(search);
      setTempTableName(tableName);
      setTempAction(action);
      setTempStartDate(startDate);
      setTempEndDate(endDate);
    }
    setShowFilters(!showFilters);
  }, [showFilters, search, tableName, action, startDate, endDate]);

  const handleApplyFilters = useCallback(() => {
    setSearch(tempSearch);
    setTableName(tempTableName);
    setAction(tempAction);
    setStartDate(tempStartDate);
    setEndDate(tempEndDate);
    fetchLogs(1, {
      search: tempSearch,
      table_name: tempTableName,
      action: tempAction,
      startDate: tempStartDate,
      endDate: tempEndDate
    });
  }, [tempSearch, tempTableName, tempAction, tempStartDate, tempEndDate, fetchLogs]);

  const handleResetFilters = useCallback(() => {
    setTempSearch('');
    setTempTableName('');
    setTempAction('');
    setTempStartDate('');
    setTempEndDate('');
    setSearch('');
    setTableName('');
    setAction('');
    setStartDate('');
    setEndDate('');
    fetchLogs(1, {
      search: '',
      table_name: '',
      action: '',
      startDate: '',
      endDate: ''
    });
  }, [fetchLogs]);

  const handlePageChange = useCallback((page: number) => {
    if (page < 1 || page > pagination.totalPages) return;
    fetchLogs(page);
  }, [pagination.totalPages, fetchLogs]);

  return (
    <>
      <div className="space-y-4">
        <Toolbar
          leftActions={
            <button
              onClick={handleToggleFilters}
              className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all border"
              style={{ 
                borderColor: 'var(--color-border)',
                color: 'var(--color-text)',
                background: 'var(--color-surface)'
              }}
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M3 6h18M6 12h12M10 18h4"/>
              </svg>
              {showFilters ? 'Hide Filters' : 'Show Filters'}
            </button>
          }
        />
        
        {showFilters && (
          <FilterPanel
            fields={filterFields}
            onApply={handleApplyFilters}
            onReset={handleResetFilters}
            applyButtonText="Apply Filters"
            resetButtonText="Reset"
          />
        )}
        
        <DataTable
          columns={columns}
          data={logs}
          loading={loading}
          getRowId={(log) => log.id}
          emptyMessage="No audit logs found"
          skeletonRows={10}
        />
        
        {!loading && pagination.totalPages > 0 && (
          <Pagination
            currentPage={currentPage}
            totalPages={pagination.totalPages}
            totalItems={pagination.total}
            itemsPerPage={pagination.limit}
            onPageChange={handlePageChange}
            showItemsInfo={true}
          />
        )}
      </div>

      <AuditLogDetailModal
        isOpen={isModalOpen}
        logId={selectedLogId}
        onClose={() => {
          setIsModalOpen(false);
          setSelectedLogId(null);
        }}
      />
    </>
  );
}