import { format } from "date-fns";
import { useTranslation } from "react-i18next";
import { cn } from "@/shared/lib/utils";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/common/ui/table";
import { Badge } from "@/shared/common/ui/badge";
import { Avatar, AvatarFallback } from "@/shared/common/ui/avatar";

export type AuditLogItem = {
  id?: string;
  createdAt: string;
  entityName: string;
  queryMethod: "INSERT" | "UPDATE" | "DELETE" | string;
  user: {
    id: string;
    name: {
      am: string;
      en: string;
    };
    email: string;
    username?: string;
  };
  changes?: Array<{
    field?: string;
    from?: unknown;
    to?: unknown;
  }>;
};

type AuditLogDisplayProps = {
  logs: AuditLogItem[];
  loading?: boolean;
  localizedName?: (name: { en: string; am: string }) => string;
  onRowClick?: (log: AuditLogItem) => void;
  compact?: boolean;
  className?: string;
};

const getActionColor = (
  action: string,
): "default" | "secondary" | "destructive" | "outline" => {
  const upper = action.toUpperCase();
  if (upper === "INSERT") return "default";
  if (upper === "UPDATE") return "secondary";
  if (upper === "DELETE") return "destructive";
  return "outline";
};

const getEntityLabel = (entityName: string): string => {
  // Convert snake_case to Title Case
  return entityName
    .split("_")
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(" ");
};

const getInitials = (name: string): string => {
  return name
    .split(" ")
    .map((n) => n.charAt(0))
    .join("")
    .toUpperCase()
    .slice(0, 2);
};

/**
 * Displays audit logs in a table or compact format
 * Shows: WHO (user name) -> WHAT (action on entity) -> WHEN (timestamp)
 */
export const AuditLogDisplay = ({
  logs,
  loading = false,
  localizedName,
  onRowClick,
  compact = false,
  className,
}: AuditLogDisplayProps) => {
  const { t, i18n } = useTranslation();
  const isAmharic = i18n.language === "am";

  if (loading) {
    return (
      <div className={cn("flex items-center justify-center py-8", className)}>
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900" />
      </div>
    );
  }

  if (!logs || logs.length === 0) {
    return (
      <div className={cn("text-center py-8 text-gray-500", className)}>
        <p>{t("auditLog.noRecords", "No audit records found")}</p>
      </div>
    );
  }

  if (compact) {
    return (
      <div className={cn("space-y-2", className)}>
        {logs.map((log, idx) => {
          const userName = isAmharic ? log.user.name.am : log.user.name.en;
          const displayName = localizedName
            ? localizedName(log.user.name)
            : userName;
          const timestamp = new Date(log.createdAt).toLocaleString(
            i18n.language,
            {
              year: "numeric",
              month: "short",
              day: "numeric",
              hour: "2-digit",
              minute: "2-digit",
            },
          );

          return (
            <div
              key={log.id || idx}
              className="flex items-start gap-3 p-3 rounded-lg border border-gray-200 hover:bg-gray-50 transition-colors cursor-pointer"
              onClick={() => onRowClick?.(log)}
            >
              <Avatar className="h-8 w-8 mt-0.5">
                <AvatarFallback className="text-xs">
                  {getInitials(displayName)}
                </AvatarFallback>
              </Avatar>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 flex-wrap">
                  <span className="font-semibold text-sm">{displayName}</span>
                  <Badge variant={getActionColor(log.queryMethod)} className="text-xs">
                    {log.queryMethod.toUpperCase()}
                  </Badge>
                </div>
                <p className="text-xs text-gray-600 mt-1">
                  {getEntityLabel(log.entityName)}
                </p>
                <p className="text-xs text-gray-500 mt-0.5">{timestamp}</p>
              </div>
            </div>
          );
        })}
      </div>
    );
  }

  return (
    <div className={cn("rounded-lg border border-gray-200 overflow-hidden", className)}>
      <Table>
        <TableHeader>
          <TableRow className="bg-gray-50">
            <TableHead className="w-[100px]">
              {t("auditLog.table.user", "User")}
            </TableHead>
            <TableHead className="w-[150px]">
              {t("auditLog.table.action", "Action")}
            </TableHead>
            <TableHead className="w-[200px]">
              {t("auditLog.table.entity", "Entity")}
            </TableHead>
            <TableHead className="w-[180px]">
              {t("auditLog.table.time", "Timestamp")}
            </TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {logs.map((log, idx) => {
            const userName = isAmharic ? log.user.name.am : log.user.name.en;
            const displayName = localizedName
              ? localizedName(log.user.name)
              : userName;
            const timestamp = new Date(log.createdAt).toLocaleString(
              i18n.language,
              {
                year: "numeric",
                month: "short",
                day: "numeric",
                hour: "2-digit",
                minute: "2-digit",
              },
            );

            return (
              <TableRow
                key={log.id || idx}
                className="hover:bg-gray-50 transition-colors cursor-pointer"
                onClick={() => onRowClick?.(log)}
              >
                <TableCell>
                  <div className="flex items-center gap-2">
                    <Avatar className="h-7 w-7">
                      <AvatarFallback className="text-xs">
                        {getInitials(displayName)}
                      </AvatarFallback>
                    </Avatar>
                    <span className="text-sm font-medium truncate">
                      {displayName}
                    </span>
                  </div>
                </TableCell>
                <TableCell>
                  <Badge variant={getActionColor(log.queryMethod)}>
                    {log.queryMethod.toUpperCase()}
                  </Badge>
                </TableCell>
                <TableCell className="text-sm">
                  {getEntityLabel(log.entityName)}
                </TableCell>
                <TableCell className="text-sm text-gray-600">
                  {timestamp}
                </TableCell>
              </TableRow>
            );
          })}
        </TableBody>
      </Table>
    </div>
  );
};
