"use client";

import { useState, useEffect } from "react";
import {
  Search,
  Filter,
  Download,
  ChevronLeft,
  ChevronRight,
  CheckCircle,
  XCircle,
  Eye,
  X,
  RefreshCw,
} from "lucide-react";

interface AuditLog {
  id: string;
  userId: string | null;
  type: string;
  action: string;
  success: boolean;
  ip: string;
  userAgent: string | null;
  metadata: Record<string, unknown> | null;
  createdAt: string;
  user: {
    id: string;
    email: string;
    name: string | null;
  } | null;
}

interface Filters {
  type: string;
  action: string;
  success: string;
  ip: string;
  startDate: string;
  endDate: string;
}

export default function AuditLogViewer() {
  const [logs, setLogs] = useState<AuditLog[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [total, setTotal] = useState(0);
  const [types, setTypes] = useState<string[]>([]);
  const [showFilters, setShowFilters] = useState(false);
  const [selectedLog, setSelectedLog] = useState<AuditLog | null>(null);
  const [filters, setFilters] = useState<Filters>({
    type: "",
    action: "",
    success: "",
    ip: "",
    startDate: "",
    endDate: "",
  });

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

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

  const fetchTypes = async () => {
    try {
      const response = await fetch(
        "/api/staff/dashboard/security/audit-logs?action=types",
      );
      if (response.ok) {
        const data = await response.json();
        setTypes(data.types);
      }
    } catch (error) {
      console.error("Failed to fetch audit log types:", error);
    }
  };

  const fetchLogs = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: page.toString(),
        limit: "25",
      });

      if (filters.type) params.append("type", filters.type);
      if (filters.action) params.append("action", filters.action);
      if (filters.success) params.append("success", filters.success);
      if (filters.ip) params.append("ip", filters.ip);
      if (filters.startDate) params.append("startDate", filters.startDate);
      if (filters.endDate) params.append("endDate", filters.endDate);

      const response = await fetch(
        `/api/staff/dashboard/security/audit-logs?${params}`,
      );
      if (response.ok) {
        const data = await response.json();
        setLogs(data.logs);
        setTotalPages(data.totalPages);
        setTotal(data.total);
      }
    } catch (error) {
      console.error("Failed to fetch audit logs:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleExport = async () => {
    const params = new URLSearchParams({ action: "export" });

    if (filters.type) params.append("type", filters.type);
    if (filters.action) params.append("action", filters.action);
    if (filters.success) params.append("success", filters.success);
    if (filters.ip) params.append("ip", filters.ip);
    if (filters.startDate) params.append("startDate", filters.startDate);
    if (filters.endDate) params.append("endDate", filters.endDate);

    window.location.href = `/api/staff/dashboard/security/audit-logs?${params}`;
  };

  const clearFilters = () => {
    setFilters({
      type: "",
      action: "",
      success: "",
      ip: "",
      startDate: "",
      endDate: "",
    });
    setPage(1);
  };

  const hasActiveFilters = Object.values(filters).some((v) => v !== "");

  return (
    <div className="space-y-4">
      {/* Toolbar */}
      <div className="flex flex-wrap items-center gap-3">
        {/* Search by action */}
        <div className="relative flex-1 min-w-[200px]">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
          <input
            type="text"
            placeholder="Search by action..."
            value={filters.action}
            onChange={(e) => {
              setFilters({ ...filters, action: e.target.value });
              setPage(1);
            }}
            className="w-full pl-9 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green text-sm"
          />
        </div>

        {/* Filter toggle */}
        <button
          onClick={() => setShowFilters(!showFilters)}
          className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition ${
            showFilters || hasActiveFilters
              ? "bg-brand-green text-white"
              : "bg-gray-100 text-gray-700 hover:bg-gray-200"
          }`}
        >
          <Filter className="w-4 h-4" />
          Filters
          {hasActiveFilters && (
            <span className="bg-white/20 text-white text-xs px-1.5 py-0.5 rounded">
              {Object.values(filters).filter((v) => v !== "").length}
            </span>
          )}
        </button>

        {/* Refresh */}
        <button
          onClick={fetchLogs}
          disabled={loading}
          className="p-2 text-gray-600 hover:bg-gray-100 rounded-lg transition"
          title="Refresh"
        >
          <RefreshCw className={`w-4 h-4 ${loading ? "animate-spin" : ""}`} />
        </button>

        {/* Export */}
        <button
          onClick={handleExport}
          className="flex items-center gap-2 px-4 py-2 bg-gray-100 text-gray-700 rounded-lg text-sm font-medium hover:bg-gray-200 transition"
        >
          <Download className="w-4 h-4" />
          Export CSV
        </button>
      </div>

      {/* Filters Panel */}
      {showFilters && (
        <div className="bg-gray-50 rounded-lg p-4 border border-gray-200">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-4">
            <div>
              <label className="block text-xs font-medium text-gray-700 mb-1">
                Type
              </label>
              <select
                value={filters.type}
                onChange={(e) => {
                  setFilters({ ...filters, type: e.target.value });
                  setPage(1);
                }}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green"
              >
                <option value="">All Types</option>
                {types.map((type) => (
                  <option key={type} value={type}>
                    {type}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-xs font-medium text-gray-700 mb-1">
                Status
              </label>
              <select
                value={filters.success}
                onChange={(e) => {
                  setFilters({ ...filters, success: e.target.value });
                  setPage(1);
                }}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green"
              >
                <option value="">All</option>
                <option value="true">Success</option>
                <option value="false">Failed</option>
              </select>
            </div>

            <div>
              <label className="block text-xs font-medium text-gray-700 mb-1">
                IP Address
              </label>
              <input
                type="text"
                placeholder="Filter by IP"
                value={filters.ip}
                onChange={(e) => {
                  setFilters({ ...filters, ip: e.target.value });
                  setPage(1);
                }}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green"
              />
            </div>

            <div>
              <label className="block text-xs font-medium text-gray-700 mb-1">
                Start Date
              </label>
              <input
                type="date"
                value={filters.startDate}
                onChange={(e) => {
                  setFilters({ ...filters, startDate: e.target.value });
                  setPage(1);
                }}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green"
              />
            </div>

            <div>
              <label className="block text-xs font-medium text-gray-700 mb-1">
                End Date
              </label>
              <input
                type="date"
                value={filters.endDate}
                onChange={(e) => {
                  setFilters({ ...filters, endDate: e.target.value });
                  setPage(1);
                }}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green"
              />
            </div>

            <div className="flex items-end">
              <button
                onClick={clearFilters}
                className="w-full px-3 py-2 text-sm text-gray-600 hover:text-gray-800 border border-gray-300 rounded-lg hover:bg-gray-100 transition"
              >
                Clear All
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Results count */}
      <div className="text-sm text-gray-500">
        {total.toLocaleString()} audit log entries
      </div>

      {/* Table */}
      <div className="overflow-x-auto">
        <table className="w-full">
          <thead>
            <tr className="text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-200">
              <th className="pb-3 pr-4">Timestamp</th>
              <th className="pb-3 pr-4">User</th>
              <th className="pb-3 pr-4">Type</th>
              <th className="pb-3 pr-4">Action</th>
              <th className="pb-3 pr-4">Status</th>
              <th className="pb-3 pr-4">IP Address</th>
              <th className="pb-3"></th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {loading ? (
              <tr>
                <td colSpan={7} className="py-12 text-center text-gray-500">
                  <RefreshCw className="w-6 h-6 animate-spin mx-auto mb-2" />
                  Loading audit logs...
                </td>
              </tr>
            ) : logs.length === 0 ? (
              <tr>
                <td colSpan={7} className="py-12 text-center text-gray-500">
                  No audit logs found
                </td>
              </tr>
            ) : (
              logs.map((log) => (
                <tr key={log.id} className="hover:bg-gray-50">
                  <td className="py-3 pr-4">
                    <div className="text-sm text-brand-ink">
                      {new Date(log.createdAt).toLocaleDateString()}
                    </div>
                    <div className="text-xs text-gray-500">
                      {new Date(log.createdAt).toLocaleTimeString()}
                    </div>
                  </td>
                  <td className="py-3 pr-4">
                    {log.user ? (
                      <div>
                        <div className="text-sm font-medium text-brand-ink">
                          {log.user.name || "Unknown"}
                        </div>
                        <div className="text-xs text-gray-500">
                          {log.user.email}
                        </div>
                      </div>
                    ) : (
                      <span className="text-sm text-gray-400">System</span>
                    )}
                  </td>
                  <td className="py-3 pr-4">
                    <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-700">
                      {log.type}
                    </span>
                  </td>
                  <td className="py-3 pr-4">
                    <span className="text-sm text-brand-ink">{log.action}</span>
                  </td>
                  <td className="py-3 pr-4">
                    {log.success ? (
                      <span className="inline-flex items-center gap-1 text-xs font-medium text-green-700">
                        <CheckCircle className="w-3.5 h-3.5" />
                        Success
                      </span>
                    ) : (
                      <span className="inline-flex items-center gap-1 text-xs font-medium text-red-700">
                        <XCircle className="w-3.5 h-3.5" />
                        Failed
                      </span>
                    )}
                  </td>
                  <td className="py-3 pr-4">
                    <span className="text-sm text-gray-600 font-mono">
                      {log.ip}
                    </span>
                  </td>
                  <td className="py-3">
                    <button
                      onClick={() => setSelectedLog(log)}
                      className="p-1.5 text-gray-400 hover:text-brand-green hover:bg-gray-100 rounded transition"
                      title="View details"
                    >
                      <Eye className="w-4 h-4" />
                    </button>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-between pt-4 border-t border-gray-200">
          <p className="text-sm text-gray-500">
            Page {page} of {totalPages}
          </p>
          <div className="flex gap-2">
            <button
              onClick={() => setPage(page - 1)}
              disabled={page === 1}
              className="flex items-center gap-1 px-3 py-1.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <ChevronLeft className="w-4 h-4" />
              Previous
            </button>
            <button
              onClick={() => setPage(page + 1)}
              disabled={page === totalPages}
              className="flex items-center gap-1 px-3 py-1.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Next
              <ChevronRight className="w-4 h-4" />
            </button>
          </div>
        </div>
      )}

      {/* Detail Modal */}
      {selectedLog && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl max-w-2xl w-full max-h-[80vh] overflow-hidden">
            <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200">
              <h3 className="text-lg font-semibold text-brand-ink">
                Audit Log Details
              </h3>
              <button
                onClick={() => setSelectedLog(null)}
                className="p-1 text-gray-400 hover:text-gray-600 rounded"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-6 overflow-y-auto max-h-[calc(80vh-120px)]">
              <dl className="space-y-4">
                <DetailRow label="ID" value={selectedLog.id} mono />
                <DetailRow
                  label="Timestamp"
                  value={new Date(selectedLog.createdAt).toLocaleString()}
                />
                <DetailRow
                  label="User"
                  value={
                    selectedLog.user
                      ? `${selectedLog.user.name || "Unknown"} (${selectedLog.user.email})`
                      : "System"
                  }
                />
                <DetailRow label="Type" value={selectedLog.type} />
                <DetailRow label="Action" value={selectedLog.action} />
                <DetailRow
                  label="Status"
                  value={selectedLog.success ? "Success" : "Failed"}
                  color={selectedLog.success ? "green" : "red"}
                />
                <DetailRow label="IP Address" value={selectedLog.ip} mono />
                <DetailRow
                  label="User Agent"
                  value={selectedLog.userAgent || "N/A"}
                />
                {selectedLog.metadata &&
                  Object.keys(selectedLog.metadata).length > 0 && (
                    <div>
                      <dt className="text-sm font-medium text-gray-500 mb-1">
                        Metadata
                      </dt>
                      <dd className="bg-gray-50 rounded-lg p-3 overflow-x-auto">
                        <pre className="text-xs text-gray-700 font-mono whitespace-pre-wrap">
                          {JSON.stringify(selectedLog.metadata, null, 2)}
                        </pre>
                      </dd>
                    </div>
                  )}
              </dl>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function DetailRow({
  label,
  value,
  mono,
  color,
}: {
  label: string;
  value: string;
  mono?: boolean;
  color?: "green" | "red";
}) {
  const colorClasses = {
    green: "text-green-700 bg-green-50 px-2 py-0.5 rounded",
    red: "text-red-700 bg-red-50 px-2 py-0.5 rounded",
  };

  return (
    <div className="flex flex-col sm:flex-row sm:gap-4">
      <dt className="text-sm font-medium text-gray-500 sm:w-32 shrink-0">
        {label}
      </dt>
      <dd
        className={`text-sm text-brand-ink ${mono ? "font-mono" : ""} ${
          color ? colorClasses[color] : ""
        }`}
      >
        {value}
      </dd>
    </div>
  );
}
