'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: any[] = Array.isArray(data?.items) ? 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 className="flex items-center justify-between">
        <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>
        <ActionButton
          icon={Download}
          variant="secondary"
          onClick={() => {
            const items: any[] = Array.isArray(data?.items) ? data!.items : [];
            if (!items.length) return;
            const headers = ['Timestamp', 'Action', 'Entity Type', 'Entity ID', 'User ID', 'IP Address'];
            const rows = items.map((l: any) => [
              formatDateTime(l.createdAt),
              l.action,
              l.entityType,
              l.entityId || '',
              l.iamUserId || l.userId || '',
              l.ipAddress || '',
            ]);
            const csv = [headers, ...rows].map(r => r.map((v: string) => `"${String(v).replace(/"/g, '""')}"`).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-logs-${new Date().toISOString().split('T')[0]}.csv`;
            a.click();
            URL.revokeObjectURL(url);
          }}
        >
          Export CSV
        </ActionButton>
      </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="Audit Log Details"
        size="xl"
      >
        {selectedLog && (() => {
          const l = selectedLog;
          const actionColor: Record<string, string> = {
            CREATE: 'from-emerald-600 to-emerald-700',
            UPDATE: 'from-blue-600 to-blue-700',
            DELETE: 'from-red-600 to-red-700',
            LOGIN:  'from-violet-600 to-violet-700',
            LOGOUT: 'from-gray-600 to-gray-700',
          };
          const gradient = actionColor[l.action] || 'from-gray-600 to-gray-700';

          const Field = ({ label, value, mono = false, truncate = false }: { label: string; value: string; mono?: boolean; truncate?: boolean }) => (
            <div className="bg-muted/40 rounded-lg p-3">
              <p className="text-xs text-muted-foreground mb-1">{label}</p>
              <p className={`text-sm font-semibold text-foreground${mono ? ' font-mono' : ''}${truncate ? ' truncate' : ''}`} title={value}>{value || '—'}</p>
            </div>
          );

          const SectionHeader = ({ title }: { title: string }) => (
            <h3 className="text-xs font-bold uppercase tracking-widest text-muted-foreground mb-3 flex items-center gap-2">
              <span className="w-4 h-px bg-muted-foreground/40 inline-block" />{title}
            </h3>
          );

          return (
            <div>
              <div className={`-mx-6 -mt-4 mb-6 px-6 py-5 bg-gradient-to-r ${gradient} rounded-t-lg`}>
                <div className="flex items-start justify-between gap-4">
                  <div>
                    <p className="text-white/70 text-xs font-semibold uppercase tracking-widest mb-1">Action</p>
                    <p className="text-white text-2xl font-bold">{l.action}</p>
                  </div>
                  <div className="text-right shrink-0">
                    <span className="inline-block bg-white/20 text-white text-xs font-mono px-3 py-1 rounded-full">{l.entityType}</span>
                    <p className="text-white/70 text-xs mt-2">{formatDateTime(l.createdAt)}</p>
                  </div>
                </div>
                <div className="mt-4 grid grid-cols-2 gap-3">
                  <div className="bg-white/10 rounded-lg px-3 py-2">
                    <p className="text-white/70 text-xs">User</p>
                    <p className="text-white text-sm font-bold truncate">{l.user?.fullName || 'System'}</p>
                  </div>
                  <div className="bg-white/10 rounded-lg px-3 py-2">
                    <p className="text-white/70 text-xs">IP Address</p>
                    <p className="text-white text-sm font-mono font-bold">{l.ipAddress || 'N/A'}</p>
                  </div>
                </div>
              </div>

              <div className="space-y-6">
                <section>
                  <SectionHeader title="Event Details" />
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                    <Field label="Action" value={l.action} />
                    <Field label="Entity Type" value={l.entityType} mono />
                    <Field label="Entity ID" value={l.entityId || 'System'} mono truncate />
                    <Field label="Timestamp" value={formatDateTime(l.createdAt)} />
                  </div>
                </section>

                {l.user && (
                  <section>
                    <SectionHeader title="User Information" />
                    <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                      <Field label="Full Name" value={l.user.fullName} />
                      <Field label="Email" value={l.user.email} truncate />
                      <Field label="User ID" value={l.userId} mono truncate />
                    </div>
                  </section>
                )}

                {(l.ipAddress || l.userAgent) && (
                  <section>
                    <SectionHeader title="Network Information" />
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                      <Field label="IP Address" value={l.ipAddress} mono />
                      <div className="bg-muted/40 rounded-lg p-3">
                        <p className="text-xs text-muted-foreground mb-1">User Agent</p>
                        <p className="text-xs font-mono text-foreground break-all leading-relaxed">{l.userAgent || '—'}</p>
                      </div>
                    </div>
                  </section>
                )}

                {(l.oldData || l.newData) && (
                  <section>
                    <SectionHeader title="Data Changes" />
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                      {l.oldData && (
                        <div>
                          <p className="text-xs font-bold text-red-600 dark:text-red-400 mb-2 uppercase tracking-wide">← Before</p>
                          <pre className="text-xs p-3 bg-red-50 dark:bg-red-950/20 rounded-lg border border-red-200 dark:border-red-900 overflow-auto max-h-52 text-muted-foreground leading-relaxed">
                            {formatJsonData(l.oldData)}
                          </pre>
                        </div>
                      )}
                      {l.newData && (
                        <div>
                          <p className="text-xs font-bold text-emerald-600 dark:text-emerald-400 mb-2 uppercase tracking-wide">→ After</p>
                          <pre className="text-xs p-3 bg-emerald-50 dark:bg-emerald-950/20 rounded-lg border border-emerald-200 dark:border-emerald-900 overflow-auto max-h-52 text-muted-foreground leading-relaxed">
                            {formatJsonData(l.newData)}
                          </pre>
                        </div>
                      )}
                    </div>
                  </section>
                )}

                <section>
                  <SectionHeader title="System" />
                  <div className="grid grid-cols-1 gap-3">
                    <Field label="Log ID" value={l.id} mono truncate />
                  </div>
                </section>
              </div>

              <div className="flex justify-end gap-2 pt-6 mt-2 border-t border-muted">
                <ActionButton variant="secondary" onClick={() => { setShowDetailsModal(false); setSelectedLog(null); }}>Close</ActionButton>
              </div>
            </div>
          );
        })()}
      </Modal>
    </div>
  );
}
