"use client";

import { AuthorizedAction } from "@/components/auth/authorized-action";
import { DataTableWrapper, type DataTableColumn } from "@/components/shared/data-table-wrapper";
import { StatusBadge } from "@/components/shared/status-badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Link } from "@/i18n/routing";
import type { PaginationConfig } from "@/hooks/use-swr";
import type { ProjectDeletionLog } from "@/types";
import { Trash2 } from "lucide-react";
import { useMemo } from "react";

interface ProjectDeletionLogsViewProps {
  locale: "ar" | "en" | string;
  isLoading: boolean;
  logs: ProjectDeletionLog[];
  pagination: PaginationConfig;
  formatDate: (date: string | Date) => string;
  formatTime: (date: string | Date) => string;
  emptyTitle: string;
  emptyDescription: string;
  deletedByLabel: string;
  projectLabel: string;
  deletedAtLabel: string;
  statusLabel: string;
  actionsLabel: string;
  viewDetailsLabel: string;
  statusLabels: {
    planned: string;
    inProgress: string;
    completed: string;
    delayed: string;
    notStarted: string;
  };
}

function getInitials(name: string) {
  return name
    .split(" ")
    .filter(Boolean)
    .slice(0, 2)
    .map((part) => part[0]?.toUpperCase())
    .join("");
}

function resolveStatusLabel(
  status: string,
  labels: ProjectDeletionLogsViewProps["statusLabels"],
) {
  const normalized = status.toLowerCase().replace(/_/g, "");

  switch (normalized) {
    case "completed":
      return labels.completed;
    case "inprogress":
      return labels.inProgress;
    case "delayed":
      return labels.delayed;
    case "notstarted":
      return labels.notStarted;
    case "planned":
    default:
      return labels.planned;
  }
}

function formatRelativeTime(dateValue: string, locale: string) {
  const date = new Date(dateValue);
  if (Number.isNaN(date.getTime())) {
    return "-";
  }

  const diff = date.getTime() - Date.now();
  const absDiff = Math.abs(diff);

  const units: Array<[Intl.RelativeTimeFormatUnit, number]> = [
    ["year", 1000 * 60 * 60 * 24 * 365],
    ["month", 1000 * 60 * 60 * 24 * 30],
    ["week", 1000 * 60 * 60 * 24 * 7],
    ["day", 1000 * 60 * 60 * 24],
    ["hour", 1000 * 60 * 60],
    ["minute", 1000 * 60],
    ["second", 1000],
  ];

  const [unit, divisor] = units.find(([, value]) => absDiff >= value) || units[units.length - 1];
  const value = Math.round(diff / divisor);
  return new Intl.RelativeTimeFormat(locale, { numeric: "auto" }).format(value, unit);
}

export function ProjectDeletionLogsView({
  locale,
  isLoading,
  logs,
  pagination,
  formatDate,
  formatTime,
  emptyTitle,
  emptyDescription,
  deletedByLabel,
  projectLabel,
  deletedAtLabel,
  statusLabel,
  actionsLabel,
  viewDetailsLabel,
  statusLabels,
}: ProjectDeletionLogsViewProps) {
  const columns = useMemo<DataTableColumn<ProjectDeletionLog>[]>(() => [
    {
      header: projectLabel,
      accessor: "project_snapshot",
      className: "w-[22%]",
      cell: (row) => {
        const language = locale?.toLowerCase().startsWith("ar") ? "ar" : "en";
        const snapshot = row.project_snapshot;
        const title =
          snapshot?.name_translations?.[language] ||
          snapshot?.name ||
          row.project_name ||
          "-";

        return (
        <div className="space-y-1">
          <p className="text-sm font-semibold text-foreground">{title}</p>
          <p className="text-xs text-muted-foreground">ID: {row.project_id}</p>
        </div>
      )},
    },
    {
      header: deletedByLabel,
      className: "w-[28%]",
      cell: (row) => {
        const deletedBy = row.deleted_by;
        const avatarSrc =
          deletedBy?.avatar_path && deletedBy.avatar_path.startsWith("http")
            ? deletedBy.avatar_path
            : undefined;

        return (
          <div className="flex items-center gap-3">
            <Avatar className="h-8 w-8">
              <AvatarImage src={avatarSrc} alt={deletedBy?.name || row.deleted_by_name} />
              <AvatarFallback className="bg-primary/10 text-xs font-semibold text-primary">
                {getInitials(deletedBy?.name || row.deleted_by_name)}
              </AvatarFallback>
            </Avatar>
            <div className="min-w-0">
              <p className="truncate text-sm font-medium text-foreground">
                {deletedBy?.name || row.deleted_by_name}
              </p>
              <p className="truncate text-xs text-muted-foreground">
                {deletedBy?.email || "-"}
              </p>
            </div>
          </div>
        );
      },
    },
    {
      header: deletedAtLabel,
      className: "w-[18%]",
      cell: (row) => (
        <div className="space-y-1">
          <p className="text-sm font-medium text-foreground">
            {formatDate(row.deleted_at)}
          </p>
          <p className="text-xs text-muted-foreground">
            {formatTime(row.deleted_at)}
          </p>
          <p className="text-xs text-muted-foreground">
            {formatRelativeTime(row.deleted_at, locale)}
          </p>
        </div>
      ),
    },
    {
      header: statusLabel,
      className: "w-[12%]",
      cell: (row) => (
        <StatusBadge
          status={row.project_snapshot.status}
          label={resolveStatusLabel(row.project_snapshot.status, statusLabels)}
        />
      ),
    },
    {
      header: actionsLabel,
      className: "w-[20%]",
      cell: (row) => (
        <AuthorizedAction
          action={{ actionKey: "projects.view_details", mode: "hide" }}
          surface="table"
        >
          <Link
            href={`/projects/${row.project_id}`}
            className="inline-flex items-center text-sm font-medium text-primary transition-colors hover:text-primary/80 hover:underline"
          >
            {viewDetailsLabel}
          </Link>
        </AuthorizedAction>
      ),
    },
  ], [
    actionsLabel,
    deletedAtLabel,
    deletedByLabel,
    formatDate,
    formatTime,
    locale,
    projectLabel,
    statusLabel,
    statusLabels,
    viewDetailsLabel,
  ]);

  return (
    <div className="space-y-6">
      <DataTableWrapper
        data={logs}
        columns={columns}
        isLoading={isLoading}
        getRowKey={(row) => row.id}
        pagination={pagination}
        emptyState={{
          icon: Trash2,
          title: emptyTitle,
          description: emptyDescription,
        }}
        className="overflow-hidden"
      />
    </div>
  );
}
