'use client';

import { DialogCloseButton } from '@/components/ui/common/DialogCloseButton';
import { ToastStack, type ToastMessages } from '@/components/ui/common/Toast';
import type { OrganizationInvitationHistoryItemDto } from '@/lib/api/organization';
import { Badge, organizationConnectionStatusVariant } from '@/components/ui/common/Badge';
import { Table } from '@/components/ui/common/Table';
import { CopyInvitationLinkButton } from '@/components/ui/organizations/CopyInvitationLinkButton';

function formatInvitationStatusLabel(status: OrganizationInvitationHistoryItemDto['status']): string {
  if (status === 'PENDING') return 'Invitation pending';
  if (status === 'ACTIVE') return 'Invitation accepted';
  if (status === 'REJECTED') return 'Invitation rejected';
  if (status === 'EXPIRED') return 'Invitation expired';
  return status;
}

function formatTableDate(value: string): string {
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return '—';
  return d.toLocaleDateString();
}

type InvitationHistoryDialogProps = {
  open: boolean;
  onClose: () => void;
  loading: boolean;
  items: OrganizationInvitationHistoryItemDto[];
  copiedId: string | null;
  copyingInvitationId: string | null;
  onCopy: (invitation: OrganizationInvitationHistoryItemDto) => void;
  /** Same page-level toasts, rendered at top of dialog while it is open. */
  toastMessages?: ToastMessages;
};

export function InvitationHistoryDialog({
  open,
  onClose,
  loading,
  items,
  copiedId,
  copyingInvitationId,
  onCopy,
  toastMessages,
}: InvitationHistoryDialogProps) {
  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
      <div
        className="w-full max-w-[min(56rem,calc(100vw-17rem))] max-h-[90vh] overflow-y-auto rounded-[var(--radius-md)] border border-border bg-background-secondary p-6 shadow-xl space-y-4"
        role="dialog"
        aria-modal="true"
        aria-labelledby="invitation-history-title"
      >
        <div className="flex items-start justify-between gap-3">
          <h2 id="invitation-history-title" className="text-lg font-semibold text-text-primary pr-2">
            Invitation History
          </h2>
          <DialogCloseButton onClick={onClose} />
        </div>

        {toastMessages && <ToastStack {...toastMessages} />}

        {loading ? (
          <p className="text-sm text-text-secondary">Loading invitation history...</p>
        ) : items.length === 0 ? (
          <p className="text-sm text-text-secondary">No invitations yet.</p>
        ) : (
          <Table
            headers={
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">
                  Organization
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">
                  Owner email
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-text-muted uppercase tracking-wider">
                  Date
                </th>
                <th className="px-6 py-3 text-center text-xs font-medium text-text-muted uppercase tracking-wider">
                  Status
                </th>
                <th className="px-6 py-3 text-right text-xs font-medium text-text-muted uppercase tracking-wider">
                  Invitation link
                </th>
              </tr>
            }
            body={
              <>
                {items.map((inv) => (
                  <tr key={inv.id} className="hover:bg-background-secondary/45">
                    <td className="px-6 py-1.5 text-sm text-text-primary">{inv.organizationName}</td>
                    <td className="px-6 py-1.5 text-sm text-text-secondary">{inv.ownerEmail}</td>
                    <td className="px-6 py-1.5 text-sm text-text-secondary">
                      {formatTableDate(inv.createdAt)}
                    </td>
                    <td className="px-6 py-1.5 text-center align-middle">
                      <Badge variant={organizationConnectionStatusVariant(inv.status)} fixedWidth={false}>
                        {formatInvitationStatusLabel(inv.status)}
                      </Badge>
                    </td>
                    <td className="px-6 py-1.5 text-right align-middle">
                      <CopyInvitationLinkButton
                        invitation={inv}
                        copied={copiedId === inv.id}
                        copying={copyingInvitationId === inv.id}
                        onCopy={() => onCopy(inv)}
                      />
                    </td>
                  </tr>
                ))}
              </>
            }
          />
        )}
      </div>
    </div>
  );
}
