'use client';

import { useLocale, useTranslations } from 'next-intl';
import { DialogCloseButton } from '@/components/ui/shared/DialogCloseButton';
import { Card } from '@/components/ui/shared/Card';
import {
  ResponsiveDialogOverlay,
  ResponsiveDialogPanel,
} from '@/components/ui/shared/ResponsiveDialog';
import { Table } from '@/components/ui/shared/Table';
import { CopyInvitationLinkButton } from '@/components/ui/organizations/CopyInvitationLinkButton';
import type { OrganizationInvitationHistoryItemDto } from '@/lib/api/organization';
import { Badge } from '@/components/ui/shared/Badge';
import { organizationConnectionStatusVariant } from '@/components/organizations/connectionStatusVariant';
import { formatAppTableDate } from '@/lib/i18n/format';

type InvitationHistoryDialogProps = {
  open: boolean;
  onClose: () => void;
  loading: boolean;
  items: OrganizationInvitationHistoryItemDto[];
  copiedId: string | null;
  copyingInvitationId: string | null;
  onCopy: (invitation: OrganizationInvitationHistoryItemDto) => void;
};

export function InvitationHistoryDialog({
  open,
  onClose,
  loading,
  items,
  copiedId,
  copyingInvitationId,
  onCopy,
}: InvitationHistoryDialogProps) {
  const locale = useLocale();
  const t = useTranslations('organizations');

  function formatInvitationStatusLabel(
    status: OrganizationInvitationHistoryItemDto['status'],
  ): string {
    if (status === 'PENDING') return t('statusPending');
    if (status === 'ACTIVE') return t('statusAccepted');
    if (status === 'REJECTED') return t('statusRejected');
    if (status === 'EXPIRED') return t('statusExpired');
    return status;
  }

  if (!open) return null;

  return (
    <ResponsiveDialogOverlay onBackdropClick={onClose}>
      <ResponsiveDialogPanel
        maxWidthClass="sm:max-w-4xl"
        role="dialog"
        aria-modal="true"
        aria-labelledby="invitation-history-title"
        className="space-y-4"
      >
        <div className="flex items-start justify-between gap-3">
          <h2 id="invitation-history-title" className="text-lg font-semibold text-text-primary pr-2">
            {t('historyTitle')}
          </h2>
          <DialogCloseButton onClick={onClose} />
        </div>

        {loading ? (
          <p className="text-sm text-text-secondary">{t('loadingHistory')}</p>
        ) : items.length === 0 ? (
          <p className="text-sm text-text-secondary">{t('historyEmpty')}</p>
        ) : (
          <>
            <ul className="space-y-3 lg:hidden">
              {items.map((inv) => (
                <li key={inv.id}>
                  <Card padding="sm" className="space-y-2">
                    <div className="flex items-start justify-between gap-3">
                      <div className="min-w-0">
                        <p className="font-medium text-text-primary truncate">{inv.organizationName}</p>
                        <p className="text-sm text-text-secondary truncate mt-0.5">{inv.ownerEmail}</p>
                        <p className="text-xs text-text-muted mt-1">{formatAppTableDate(inv.createdAt, locale)}</p>
                      </div>
                      <Badge variant={organizationConnectionStatusVariant(inv.status)} fixedWidth={false}>
                        {formatInvitationStatusLabel(inv.status)}
                      </Badge>
                    </div>
                    <div className="flex justify-end pt-1 border-t border-border/60">
                      <CopyInvitationLinkButton
                        invitation={inv}
                        copied={copiedId === inv.id}
                        copying={copyingInvitationId === inv.id}
                        onCopy={() => onCopy(inv)}
                      />
                    </div>
                  </Card>
                </li>
              ))}
            </ul>

            <div className="hidden lg:block">
              <Table
                headers={
                  <tr>
                    <th className="text-xs font-medium text-text-muted uppercase tracking-wider">
                      {t('tableOrganization')}
                    </th>
                    <th className="text-xs font-medium text-text-muted uppercase tracking-wider">
                      {t('tableOwnerEmail')}
                    </th>
                    <th className="text-xs font-medium text-text-muted uppercase tracking-wider">
                      {t('tableDate')}
                    </th>
                    <th className="text-center text-xs font-medium text-text-muted uppercase tracking-wider">
                      {t('tableStatus')}
                    </th>
                    <th className="text-end text-xs font-medium text-text-muted uppercase tracking-wider">
                      {t('tableInvitationLink')}
                    </th>
                  </tr>
                }
                body={
                  <>
                    {items.map((inv) => (
                      <tr key={inv.id} className="hover:bg-background-secondary/45">
                        <td className="text-sm text-text-primary">{inv.organizationName}</td>
                        <td className="text-sm text-text-secondary">{inv.ownerEmail}</td>
                        <td className="text-sm text-text-secondary">
                          {formatAppTableDate(inv.createdAt, locale)}
                        </td>
                        <td className="text-center align-middle">
                          <Badge variant={organizationConnectionStatusVariant(inv.status)} fixedWidth={false}>
                            {formatInvitationStatusLabel(inv.status)}
                          </Badge>
                        </td>
                        <td className="text-end align-middle">
                          <CopyInvitationLinkButton
                            invitation={inv}
                            copied={copiedId === inv.id}
                            copying={copyingInvitationId === inv.id}
                            onCopy={() => onCopy(inv)}
                          />
                        </td>
                      </tr>
                    ))}
                  </>
                }
              />
            </div>
          </>
        )}
      </ResponsiveDialogPanel>
    </ResponsiveDialogOverlay>
  );
}
