import { Separator } from '@/components/ui/separator';
import { ReceiptIcon } from '@phosphor-icons/react';
import { useTranslation } from 'react-i18next';
import type { Transaction } from './types';

const IMAGE_EXTENSIONS = /\.(jpe?g|png|gif|webp|svg|bmp|avif)(\?.*)?$/i;

function isImageUrl(value: string): boolean {
  try {
    const url = new URL(value);
    return IMAGE_EXTENSIONS.test(url.pathname);
  } catch {
    return IMAGE_EXTENSIONS.test(value);
  }
}

function ProofValue({ value }: { value: string }) {
  const { t } = useTranslation();

  if (isImageUrl(value)) {
    return (
      <a
        href={value}
        target="_blank"
        rel="noopener noreferrer"
        className="block"
      >
        <img
          src={value}
          alt={t('Payment proof')}
          className="max-h-48 rounded-lg border border-black/10 object-contain"
        />
      </a>
    );
  }

  return (
    <span className="max-w-[60%] text-right text-sm font-medium wrap-break-word">
      {value}
    </span>
  );
}

export default function PaymentProof({
  transaction,
}: {
  transaction: Transaction;
}) {
  const { t } = useTranslation();
  const details = transaction.meta?.details as
    | Record<string, string>
    | null
    | undefined;

  if (!details || Object.keys(details).length === 0) {
    return (
      <div className="rounded-2xl border border-black/5 bg-white p-5">
        <h3 className="mb-1 text-xs font-semibold tracking-widest text-black/30 uppercase">
          {t('Payment Proof')}
        </h3>
        <Separator className="mb-4" />
        <p className="text-sm text-black/40">
          {t('No payment proof submitted.')}
        </p>
      </div>
    );
  }

  return (
    <div className="rounded-2xl border border-black/5 bg-white p-5">
      <h3 className="mb-1 text-xs font-semibold tracking-widest text-black/30 uppercase">
        {t('Payment Proof')}
      </h3>
      <Separator className="mb-1" />

      {Object.entries(details).map(([key, value], index) => (
        <div key={key}>
          <div className="flex items-start justify-between gap-4 py-3">
            <div className="flex items-center gap-3 text-black/50">
              <span className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-black/5">
                <ReceiptIcon weight="bold" className="size-4" />
              </span>
              <span className="text-sm capitalize">
                {key.replace(/_/g, ' ')}
              </span>
            </div>
            <ProofValue value={value} />
          </div>
          {index < Object.keys(details).length - 1 && (
            <Separator className="opacity-40" />
          )}
        </div>
      ))}
    </div>
  );
}
