// Offering detail — SolaceNet (IRU) offering from Solace Bank Group PLC on Sankofa Marketplace

import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { apiClient } from '@/services/api/client';
import { InquiryForm } from './InquiryForm';
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;
  technicalSpecs?: any;
  legalFramework?: any;
  regulatoryPosition?: any;
  documents?: any;
}

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

export const OfferingDetail: React.FC = () => {
  const { offeringId } = useParams<{ offeringId: string }>();
  const navigate = useNavigate();
  const [offering, setOffering] = useState<MarketplaceOffering | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showInquiryForm, setShowInquiryForm] = useState(false);
  const [pricing, setPricing] = useState<any>(null);

  useEffect(() => {
    const fetchOffering = async () => {
      if (!offeringId) return;

      try {
        setLoading(true);
        const data = await apiClient.get<{ success: boolean; data: MarketplaceOffering }>(
          `/api/v1/iru/marketplace/offerings/${offeringId}`
        );
        
        if (data.success) {
          setOffering(data.data);
          
          // Fetch pricing
          try {
            const pricingData = await apiClient.get<{ success: boolean; data: any }>(
              `/api/v1/iru/marketplace/offerings/${offeringId}/pricing`
            );
            if (pricingData.success) {
              setPricing(pricingData.data);
            }
          } catch (err) {
            // Pricing fetch failed, continue without it
          }
        }
      } catch (err: any) {
        setError(err.message || 'Failed to load offering');
      } finally {
        setLoading(false);
      }
    };

    fetchOffering();
  }, [offeringId]);

  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 offering details...</p>
        </div>
      </div>
    );
  }

  if (error || !offering) {
    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 mb-4">{error || 'Offering not found'}</p>
          <button
            onClick={() => navigate('/marketplace')}
            className="text-blue-600 hover:text-blue-700"
          >
            Back to Marketplace
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="container mx-auto px-4 max-w-6xl">
        {/* Header */}
        <div className="mb-6">
          <button
            onClick={() => navigate('/marketplace')}
            className="text-blue-600 hover:text-blue-700 mb-4"
          >
            ← Back to Marketplace
          </button>
          <p className="text-sm text-gray-500 mb-1">
            {SOLACENET_VENDOR_NAME} · {SOLACENET_PRODUCT_NAME} ({SOLACENET_IRU_LABEL})
          </p>
          <h1 className="text-4xl font-bold mb-2 text-gray-800">{offering.name}</h1>
          <div className="mb-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">
              {SUPPORT_OWNER_LABELS[SOLACENET_OFFER_METADATA.supportOwner]}
            </span>
          </div>
          <div className="flex flex-wrap items-center gap-4">
            <span className="bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-sm font-semibold">
              Tier {offering.capacityTier}: {TIER_NAMES[offering.capacityTier]}
            </span>
            <span className="text-gray-600">{offering.institutionalType}</span>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Main Content */}
          <div className="lg:col-span-2 space-y-6">
            {/* Description */}
            {offering.description && (
              <div className="bg-white rounded-lg shadow p-6">
                <h2 className="text-2xl font-semibold mb-4 text-gray-800">Description</h2>
                <p className="text-gray-700 whitespace-pre-line">{offering.description}</p>
              </div>
            )}

            {/* Features */}
            {offering.features && (
              <div className="bg-white rounded-lg shadow p-6">
                <h2 className="text-2xl font-semibold mb-4 text-gray-800">Features</h2>
                {Array.isArray(offering.features) ? (
                  <ul className="list-disc list-inside space-y-2 text-gray-700">
                    {offering.features.map((feature: string, index: number) => (
                      <li key={index}>{feature}</li>
                    ))}
                  </ul>
                ) : (
                  <pre className="text-gray-700 whitespace-pre-wrap">
                    {JSON.stringify(offering.features, null, 2)}
                  </pre>
                )}
              </div>
            )}

            {/* Technical Specs */}
            {offering.technicalSpecs && (
              <div className="bg-white rounded-lg shadow p-6">
                <h2 className="text-2xl font-semibold mb-4 text-gray-800">Technical Specifications</h2>
                <pre className="text-gray-700 whitespace-pre-wrap bg-gray-50 p-4 rounded">
                  {JSON.stringify(offering.technicalSpecs, null, 2)}
                </pre>
              </div>
            )}

            {/* Legal Framework */}
            {offering.legalFramework && (
              <div className="bg-white rounded-lg shadow p-6">
                <h2 className="text-2xl font-semibold mb-4 text-gray-800">Legal Framework</h2>
                <pre className="text-gray-700 whitespace-pre-wrap bg-gray-50 p-4 rounded">
                  {JSON.stringify(offering.legalFramework, null, 2)}
                </pre>
              </div>
            )}

            {/* Regulatory Position */}
            {offering.regulatoryPosition && (
              <div className="bg-white rounded-lg shadow p-6">
                <h2 className="text-2xl font-semibold mb-4 text-gray-800">Regulatory Positioning</h2>
                <pre className="text-gray-700 whitespace-pre-wrap bg-gray-50 p-4 rounded">
                  {JSON.stringify(offering.regulatoryPosition, null, 2)}
                </pre>
              </div>
            )}

            {/* Documents */}
            {offering.documents && (
              <div className="bg-white rounded-lg shadow p-6">
                <h2 className="text-2xl font-semibold mb-4 text-gray-800">Documents</h2>
                <div className="space-y-2">
                  {Array.isArray(offering.documents) ? (
                    offering.documents.map((doc: any, index: number) => (
                      <a
                        key={index}
                        href={doc.url || '#'}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="block text-blue-600 hover:text-blue-700 underline"
                      >
                        {doc.name || doc.title || `Document ${index + 1}`}
                      </a>
                    ))
                  ) : (
                    <pre className="text-gray-700 whitespace-pre-wrap">
                      {JSON.stringify(offering.documents, null, 2)}
                    </pre>
                  )}
                </div>
              </div>
            )}
          </div>

          {/* Sidebar */}
          <div className="space-y-6">
            {/* Pricing Card */}
            <div className="bg-white rounded-lg shadow p-6 sticky top-4">
              <h2 className="text-2xl font-semibold mb-4 text-gray-800">Pricing</h2>
              <p className="mb-4 text-sm text-gray-600">
                This is a request-based partner program. Commercial terms are handled through qualification and agreement,
                not as a separate marketplace type.
              </p>
              <div className="mb-4 flex flex-wrap gap-2">
                <span className="rounded-full bg-gray-100 px-3 py-1 text-sm text-gray-700">
                  {BILLING_MODE_LABELS[SOLACENET_OFFER_METADATA.billingMode]}
                </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>
              </div>
              {pricing ? (
                <div className="space-y-4">
                  {pricing.basePrice && (
                    <div>
                      <div className="text-sm text-gray-500 mb-1">
                        {SOLACENET_PRODUCT_NAME} grant fee ({SOLACENET_IRU_LABEL})
                      </div>
                      <div className="text-2xl font-bold text-blue-600">
                        {pricing.currency} {pricing.basePrice.toLocaleString()}
                      </div>
                    </div>
                  )}
                  {pricing.breakdown && (
                    <div className="border-t pt-4">
                      <div className="text-sm font-semibold text-gray-700 mb-2">
                        Ongoing Fees (Monthly)
                      </div>
                      {pricing.breakdown.ongoingFees && (
                        <div className="space-y-1 text-sm">
                          {Object.entries(pricing.breakdown.ongoingFees).map(([key, value]: [string, any]) => (
                            <div key={key} className="flex justify-between">
                              <span className="text-gray-600 capitalize">{key}:</span>
                              <span className="text-gray-800">
                                {pricing.currency} {Number(value).toLocaleString()}
                              </span>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  )}
                </div>
              ) : (
                <div className="text-gray-600">
                  {offering.basePrice ? (
                    <>
                      <div className="text-sm text-gray-500 mb-1">Base Price</div>
                      <div className="text-2xl font-bold text-blue-600">
                        {offering.currency} {offering.basePrice.toLocaleString()}
                      </div>
                    </>
                  ) : (
                    <p>Contact us for pricing</p>
                  )}
                </div>
              )}

              <button
                onClick={() => setShowInquiryForm(true)}
                className="w-full mt-6 bg-blue-600 text-white py-3 px-4 rounded-lg hover:bg-blue-700 transition-colors font-semibold"
              >
                Request Information
              </button>
            </div>

            {/* Quick Info */}
            <div className="bg-white rounded-lg shadow p-6">
              <h3 className="text-lg font-semibold mb-4 text-gray-800">Quick Information</h3>
              <div className="space-y-3 text-sm">
                <div>
                  <div className="text-gray-500">Capacity Tier</div>
                  <div className="text-gray-800 font-medium">
                    Tier {offering.capacityTier}: {TIER_NAMES[offering.capacityTier]}
                  </div>
                </div>
                <div>
                  <div className="text-gray-500">Institutional Type</div>
                  <div className="text-gray-800 font-medium">{offering.institutionalType}</div>
                </div>
                <div>
                  <div className="text-gray-500">Pricing Model</div>
                  <div className="text-gray-800 font-medium">{offering.pricingModel}</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Inquiry Form Modal */}
        {showInquiryForm && offering && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto">
              <div className="p-6">
                <div className="flex justify-between items-center mb-4">
                  <h2 className="text-2xl font-semibold text-gray-800">
                    Request information — {SOLACENET_PRODUCT_NAME}
                  </h2>
                  <button
                    onClick={() => setShowInquiryForm(false)}
                    className="text-gray-500 hover:text-gray-700"
                  >
                    ✕
                  </button>
                </div>
                <InquiryForm
                  offeringId={offering.offeringId}
                  onSuccess={() => {
                    setShowInquiryForm(false);
                    // Show success message
                  }}
                  onCancel={() => setShowInquiryForm(false)}
                />
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default OfferingDetail;
