// Marketplace Home Page
// Main landing page for Sankofa Phoenix Marketplace

import React from 'react';
import { Link } from 'react-router-dom';
import { apiClient } from '@/services/api/client';
import {
  BILLING_MODE_LABELS,
  COMMERCIAL_MODEL_LABELS,
  FULFILLMENT_MODE_LABELS,
  MARKETPLACE_NAME,
  OFFER_TYPE_LABELS,
  SOLACENET_PRODUCT_NAME,
  SOLACENET_OFFER_METADATA,
  SOLACENET_VENDOR_NAME,
  SOLACENET_IRU_LABEL,
  SUPPORT_OWNER_LABELS,
} from '@/constants/marketplace';

interface MarketplaceOffering {
  id: string;
  offeringId: string;
  name: string;
  description?: string;
  capacityTier: number;
  institutionalType: string;
  basePrice?: number;
  currency: string;
}

const TIER_NAMES: Record<number, string> = {
  1: 'Central Banks',
  2: 'Settlement Banks',
  3: 'Commercial Banks',
  4: 'Development Finance Institutions',
  5: 'Special Entities',
};

export const MarketplaceHome: React.FC = () => {
  const [offerings, setOfferings] = React.useState<MarketplaceOffering[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);

  React.useEffect(() => {
    const fetchOfferings = async () => {
      try {
        setLoading(true);
        const data = await apiClient.get<{ success: boolean; data: MarketplaceOffering[] }>(
          '/api/v1/iru/marketplace/offerings'
        );
        if (data.success) {
          setOfferings(data.data);
        }
      } catch (err: any) {
        setError(err.message || 'Failed to load offerings');
      } finally {
        setLoading(false);
      }
    };

    fetchOfferings();
  }, []);

  const offeringsByTier = offerings.reduce((acc, offering) => {
    if (!acc[offering.capacityTier]) {
      acc[offering.capacityTier] = [];
    }
    acc[offering.capacityTier].push(offering);
    return acc;
  }, {} as Record<number, MarketplaceOffering[]>);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">Loading marketplace...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="text-red-600 text-xl mb-4">Error</div>
          <p className="text-gray-600">{error}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Hero Section */}
      <div className="bg-gradient-to-r from-blue-600 to-indigo-700 text-white py-20">
        <div className="container mx-auto px-4">
          <h1 className="text-4xl md:text-5xl font-bold mb-4">{MARKETPLACE_NAME}</h1>
          <p className="text-xl md:text-2xl mb-4 text-blue-100">
            Multiple sovereign-grade offerings — one trusted venue
          </p>
          <p className="text-lg text-blue-50 max-w-3xl mb-6">
            Explore products from leading vendors. Below you can browse{' '}
            <span className="font-semibold text-white">{SOLACENET_PRODUCT_NAME}</span> (
            {SOLACENET_IRU_LABEL}) from <span className="font-semibold text-white">{SOLACENET_VENDOR_NAME}</span>
            — a partner program offered through Sankofa Marketplace for Central Banks, Settlement Banks, Commercial Banks, DFIs, and
            Special Entities.
          </p>
          <div className="flex flex-wrap gap-2">
            <span className="rounded-full bg-white/15 px-3 py-1 text-sm">
              {OFFER_TYPE_LABELS[SOLACENET_OFFER_METADATA.offerType]}
            </span>
            <span className="rounded-full bg-white/15 px-3 py-1 text-sm">
              {COMMERCIAL_MODEL_LABELS[SOLACENET_OFFER_METADATA.commercialModel]}
            </span>
            <span className="rounded-full bg-white/15 px-3 py-1 text-sm">
              {FULFILLMENT_MODE_LABELS[SOLACENET_OFFER_METADATA.fulfillmentMode]}
            </span>
            <span className="rounded-full bg-white/15 px-3 py-1 text-sm">
              {SUPPORT_OWNER_LABELS[SOLACENET_OFFER_METADATA.supportOwner]}
            </span>
            <span className="rounded-full bg-white/15 px-3 py-1 text-sm">
              {BILLING_MODE_LABELS[SOLACENET_OFFER_METADATA.billingMode]}
            </span>
          </div>
        </div>
      </div>

      {/* SolaceNet (IRU) offerings — additional marketplace products may appear here over time */}
      <div className="container mx-auto px-4 py-12">
        <div className="mb-10 pb-6 border-b border-gray-200">
          <p className="text-sm font-medium text-gray-500 uppercase tracking-wide mb-1">
            {SOLACENET_VENDOR_NAME}
          </p>
          <h2 className="text-2xl md:text-3xl font-bold text-gray-900">
            {SOLACENET_PRODUCT_NAME}{' '}
            <span className="text-lg md:text-xl font-normal text-gray-600">({SOLACENET_IRU_LABEL})</span>
          </h2>
          <div className="mt-3 flex flex-wrap gap-2">
            <span className="rounded-full bg-blue-50 px-3 py-1 text-sm text-blue-700">
              {OFFER_TYPE_LABELS[SOLACENET_OFFER_METADATA.offerType]}
            </span>
            <span className="rounded-full bg-gray-100 px-3 py-1 text-sm text-gray-700">
              {COMMERCIAL_MODEL_LABELS[SOLACENET_OFFER_METADATA.commercialModel]}
            </span>
            <span className="rounded-full bg-gray-100 px-3 py-1 text-sm text-gray-700">
              {FULFILLMENT_MODE_LABELS[SOLACENET_OFFER_METADATA.fulfillmentMode]}
            </span>
            <span className="rounded-full bg-gray-100 px-3 py-1 text-sm text-gray-700">
              {BILLING_MODE_LABELS[SOLACENET_OFFER_METADATA.billingMode]}
            </span>
          </div>
          <p className="mt-3 text-sm text-gray-600">
            IRU is the commercial model for this partner offering line. It is not a separate marketplace type.
          </p>
        </div>
        {Object.entries(offeringsByTier).map(([tier, tierOfferings]) => (
          <div key={tier} className="mb-12">
            <h2 className="text-3xl font-bold mb-6 text-gray-800">
              Tier {tier}: {TIER_NAMES[parseInt(tier)]}
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {tierOfferings.map((offering) => (
                <div
                  key={offering.id}
                  className="bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow p-6"
                >
                  <h3 className="text-xl font-semibold mb-2 text-gray-800">{offering.name}</h3>
                  {offering.description && (
                    <p className="text-gray-600 mb-4 line-clamp-3">{offering.description}</p>
                  )}
                  <div className="flex items-center justify-between mb-4">
                    <span className="text-sm text-gray-500">
                      {offering.institutionalType}
                    </span>
                    {offering.basePrice && (
                      <span className="text-lg font-bold text-blue-600">
                        {offering.currency} {offering.basePrice.toLocaleString()}
                      </span>
                    )}
                  </div>
                  <Link
                    to={`/marketplace/offerings/${offering.offeringId}`}
                    className="block w-full text-center bg-blue-600 text-white py-2 px-4 rounded hover:bg-blue-700 transition-colors"
                  >
                    View Details
                  </Link>
                </div>
              ))}
            </div>
          </div>
        ))}

        {offerings.length === 0 && (
          <div className="text-center py-12">
            <p className="text-gray-600 text-lg">No offerings available at this time.</p>
            <p className="text-gray-500 mt-2">Please check back later.</p>
          </div>
        )}
      </div>

      {/* Features Section */}
      <div className="bg-white py-12">
        <div className="container mx-auto px-4">
          <h2 className="text-3xl font-bold mb-8 text-center text-gray-800">
            Why choose {SOLACENET_PRODUCT_NAME}?
          </h2>
          <p className="text-center text-gray-600 max-w-2xl mx-auto -mt-4 mb-8">
            Offered by {SOLACENET_VENDOR_NAME} on {MARKETPLACE_NAME}.
          </p>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
            <div className="text-center">
              <div className="text-4xl mb-4">🏛️</div>
              <h3 className="text-xl font-semibold mb-2">Supranational Infrastructure</h3>
              <p className="text-gray-600">
                Built for sovereign institutions with governance without shares, respecting
                jurisdictional sovereignty.
              </p>
            </div>
            <div className="text-center">
              <div className="text-4xl mb-4">⚡</div>
              <h3 className="text-xl font-semibold mb-2">Enterprise-Grade Performance</h3>
              <p className="text-gray-600">
                High-availability infrastructure with 99.9% uptime SLA and sub-100ms settlement
                latency.
              </p>
            </div>
            <div className="text-center">
              <div className="text-4xl mb-4">🔒</div>
              <h3 className="text-xl font-semibold mb-2">Security & Compliance</h3>
              <p className="text-gray-600">
                Bank-grade security, regulatory compliance, and comprehensive audit trails.
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default MarketplaceHome;
