import { useTranslation } from "react-i18next";
import { format } from "date-fns";
import { cn } from "@/shared/lib/utils";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/shared/common/ui/card";
import { Badge } from "@/shared/common/ui/badge";
import { Avatar, AvatarFallback } from "@/shared/common/ui/avatar";
import { Button } from "@/shared/common/ui/button";
import { X } from "lucide-react";
import { AuditLogItem } from "./AuditLogDisplay";

type AuditLogDetailPanelProps = {
  log: AuditLogItem;
  onClose?: () => void;
  localizedName?: (name: { en: string; am: string }) => 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 => {
  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);
};

/**
 * Detailed view of a single audit log entry
 * Shows full information including changes made
 */
export const AuditLogDetailPanel = ({
  log,
  onClose,
  localizedName,
}: AuditLogDetailPanelProps) => {
  const { t, i18n } = useTranslation();
  const isAmharic = i18n.language === "am";

  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: "long",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });

  return (
    <Card className="w-full">
      <CardHeader>
        <div className="flex items-start justify-between">
          <div className="flex-1">
            <CardTitle>{t("auditLog.detail.title", "Audit Log Details")}</CardTitle>
            <CardDescription>
              {t("auditLog.detail.description", "View details of this audit entry")}
            </CardDescription>
          </div>
          {onClose && (
            <Button variant="ghost" size="sm" onClick={onClose}>
              <X className="h-4 w-4" />
            </Button>
          )}
        </div>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* Header with user and action */}
        <div className="flex items-start gap-4 pb-4 border-b">
          <Avatar className="h-10 w-10 mt-1">
            <AvatarFallback>{getInitials(displayName)}</AvatarFallback>
          </Avatar>
          <div className="flex-1">
            <h3 className="text-lg font-semibold">{displayName}</h3>
            <p className="text-sm text-gray-600">{log.user.email}</p>
          </div>
        </div>

        {/* Action and Entity info */}
        <div className="grid grid-cols-2 gap-4">
          <div>
            <p className="text-sm font-medium text-gray-700">
              {t("auditLog.detail.action", "Action")}
            </p>
            <div className="mt-2">
              <Badge variant={getActionColor(log.queryMethod)}>
                {log.queryMethod.toUpperCase()}
              </Badge>
            </div>
          </div>
          <div>
            <p className="text-sm font-medium text-gray-700">
              {t("auditLog.detail.entity", "Entity")}
            </p>
            <p className="mt-2 text-sm">{getEntityLabel(log.entityName)}</p>
          </div>
        </div>

        {/* Timestamp */}
        <div>
          <p className="text-sm font-medium text-gray-700">
            {t("auditLog.detail.timestamp", "Timestamp")}
          </p>
          <p className="mt-2 text-sm text-gray-600">{timestamp}</p>
        </div>

        {/* Changes if available */}
        {log.changes && log.changes.length > 0 && (
          <div>
            <p className="text-sm font-medium text-gray-700 mb-3">
              {t("auditLog.detail.changes", "Changes Made")}
            </p>
            <div className="space-y-3 bg-gray-50 rounded-lg p-4">
              {log.changes.map((change, idx) => (
                <div key={idx} className="text-sm">
                  <p className="font-medium text-gray-900 mb-1">
                    {change.field ? String(change.field) : `Change ${idx + 1}`}
                  </p>
                  {change.from !== undefined && (
                    <p className="text-gray-600">
                      <span className="text-xs font-semibold">From:</span>{" "}
                      <code className="bg-gray-100 px-2 py-1 rounded text-xs">
                        {JSON.stringify(change.from)}
                      </code>
                    </p>
                  )}
                  {change.to !== undefined && (
                    <p className="text-gray-600 mt-1">
                      <span className="text-xs font-semibold">To:</span>{" "}
                      <code className="bg-primary-50 px-2 py-1 rounded text-xs text-primary-900">
                        {JSON.stringify(change.to)}
                      </code>
                    </p>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Additional info */}
        {log.user.username && (
          <div className="text-xs text-gray-500 pt-4 border-t">
            <p>
              <span className="font-semibold">Username:</span> {log.user.username}
            </p>
          </div>
        )}
      </CardContent>
    </Card>
  );
};
