// SolaceNet (IRU) catalog — Sankofa Marketplace; other products may be listed elsewhere

import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { apiClient } from '@/services/api/client';
import {
  BILLING_MODE_LABELS,
  COMMERCIAL_MODEL_LABELS,
  FULFILLMENT_MODE_LABELS,
  OFFER_TYPE_LABELS,
  SOLACENET_OFFER_METADATA,
  SOLACENET_PRODUCT_NAME,
  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;
  pricingModel: string;
  basePrice?: number;
  currency: string;
  features?: any;
  status: 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 IRUOfferings: React.FC = () => {
  const [offerings, setOfferings] = useState<MarketplaceOffering[]>([]);
  const [filteredOfferings, setFilteredOfferings] = useState<MarketplaceOffering[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [filters, setFilters] = useState({
    capacityTier: '',
    institutionalType: '',
  });

  React.useEffect(() => {
    const fetchOfferings = async () => {
      try {
        setLoading(true);
        const params: any = {};
        if (filters.capacityTier) {
          params.capacityTier = filters.capacityTier;
        }
        if (filters.institutionalType) {
          params.institutionalType = filters.institutionalType;
        }

        const queryString = new URLSearchParams(params).toString();
        const url = `/api/v1/iru/marketplace/offerings${queryString ? `?${queryString}` : ''}`;
        const data = await apiClient.get<{ success: boolean; data: MarketplaceOffering[] }>(url);
        
        if (data.success) {
          setOfferings(data.data);
          setFilteredOfferings(data.data);
        }
      } catch (err: any) {
        setError(err.message || 'Failed to load offerings');
      } finally {
        setLoading(false);
      }
    };

    fetchOfferings();
  }, [filters]);

  const handleFilterChange = (key: string, value: string) => {
    setFilters((prev) => ({
      ...prev,
      [key]: value,
    }));
  };

  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 offerings...</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 py-8">
      <div className="container mx-auto px-4">
        <div className="mb-8">
          <p className="text-sm font-medium text-gray-500 uppercase tracking-wide mb-1">
            {SOLACENET_VENDOR_NAME}
          </p>
          <h1 className="text-3xl font-bold mb-2 text-gray-800">
            {SOLACENET_PRODUCT_NAME}{' '}
            <span className="text-xl font-normal text-gray-600">({SOLACENET_IRU_LABEL})</span>
          </h1>
          <p className="text-gray-600 mb-4">
            One product family on Sankofa Marketplace — additional offerings from other vendors may be
            available separately.
          </p>
          <div className="mb-4 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">
              {SUPPORT_OWNER_LABELS[SOLACENET_OFFER_METADATA.supportOwner]}
            </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="text-sm text-gray-600">
            IRU remains the commercial model for this partner offering line. It does not define a separate marketplace category.
          </p>
          
          {/* Filters */}
          <div className="bg-white rounded-lg shadow p-4 mb-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Capacity Tier
                </label>
                <select
                  value={filters.capacityTier}
                  onChange={(e) => handleFilterChange('capacityTier', e.target.value)}
                  className="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="">All Tiers</option>
                  {Object.entries(TIER_NAMES).map(([tier, name]) => (
                    <option key={tier} value={tier}>
                      Tier {tier}: {name}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Institutional Type
                </label>
                <select
                  value={filters.institutionalType}
                  onChange={(e) => handleFilterChange('institutionalType', e.target.value)}
                  className="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="">All Types</option>
                  <option value="CentralBank">Central Bank</option>
                  <option value="SettlementBank">Settlement Bank</option>
                  <option value="CommercialBank">Commercial Bank</option>
                  <option value="DFI">Development Finance Institution</option>
                  <option value="SpecialEntity">Special Entity</option>
                </select>
              </div>
            </div>
          </div>
        </div>

        {/* Offerings Grid */}
        {filteredOfferings.length > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {filteredOfferings.map((offering) => (
              <div
                key={offering.id}
                className="bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow p-6"
              >
                <div className="flex items-start justify-between mb-3">
                  <h3 className="text-xl font-semibold text-gray-800">{offering.name}</h3>
                  <span className="text-xs bg-blue-100 text-blue-800 px-2 py-1 rounded">
                    Tier {offering.capacityTier}
                  </span>
                </div>
                
                {offering.description && (
                  <p className="text-gray-600 mb-4 line-clamp-3">{offering.description}</p>
                )}

                <div className="mb-4">
                  <div className="text-sm text-gray-500 mb-1">Institutional Type</div>
                  <div className="text-gray-800">{offering.institutionalType}</div>
                </div>

                {offering.basePrice && (
                  <div className="mb-4">
                    <div className="text-sm text-gray-500 mb-1">Base Price</div>
                    <div className="text-xl font-bold text-blue-600">
                      {offering.currency} {offering.basePrice.toLocaleString()}
                    </div>
                  </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 className="text-center py-12 bg-white rounded-lg shadow">
            <p className="text-gray-600 text-lg">No offerings match your filters.</p>
            <button
              onClick={() => setFilters({ capacityTier: '', institutionalType: '' })}
              className="mt-4 text-blue-600 hover:text-blue-700"
            >
              Clear Filters
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default IRUOfferings;
