'use client';

import { useState, useEffect, useCallback } from 'react';
import { FileText, Filter, Download, User, Clock, Activity } from 'lucide-react';
import { auditLogsAPI } from '@/lib/api/admin';
import type { AuditLog } from '@/lib/api/admin';
import LoadingSpinner from '@/components/LoadingSpinner';

export default function AuditLogs() {
  const [logs, setLogs] = useState<AuditLog[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(20);
  const [entityType, setEntityType] = useState('');
  const [action, setAction] = useState('');
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');

  const fetchLogs = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await auditLogsAPI.getAll({
        entityType: entityType || undefined,
        action: action || undefined,
        startDate: startDate || undefined,
        endDate: endDate || undefined,
        page,
        pageSize,
      });
      setLogs(res.data);
      setTotal(res.pagination.total);
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'فشل تحميل السجل');
    } finally {
      setLoading(false);
    }
  }, [entityType, action, startDate, endDate, page, pageSize]);

  useEffect(() => {
    fetchLogs();
  }, [fetchLogs]);

  const formatDate = (d: string | null | undefined) =>
    d ? new Date(d).toLocaleString('ar-SA', { dateStyle: 'medium', timeStyle: 'short' }) : '-';

  const getActionLabel = (a: string) => {
    const labels: Record<string, string> = {
      CREATE: 'إنشاء',
      UPDATE: 'تحديث',
      DELETE: 'حذف',
      ACTIVATE: 'تفعيل',
      DEACTIVATE: 'تعطيل',
    };
    return labels[a] || a;
  };

  const handleExport = () => {
    const headers = ['المستخدم', 'نوع الكيان', 'الإجراء', 'التاريخ'];
    const rows = logs.map((l) => [
      l.user?.username || l.userId,
      l.entityType,
      getActionLabel(l.action),
      formatDate(l.createdAt),
    ]);
    const csv = [headers.join(','), ...rows.map((r) => r.join(','))].join('\n');
    const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `audit-logs-${new Date().toISOString().slice(0, 10)}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div>
      <div className="mb-8 flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 mb-2">سجل العمليات</h1>
          <p className="text-gray-600">عرض وتتبع جميع العمليات التي تمت على النظام</p>
        </div>
        <button
          onClick={handleExport}
          className="flex items-center gap-2 px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-all shadow-md hover:shadow-lg"
        >
          <Download className="h-5 w-5" />
          <span className="font-semibold">تصدير السجل</span>
        </button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
        <div className="bg-white rounded-xl shadow-md p-6 border border-gray-100">
          <div className="bg-blue-500 w-12 h-12 rounded-lg flex items-center justify-center mb-3">
            <Activity className="h-6 w-6 text-white" />
          </div>
          <h3 className="text-2xl font-bold text-gray-900 mb-1">{total}</h3>
          <p className="text-sm text-gray-600">إجمالي العمليات في الصفحة الحالية</p>
        </div>
        <div className="bg-white rounded-xl shadow-md p-6 border border-gray-100">
          <div className="bg-green-500 w-12 h-12 rounded-lg flex items-center justify-center mb-3">
            <FileText className="h-6 w-6 text-white" />
          </div>
          <h3 className="text-2xl font-bold text-gray-900 mb-1">{logs.length}</h3>
          <p className="text-sm text-gray-600">عرض في هذه الصفحة</p>
        </div>
      </div>

      <div className="bg-white rounded-xl shadow-md p-6 mb-8 border border-gray-100">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <input
            type="text"
            placeholder="نوع الكيان..."
            value={entityType}
            onChange={(e) => setEntityType(e.target.value)}
            className="px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          />
          <select
            value={action}
            onChange={(e) => setAction(e.target.value)}
            className="px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          >
            <option value="">جميع الإجراءات</option>
            <option value="CREATE">إنشاء</option>
            <option value="UPDATE">تحديث</option>
            <option value="DELETE">حذف</option>
            <option value="ACTIVATE">تفعيل</option>
            <option value="DEACTIVATE">تعطيل</option>
          </select>
          <input
            type="date"
            value={startDate}
            onChange={(e) => setStartDate(e.target.value)}
            className="px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          />
          <input
            type="date"
            value={endDate}
            onChange={(e) => setEndDate(e.target.value)}
            className="px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          />
        </div>
        <button
          onClick={() => setPage(1)}
          className="mt-4 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-sm font-medium"
        >
          بحث
        </button>
      </div>

      <div className="bg-white rounded-xl shadow-md border border-gray-100 overflow-hidden">
        {loading ? (
          <div className="p-12 flex justify-center">
            <LoadingSpinner />
          </div>
        ) : error ? (
          <div className="p-12 text-center text-red-600">{error}</div>
        ) : (
          <>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-50 border-b border-gray-200">
                  <tr>
                    <th className="px-6 py-4 text-right text-sm font-semibold text-gray-900">المستخدم</th>
                    <th className="px-6 py-4 text-right text-sm font-semibold text-gray-900">نوع الكيان</th>
                    <th className="px-6 py-4 text-right text-sm font-semibold text-gray-900">الإجراء</th>
                    <th className="px-6 py-4 text-right text-sm font-semibold text-gray-900">التفاصيل</th>
                    <th className="px-6 py-4 text-right text-sm font-semibold text-gray-900">التاريخ</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200">
                  {logs.map((log) => (
                    <tr key={log.id} className="hover:bg-gray-50 transition-colors">
                      <td className="px-6 py-4">
                        <div className="flex items-center gap-2">
                          <User className="h-4 w-4 text-gray-400" />
                          <span className="font-medium text-gray-900 text-sm">
                            {log.user?.username || log.userId}
                          </span>
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        <span className="text-sm font-medium text-blue-600">{log.entityType}</span>
                      </td>
                      <td className="px-6 py-4">
                        <span className="text-sm text-gray-700">{getActionLabel(log.action)}</span>
                      </td>
                      <td className="px-6 py-4">
                        <span className="text-sm text-gray-600">
                          {log.entityType} #{log.entityId.slice(0, 8)}...
                        </span>
                      </td>
                      <td className="px-6 py-4">
                        <div className="flex items-center gap-2">
                          <Clock className="h-4 w-4 text-gray-400" />
                          <span className="text-sm text-gray-700">{formatDate(log.createdAt)}</span>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            <div className="px-6 py-4 border-t border-gray-200 flex items-center justify-between">
              <p className="text-sm text-gray-600">
                عرض{' '}
                <span className="font-semibold">
                  {logs.length ? (page - 1) * pageSize + 1 : 0}-{Math.min(page * pageSize, total)}
                </span>{' '}
                من <span className="font-semibold">{total}</span> عملية
              </p>
              <div className="flex gap-2">
                <button
                  onClick={() => setPage((p) => Math.max(1, p - 1))}
                  disabled={page <= 1}
                  className="px-4 py-2 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  السابق
                </button>
                <span className="px-4 py-2 text-sm text-gray-600">
                  صفحة {page} من {Math.max(1, Math.ceil(total / pageSize))}
                </span>
                <button
                  onClick={() => setPage((p) => Math.min(Math.ceil(total / pageSize) || 1, p + 1))}
                  disabled={page >= Math.ceil(total / pageSize)}
                  className="px-4 py-2 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  التالي
                </button>
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
