/**
 * Copyright (c) 2025-present, Goldman Sachs
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { type JSX, useCallback, useState } from 'react';
import {
  Box,
  Button,
  Card,
  CardActionArea,
  CardActions,
  CardContent,
  CardMedia,
  Chip,
  CircularProgress,
  Typography,
} from '@mui/material';
import type { TerminalResult } from '@finos/legend-server-marketplace';
import { CheckCircleIcon, ShoppingCartIcon } from '@finos/legend-art';
import { useLegendMarketplaceBaseStore } from '../../application/providers/LegendMarketplaceFrameworkProvider.js';
import { observer } from 'mobx-react-lite';
import { flowResult } from 'mobx';
import { toastManager } from '../Toast/CartToast.js';
import { RecommendedAddOnsModal } from '../AddToCart/RecommendedAddOnsModal.js';
import { assertErrorThrown } from '@finos/legend-shared';
import { MAX_PRODUCT_IMAGE_COUNT } from '../../stores/lakehouse/dataProducts/ProductCardState.js';

export const LegendMarketplaceTerminalCard = observer(
  (props: { terminalResult: TerminalResult }): JSX.Element => {
    const { terminalResult } = props;
    const [isAddingToCart, setIsAddingToCart] = useState(false);
    const [showRecommendationsModal, setShowRecommendationsModal] =
      useState(false);
    const [recommendedItems, setRecommendedItems] = useState<TerminalResult[]>(
      [],
    );

    const [modalMessage, setModalMessage] = useState<string>('');
    const [modalTotalCount, setModalTotalCount] = useState<
      number | null | undefined
    >(undefined);

    const legendMarketplaceBaseStore = useLegendMarketplaceBaseStore();
    const applicationStore = legendMarketplaceBaseStore.applicationStore;
    const assetUrl = applicationStore.config.assetsBaseUrl;

    const [imageUrl] = useState(() => {
      const randomIndex =
        Math.floor(Math.random() * MAX_PRODUCT_IMAGE_COUNT) + 1;
      return `${assetUrl}/images${randomIndex}.jpg`;
    });

    const handleAddToCart = async () => {
      setIsAddingToCart(true);
      try {
        const result = await flowResult(
          legendMarketplaceBaseStore.cartStore.addToCartWithAPI(
            legendMarketplaceBaseStore.cartStore.providerToCartRequest(
              terminalResult,
            ),
          ),
        );
        if (result.recommendations && result.recommendations.length > 0) {
          setRecommendedItems(result.recommendations);
          setModalMessage(result.message);
          setModalTotalCount(result.totalCount);
          setShowRecommendationsModal(true);
        }
      } catch (error) {
        assertErrorThrown(error);
        toastManager.error(
          `Failed to add ${terminalResult.productName} to cart: ${error.message}`,
        );
      } finally {
        setIsAddingToCart(false);
      }
    };

    const isInCart = legendMarketplaceBaseStore.cartStore.isItemInCart(
      terminalResult.id,
    );

    const handleViewCart = () => {
      legendMarketplaceBaseStore.cartStore.setOpen(true);
    };

    const handleTerminalSelected = useCallback(
      (
        _selectedTerminal: TerminalResult,
        recommendations: TerminalResult[],
        responseMessage: string,
        totalCount?: number | null,
      ) => {
        setRecommendedItems(recommendations);
        setModalMessage(responseMessage);
        setModalTotalCount(totalCount);
        setShowRecommendationsModal(true);
      },
      [],
    );

    return (
      <Card className="legend-marketplace-terminal-card">
        <CardActionArea className="legend-marketplace-terminal-card__action">
          <CardMedia
            component="img"
            className="legend-marketplace-terminal-card__image"
            height="140"
            image={imageUrl}
            alt="data asset"
          />
          {terminalResult.category && (
            <Chip
              label={terminalResult.category}
              className="legend-marketplace-terminal-card__category-chip"
            />
          )}
          <CardContent className="legend-marketplace-terminal-card__content">
            <Typography
              variant="subtitle2"
              className="legend-marketplace-terminal-card__provider"
            >
              {terminalResult.providerName}
            </Typography>
            <Typography
              variant="h6"
              className="legend-marketplace-terminal-card__title"
            >
              {terminalResult.productName}
            </Typography>
          </CardContent>
        </CardActionArea>
        <CardActions className="legend-marketplace-terminal-card__action-buttons">
          {terminalResult.isOwned ? (
            <Box className="legend-marketplace-terminal-card__owned-access">
              Already have access &nbsp;
              <CheckCircleIcon />
            </Box>
          ) : (
            <>
              <Button
                variant="outlined"
                className="legend-marketplace-terminal-card__add-to-cart-button"
                onClick={() => {
                  handleAddToCart().catch(() => {});
                }}
                disabled={isAddingToCart || isInCart}
              >
                {isAddingToCart && (
                  <>
                    Adding... &nbsp;
                    <CircularProgress size={16} />
                  </>
                )}
                {!isAddingToCart && isInCart && (
                  <>
                    In Cart &nbsp;
                    <Box className="legend-marketplace-terminal-card__in-cart-check">
                      <CheckCircleIcon />
                    </Box>
                  </>
                )}
                {!isAddingToCart && !isInCart && (
                  <>
                    Add to cart &nbsp;
                    <ShoppingCartIcon />
                  </>
                )}
              </Button>
              {typeof terminalResult.price === 'number' && (
                <Chip
                  label={`${new Intl.NumberFormat('en-US', {
                    style: 'currency',
                    currency: 'USD',
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2,
                  }).format(terminalResult.price)}/month`}
                  className="legend-marketplace-terminal-card__price"
                />
              )}
            </>
          )}
        </CardActions>

        <RecommendedAddOnsModal
          terminal={terminalResult}
          recommendedItems={recommendedItems}
          message={modalMessage}
          showModal={showRecommendationsModal}
          setShowModal={setShowRecommendationsModal}
          onViewCart={handleViewCart}
          onTerminalSelected={handleTerminalSelected}
          totalCount={modalTotalCount}
        />
      </Card>
    );
  },
);
