'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Eye, Download } from 'lucide-react';
import DataTable from '@/components/ui/DataTable';
import Badge from '@/components/ui/Badge';
import { auditApi } from '@/lib/api';
import { formatDateTime } from '@/lib/utils';
import Modal from '@/components/ui/Modal';
import ActionButton from '@/components/ui/ActionButton';

export default function AuditLogsPage() {
  const [filters, setFilters] = useState({ search: '', action: '', entityType: '' });
  const [selectedLog, setSelectedLog] = useState<any>(null);
  const [showDetailsModal, setShowDetailsModal] = useState(false);

  const { data, isLoading } = useQuery({
    queryKey: ['audit-logs', filters],
    queryFn: () => auditApi.getLogs(filters),
    refetchInterval: 30000, // Refetch every 30 seconds
  });

  const getActionBadgeColor = (action: string) => {
    switch (action) {
      case 'CREATE':
        return 'success';
      case 'UPDATE':
        return 'primary';
      case 'DELETE':
        return 'danger';
      case 'LOGIN':
        return 'info';
      case 'LOGOUT':
        return 'secondary';
      default:
        return 'secondary';
    }
  };

  const formatJsonData = (data: any) => {
    if (!data) return 'N/A';
    try {
      return JSON.stringify(data, null, 2);
    } catch {
      return String(data);
    }
  };

  const columns = [
    {
      key: 'createdAt',
      label: 'Timestamp',
      sortable: true,
      render: (log: any) => (
        <div className="text-sm">
          <div className="font-medium">{formatDateTime(log.createdAt)}</div>
          <div className="text-xs text-muted-foreground">{new Date(log.createdAt).toLocaleTimeString()}</div>
        </div>
      ),
    },
    {
      key: 'action',
      label: 'Action',
      sortable: true,
      render: (log: any) => (
        <Badge className={getActionBadgeColor(log.action)}>
          {log.action}
        </Badge>
      ),
    },
    {
      key: 'entityType',
      label: 'Entity Type',
      sortable: true,
      render: (log: any) => (
        <span className="px-2 py-1 bg-gray-100 dark:bg-gray-700 rounded text-xs font-medium">
          {log.entityType}
        </span>
      ),
    },
    {
      key: 'entityId',
      label: 'Entity ID',
      render: (log: any) => (
        <span className="font-mono text-xs text-muted-foreground">
          {log.entityId ? log.entityId.substring(0, 12) : 'System'}
        </span>
      ),
    },
    {
      key: 'user',
      label: 'User',
      render: (log: any) => (
        <div>
          <div className="font-medium text-sm">{log.user?.fullName || 'System'}</div>
          <div className="text-xs text-muted-foreground">{log.user?.email || log.userId || 'N/A'}</div>
        </div>
      ),
    },
    {
      key: 'ipAddress',
      label: 'IP Address',
      render: (log: any) => (
        <span className="text-xs text-muted-foreground font-mono">
          {log.ipAddress || 'N/A'}
        </span>
      ),
    },
  ];

  const actions = [
    {
      label: 'View Details',
      onClick: (log: any) => {
        setSelectedLog(log);
        setShowDetailsModal(true);
      },
      variant: 'secondary' as const,
      icon: Eye,
    },
  ];

  const logs = data?.items || [];
  const stats = {
    total: logs.length,
    creates: logs.filter((l: any) => l.action === 'CREATE').length,
    updates: logs.filter((l: any) => l.action === 'UPDATE').length,
    deletes: logs.filter((l: any) => l.action === 'DELETE').length,
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-foreground">Audit Logs</h1>
        <p className="text-muted-foreground mt-1">Track all system activities and changes</p>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="card">
          <div className="text-muted-foreground text-sm font-medium">Total Logs</div>
          <div className="text-2xl font-bold mt-2">{stats.total}</div>
        </div>
        <div className="card">
          <div className="text-green-600 text-sm font-medium">Created</div>
          <div className="text-2xl font-bold mt-2">{stats.creates}</div>
        </div>
        <div className="card">
          <div className="text-blue-600 text-sm font-medium">Updated</div>
          <div className="text-2xl font-bold mt-2">{stats.updates}</div>
        </div>
        <div className="card">
          <div className="text-red-600 text-sm font-medium">Deleted</div>
          <div className="text-2xl font-bold mt-2">{stats.deletes}</div>
        </div>
      </div>

      {/* Filters */}
      <div className="card">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div>
            <label className="label">Search (User/Entity ID)</label>
            <input
              type="text"
              placeholder="Search logs..."
              className="input"
              value={filters.search}
              onChange={(e) => setFilters({ ...filters, search: e.target.value })}
            />
          </div>
          <div>
            <label className="label">Action</label>
            <select
              className="input"
              value={filters.action}
              onChange={(e) => setFilters({ ...filters, action: e.target.value })}
            >
              <option value="">All Actions</option>
              <option value="CREATE">Create</option>
              <option value="UPDATE">Update</option>
              <option value="DELETE">Delete</option>
              <option value="LOGIN">Login</option>
              <option value="LOGOUT">Logout</option>
            </select>
          </div>
          <div>
            <label className="label">Entity Type</label>
            <select
              className="input"
              value={filters.entityType}
              onChange={(e) => setFilters({ ...filters, entityType: e.target.value })}
            >
              <option value="">All Types</option>
              <optgroup label="Master Data">
                <option value="Station">Station</option>
                <option value="Route">Route</option>
                <option value="RouteStop">Route Stop</option>
                <option value="Train">Train</option>
                <option value="TrainSchedule">Train Schedule</option>
                <option value="Coach">Coach</option>
                <option value="CoachType">Coach Type</option>
                <option value="SeatClass">Seat Class</option>
                <option value="FareRule">Fare Rule</option>
                <option value="RouteFareRule">Route Fare Rule</option>
                <option value="SegmentFareRule">Segment Fare Rule</option>
                <option value="BaggageAllowance">Baggage Allowance</option>
              </optgroup>
              <optgroup label="Operations">
                <option value="Booking">Booking</option>
                <option value="Payment">Payment</option>
                <option value="Ticket">Ticket</option>
                <option value="Seat">Seat</option>
                <option value="SeatBlock">Seat Block</option>
              </optgroup>
              <optgroup label="Users & Access">
                <option value="User">User</option>
                <option value="Agent">Agent</option>
                <option value="Passenger">Passenger</option>
              </optgroup>
              <optgroup label="System & Features">
                <option value="Notification">Notification</option>
                <option value="Promotion">Promotion</option>
                <option value="Loyalty">Loyalty</option>
                <option value="Wallet">Wallet</option>
                <option value="FraudAlert">Fraud Alert</option>
                <option value="FraudRule">Fraud Rule</option>
              </optgroup>
            </select>
          </div>
          <div className="flex items-end">
            <ActionButton
              variant="secondary"
              onClick={() => setFilters({ search: '', action: '', entityType: '' })}
              className="w-full"
            >
              Clear Filters
            </ActionButton>
          </div>
        </div>
      </div>

      {/* Data Table */}
      <DataTable
        data={logs}
        columns={columns}
        actions={actions}
        loading={isLoading}
        emptyMessage="No audit logs found"
      />

      {/* Details Modal */}
      <Modal
        isOpen={showDetailsModal}
        onClose={() => {
          setShowDetailsModal(false);
          setSelectedLog(null);
        }}
        title={`${selectedLog?.action} - ${selectedLog?.entityType}`}
        size="lg"
      >
        <div className="space-y-4">
          {/* Basic Info */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="text-xs font-semibold text-muted-foreground">Timestamp</label>
              <p className="text-sm mt-1">{formatDateTime(selectedLog?.createdAt)}</p>
            </div>
            <div>
              <label className="text-xs font-semibold text-muted-foreground">Action</label>
              <p className="text-sm mt-1">
                <Badge className={getActionBadgeColor(selectedLog?.action)}>
                  {selectedLog?.action}
                </Badge>
              </p>
            </div>
            <div>
              <label className="text-xs font-semibold text-muted-foreground">Entity Type</label>
              <p className="text-sm mt-1 font-mono">{selectedLog?.entityType}</p>
            </div>
            <div>
              <label className="text-xs font-semibold text-muted-foreground">Entity ID</label>
              <p className="text-sm mt-1 font-mono text-muted-foreground">
                {selectedLog?.entityId || 'System'}
              </p>
            </div>
          </div>

          {/* User Info */}
          {selectedLog?.user && (
            <div className="border-t pt-4">
              <h4 className="text-sm font-semibold mb-2">User Information</h4>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-xs font-semibold text-muted-foreground">Name</label>
                  <p className="text-sm mt-1">{selectedLog?.user?.fullName}</p>
                </div>
                <div>
                  <label className="text-xs font-semibold text-muted-foreground">Email</label>
                  <p className="text-sm mt-1">{selectedLog?.user?.email}</p>
                </div>
              </div>
            </div>
          )}

          {/* Network Info */}
          {(selectedLog?.ipAddress || selectedLog?.userAgent) && (
            <div className="border-t pt-4">
              <h4 className="text-sm font-semibold mb-2">Network Information</h4>
              <div className="space-y-2">
                {selectedLog?.ipAddress && (
                  <div>
                    <label className="text-xs font-semibold text-muted-foreground">IP Address</label>
                    <p className="text-sm mt-1 font-mono">{selectedLog?.ipAddress}</p>
                  </div>
                )}
                {selectedLog?.userAgent && (
                  <div>
                    <label className="text-xs font-semibold text-muted-foreground">User Agent</label>
                    <p className="text-xs mt-1 font-mono break-all text-muted-foreground">
                      {selectedLog?.userAgent}
                    </p>
                  </div>
                )}
              </div>
            </div>
          )}

          {/* Changes */}
          {(selectedLog?.oldData || selectedLog?.newData) && (
            <div className="border-t pt-4">
              <h4 className="text-sm font-semibold mb-2">Data Changes</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {selectedLog?.oldData && (
                  <div>
                    <label className="text-xs font-semibold text-red-600">Old Data</label>
                    <pre className="text-xs mt-1 p-2 bg-red-50 dark:bg-red-950/20 rounded border border-red-200 dark:border-red-900 overflow-auto max-h-48 text-muted-foreground">
                      {formatJsonData(selectedLog?.oldData)}
                    </pre>
                  </div>
                )}
                {selectedLog?.newData && (
                  <div>
                    <label className="text-xs font-semibold text-green-600">New Data</label>
                    <pre className="text-xs mt-1 p-2 bg-green-50 dark:bg-green-950/20 rounded border border-green-200 dark:border-green-900 overflow-auto max-h-48 text-muted-foreground">
                      {formatJsonData(selectedLog?.newData)}
                    </pre>
                  </div>
                )}
              </div>
            </div>
          )}

          {/* Raw Log ID */}
          <div className="border-t pt-4">
            <label className="text-xs font-semibold text-muted-foreground">Log ID</label>
            <p className="text-xs mt-1 font-mono text-muted-foreground break-all">{selectedLog?.id}</p>
          </div>
        </div>
      </Modal>
    </div>
  );
}
