"use client";

import { Typography } from "@/components/atoms/typogrpahy";
import { PortableText, PortableTextReactComponents } from "@portabletext/react";
import { hasPortableTextContent } from "@/lib/tenantContent";

interface WithdrawalTnCProps {
  currency: string;
  adminFee: number;
  organizationName?: string;
  sanityTnC?: {
    title?: string;
    body?: any; // Sanity portable text
    effectiveFrom?: string;
  } | null;
}

// PortableText components for TNC styling
const tncComponents: Partial<PortableTextReactComponents> = {
  block: {
    normal: ({ children }) => (
      <p className="mb-3 leading-relaxed text-gray-800 dark:text-gray-200">{children}</p>
    ),
    h1: ({ children }) => (
      <h1 className="mb-3 text-lg font-semibold text-gray-900 dark:text-white">{children}</h1>
    ),
    h2: ({ children }) => (
      <h2 className="mb-2 text-base font-semibold text-gray-900 dark:text-white">{children}</h2>
    ),
  },
  marks: {
    strong: ({ children }) => (
      <strong className="font-bold text-brand-600 dark:text-brand-400">{children}</strong>
    ),
    em: ({ children }) => <em className="italic">{children}</em>,
    link: ({ value, children }) => (
      <a
        href={value?.href}
        className="text-brand-600 underline hover:text-brand-700 dark:text-brand-400"
        target="_blank"
        rel="noopener noreferrer"
      >
        {children}
      </a>
    ),
  },
  list: {
    bullet: ({ children }) => (
      <ul className="mt-2 mb-3 ml-4 list-disc space-y-1 text-gray-800 dark:text-gray-200">{children}</ul>
    ),
    number: ({ children }) => (
      <ol className="mt-2 mb-3 ml-4 list-decimal space-y-1 text-gray-800 dark:text-gray-200">{children}</ol>
    ),
  },
};

export const WithdrawalTnC: React.FC<WithdrawalTnCProps> = ({
  sanityTnC,
}) => {
  const hasSanityContent = sanityTnC && hasPortableTextContent(sanityTnC.body);

  return (
    <div className="mt-8 p-4 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg">
      {hasSanityContent ? (
        <div className="text-sm">
          {sanityTnC.title && (
            <Typography variant="b2" className="font-semibold mb-3 text-gray-900 dark:text-white">
              {sanityTnC.title}
            </Typography>
          )}
          <div>
            <PortableText value={sanityTnC.body} components={tncComponents} />
          </div>
          {sanityTnC.effectiveFrom && (
            <div className="mt-4 text-xs text-gray-600 dark:text-gray-400">
              Effective from: {new Date(sanityTnC.effectiveFrom).toLocaleDateString()}
            </div>
          )}
        </div>
      ) : (
        <Typography
          variant="b2"
          className="text-sm text-gray-800 dark:text-gray-200 whitespace-pre-line leading-relaxed"
        >
          Withdrawal Terms and Conditions belum tersedia.
        </Typography>
      )}
    </div>
  );
};
