"use client";

import { useEffect, useState } from "react";
import { getAuditLogs, AuditLog } from "@/lib/api";
import { Search, Calendar, Filter } from "lucide-react";

export function AuditLogsTab(_props?: { workspaceId?: string }) {
  const [logs, setLogs] = useState<AuditLog[]>([]);
  const [loading, setLoading] = useState(true);
  const [fromDate, setFromDate] = useState("");
  const [toDate, setToDate] = useState("");
  const [actionFilter, setActionFilter] = useState("");
  const [search, setSearch] = useState("");

  const loadLogs = () => {
    setLoading(true);
    getAuditLogs({
      from: fromDate || undefined,
      to: toDate || undefined,
      action: actionFilter || undefined,
    })
      .then(setLogs)
      .catch(console.error)
      .finally(() => setLoading(false));
  };

  useEffect(() => {
    loadLogs();
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  const filteredLogs = logs.filter((log) => {
    if (!search.trim()) return true;
    const text = `${log.action} ${log.actor?.name || ""} ${log.actor?.email || ""} ${log.details || ""}`.toLowerCase();
    return text.includes(search.toLowerCase());
  });

  const formatDate = (dateStr: string) => {
    try {
      return new Date(dateStr).toLocaleString();
    } catch {
      return dateStr;
    }
  };

  return (
    <div className="space-y-4">
      {/* Filters */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
        <div className="flex flex-wrap items-end gap-4">
          <div>
            <label className="block text-xs font-semibold text-gray-500 mb-1">From</label>
            <input
              type="date"
              value={fromDate}
              onChange={(e) => setFromDate(e.target.value)}
              className="px-3 py-1.5 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-slack-purple focus:border-transparent text-sm"
            />
          </div>
          <div>
            <label className="block text-xs font-semibold text-gray-500 mb-1">To</label>
            <input
              type="date"
              value={toDate}
              onChange={(e) => setToDate(e.target.value)}
              className="px-3 py-1.5 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-slack-purple focus:border-transparent text-sm"
            />
          </div>
          <div>
            <label className="block text-xs font-semibold text-gray-500 mb-1">Action</label>
            <select
              value={actionFilter}
              onChange={(e) => setActionFilter(e.target.value)}
              className="px-3 py-1.5 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-slack-purple focus:border-transparent text-sm bg-white"
            >
              <option value="">All actions</option>
              <option value="user.create">User Created</option>
              <option value="user.update">User Updated</option>
              <option value="user.suspend">User Suspended</option>
              <option value="channel.create">Channel Created</option>
              <option value="channel.delete">Channel Deleted</option>
              <option value="message.delete">Message Deleted</option>
              <option value="role.change">Role Changed</option>
              <option value="emoji.upload">Emoji Uploaded</option>
            </select>
          </div>
          <button
            onClick={loadLogs}
            className="flex items-center gap-1.5 px-4 py-1.5 rounded-md bg-slack-purple text-white text-sm font-medium hover:bg-slack-darkpurple transition-colors"
          >
            <Filter size={14} />
            Apply
          </button>
          <div className="flex-1 min-w-[200px]">
            <div className="relative">
              <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none" />
              <input
                type="text"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="Search logs..."
                className="w-full pl-9 pr-3 py-1.5 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-slack-purple focus:border-transparent text-sm"
              />
            </div>
          </div>
        </div>
      </div>

      {/* Logs table */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
        {loading ? (
          <div className="p-6 text-sm text-gray-400 animate-pulse">Loading audit logs...</div>
        ) : filteredLogs.length === 0 ? (
          <div className="p-6 text-sm text-gray-400 text-center">
            <Calendar size={32} className="mx-auto mb-2 text-gray-300" />
            No audit logs found.
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-gray-50 border-b border-gray-200">
                <tr>
                  <th className="px-4 py-2 text-left font-semibold text-gray-600">Date</th>
                  <th className="px-4 py-2 text-left font-semibold text-gray-600">Action</th>
                  <th className="px-4 py-2 text-left font-semibold text-gray-600">Actor</th>
                  <th className="px-4 py-2 text-left font-semibold text-gray-600">Target</th>
                  <th className="px-4 py-2 text-left font-semibold text-gray-600">Details</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {filteredLogs.map((log) => (
                  <tr key={log.id} className="hover:bg-gray-50">
                    <td className="px-4 py-2 text-gray-500 whitespace-nowrap">{formatDate(log.created_at)}</td>
                    <td className="px-4 py-2">
                      <span className="inline-block px-2 py-0.5 rounded-md bg-slack-purple/10 text-slack-purple text-xs font-medium">
                        {log.action}
                      </span>
                    </td>
                    <td className="px-4 py-2 text-gray-700">{log.actor?.name || log.actor?.email || "Unknown"}</td>
                    <td className="px-4 py-2 text-gray-600">{log.target || "-"}</td>
                    <td className="px-4 py-2 text-gray-500 max-w-xs truncate">{log.details || "-"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}