"use client";

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { ChevronLeft, ChevronRight, RefreshCw } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
import { Table, TableHead, TableBody, TableRow, Th, Td, EmptyState } from "@/components/ui/Table";
import { Badge } from "@/components/ui/Badge";
import { Button } from "@/components/ui/Button";
import { formatDateTime } from "@/lib/utils";
import api from "@/lib/api";
import type { AuditLog, PaginatedResponse } from "@/types";

const ENTITY_TYPES = ["", "CLIENT", "INVOICE", "PAYMENT", "TICKET", "PLAN", "AREA", "USER", "SUBSCRIPTION", "LEAD", "REMITTANCE", "JOURNAL_ENTRY"];
const ACTION_TYPES = ["", "CREATE", "UPDATE", "DELETE", "LOGIN", "LOGOUT", "ACTIVATE", "DEACTIVATE", "VOID", "RESOLVE", "CLOSE"];

export default function AuditLogPage() {
  const [page, setPage] = useState(1);
  const [dateFrom, setDateFrom] = useState("");
  const [dateTo, setDateTo] = useState("");
  const [entityType, setEntityType] = useState("");
  const [actionType, setActionType] = useState("");

  const { data, isLoading, refetch } = useQuery<PaginatedResponse<AuditLog>>({
    queryKey: ["audit-logs", page, dateFrom, dateTo, entityType, actionType],
    queryFn: async () => {
      const params = new URLSearchParams({ page: String(page), limit: "50" });
      if (dateFrom) params.set("dateFrom", new Date(dateFrom).toISOString());
      if (dateTo) {
        const end = new Date(dateTo);
        end.setHours(23, 59, 59, 999);
        params.set("dateTo", end.toISOString());
      }
      if (entityType) params.set("entityType", entityType);
      if (actionType) params.set("action", actionType);
      const res = await api.get<PaginatedResponse<AuditLog>>(`/api/v1/audit-logs?${params}`);
      return res.data;
    },
  });

  const logs = data?.data ?? [];
  const meta = data?.meta;

  const clearFilters = () => {
    setDateFrom("");
    setDateTo("");
    setEntityType("");
    setActionType("");
    setPage(1);
  };

  const hasFilters = dateFrom || dateTo || entityType || actionType;

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Audit Log</h1>
          <p className="text-sm text-gray-500">Track all system activity</p>
        </div>
        <Button size="sm" variant="outline" onClick={() => refetch()}>
          <RefreshCw className="h-4 w-4 mr-1" />
          Refresh
        </Button>
      </div>

      {/* Filters */}
      <Card>
        <CardContent className="py-4">
          <div className="flex flex-wrap gap-3 items-end">
            <div className="flex flex-col gap-1">
              <label className="text-xs font-medium text-gray-500">From</label>
              <input type="date" value={dateFrom}
                onChange={e => { setDateFrom(e.target.value); setPage(1); }}
                className="border rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 w-40" />
            </div>
            <div className="flex flex-col gap-1">
              <label className="text-xs font-medium text-gray-500">To</label>
              <input type="date" value={dateTo}
                onChange={e => { setDateTo(e.target.value); setPage(1); }}
                className="border rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 w-40" />
            </div>
            <div className="flex flex-col gap-1">
              <label className="text-xs font-medium text-gray-500">Entity Type</label>
              <select value={entityType}
                onChange={e => { setEntityType(e.target.value); setPage(1); }}
                className="border rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                {ENTITY_TYPES.map(e => <option key={e} value={e}>{e || "All Entities"}</option>)}
              </select>
            </div>
            <div className="flex flex-col gap-1">
              <label className="text-xs font-medium text-gray-500">Action</label>
              <select value={actionType}
                onChange={e => { setActionType(e.target.value); setPage(1); }}
                className="border rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                {ACTION_TYPES.map(a => <option key={a} value={a}>{a || "All Actions"}</option>)}
              </select>
            </div>
            {hasFilters && (
              <Button size="sm" variant="outline" onClick={clearFilters}>Clear Filters</Button>
            )}
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader><CardTitle>Activity Log {meta ? `(${meta.total} entries)` : ""}</CardTitle></CardHeader>
        <CardContent className="p-0">
          <Table>
            <TableHead>
              <TableRow>
                <Th>Timestamp</Th>
                <Th>User</Th>
                <Th>Action</Th>
                <Th>Entity</Th>
                <Th>Entity ID</Th>
              </TableRow>
            </TableHead>
            <TableBody>
              {isLoading ? (
                Array.from({ length: 5 }).map((_, i) => (
                  <TableRow key={i}>
                    {Array.from({ length: 5 }).map((_, j) => (
                      <Td key={j}><div className="h-4 w-24 animate-pulse bg-gray-100 rounded" /></Td>
                    ))}
                  </TableRow>
                ))
              ) : logs.length === 0 ? (
                <EmptyState message="No audit logs found" />
              ) : (
                logs.map((log) => (
                  <TableRow key={log.id}>
                    <Td className="text-xs text-gray-400 whitespace-nowrap">
                      {formatDateTime(log.createdAt)}
                    </Td>
                    <Td className="text-gray-700">
                      {log.user
                        ? `${log.user.firstName} ${log.user.lastName}`
                        : log.userId?.slice(0, 8) ?? "System"}
                    </Td>
                    <Td>
                      <Badge variant={
                        log.action?.includes("CREATE") || log.action?.includes("create") ? "success" :
                        log.action?.includes("DELETE") || log.action?.includes("delete") ? "danger" :
                        log.action?.includes("UPDATE") || log.action?.includes("update") ? "default" : "muted"
                      }>
                        {log.action}
                      </Badge>
                    </Td>
                    <Td className="text-gray-600">
                      {log.entityType ?? log.entity ?? "—"}
                    </Td>
                    <Td className="font-mono text-xs text-gray-400">
                      {log.entityId?.slice(0, 12) ?? "—"}
                    </Td>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>

          {meta && meta.totalPages > 1 && (
            <div className="flex items-center justify-between px-4 py-3 border-t border-gray-100">
              <p className="text-sm text-gray-500">Page {meta.page} of {meta.totalPages}</p>
              <div className="flex gap-2">
                <Button size="sm" variant="outline" disabled={page <= 1} onClick={() => setPage(page - 1)}>
                  <ChevronLeft className="h-4 w-4" />
                </Button>
                <Button size="sm" variant="outline" disabled={page >= meta.totalPages} onClick={() => setPage(page + 1)}>
                  <ChevronRight className="h-4 w-4" />
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
