﻿import type { FC } from 'react';
import React, { useState } from 'react';
import { Form, Modal, Sidecar } from '@theorchard/suite-components';
import { useApproveProductMutationV2 } from 'src/data/mutations/approve';
import { type Validation } from 'src/data/queries';
import { isMissingTrackAttributes } from 'src/utils/attributes';
import { useDisplayAudioAttributeModalFF } from 'src/utils/features';
import {
    getApprovalParams,
    getInfringedTracks,
    hasSpotifyWatchlist,
    validateApprovalForm,
} from './helpers';
import { useApprovalForm } from './hooks/useApprovalForm';
import { useAudioAttributes } from './hooks/useAudioAttributes';
import ProductLevelApprovalForm from './ProductLevelApprovalForm';
import TrackLevelApprovalForm from './TrackLevelApprovalForm';
import type { Product } from 'src/data/queries/product/types';
import type { MergedProduct } from 'src/product/product';

const INTL_PREFIX = 'contentReview.productModalApprovalSidecarV2';
export const CLASS_NAME = 'ProductModalApprovalSidecarV2';

const APPROVAL_REASON_DEFINITIONS_LINK =
    'https://docs.google.com/spreadsheets/d/1PTCjyMuj0MI5Pad8DTjmXHIzpIm1-CBTkgxBYqsDZyk/edit?pli=1&gid=1820067481#gid=1820067481';

export interface Props {
    product: Product;
    mergedProduct: MergedProduct;
    validations?: Validation[];
    isOpen: boolean;
    closeModal: () => void;
    productReviewQueueId: number;
    onReviewCompleted: (status: string, eventType?: string) => void;
}

const ProductModalApprovalSidecarV2: FC<Props> = ({
    product,
    mergedProduct,
    isOpen,
    closeModal,
    onReviewCompleted,
    productReviewQueueId,
    validations,
}) => {
    const isAudioAttributeModalEnabled = useDisplayAudioAttributeModalFF();

    const [isSubmitting, setIsSubmitting] = useState(false);
    const [showAttributesModal, setShowAttributesModal] = useState(false);

    const {
        approvalFormState,
        blocklistReasons,
        paiReasons,
        updateProductForm,
        updateTrackForm,
        updateSingleNoteForm,
    } = useApprovalForm();

    const infringedTracks = getInfringedTracks(mergedProduct);
    const showProductLevelForm = hasSpotifyWatchlist(validations);
    const showTrackLevelForm = infringedTracks.length > 0;
    const showSingleNoteForm = !showProductLevelForm && !showTrackLevelForm;

    const isApprovalFormValid = validateApprovalForm(
        approvalFormState,
        infringedTracks,
        showProductLevelForm,
        showTrackLevelForm
    );

    const { updateTrackAttributes } = useAudioAttributes({
        product,
        mergedProduct,
    });

    const approveProduct = useApproveProductMutationV2(onReviewCompleted);

    const submitApproval = async () => {
        setIsSubmitting(true);

        const approvalParams = getApprovalParams(
            productReviewQueueId,
            approvalFormState,
            showProductLevelForm,
            showTrackLevelForm
        );

        try {
            await approveProduct(approvalParams);
            await updateTrackAttributes();
        } finally {
            setIsSubmitting(false);
            setShowAttributesModal(false);
        }

        closeModal();
    };

    const handleFormSubmission = async () => {
        if (isAudioAttributeModalEnabled) {
            const {
                foundMissingAudioAttributes,
                foundMissingRightsAttributes,
            } = isMissingTrackAttributes(
                mergedProduct?.getTrackList(),
                product.tracks
            );

            if (foundMissingAudioAttributes || foundMissingRightsAttributes) {
                setShowAttributesModal(true);
                return;
            }
        }

        await submitApproval();
    };

    const subtitle = $tx(`${INTL_PREFIX}.subtitle`, {
        bold: ({ children }) => <b>{children}</b>,
        link: ({ children }) => (
            <a
                className={`${CLASS_NAME}-definitions-link`}
                href={APPROVAL_REASON_DEFINITIONS_LINK}
                target="_blank"
                rel="noreferrer"
            >
                {children}
            </a>
        ),
    });

    return (
        <Sidecar
            className={CLASS_NAME}
            isOpen={isOpen}
            onRequestClose={closeModal}
            title={$t(`${INTL_PREFIX}.title`)}
            subtitle={subtitle}
            testId={CLASS_NAME}
            confirmButtonProps={{
                title: $t(`${INTL_PREFIX}.confirm`),
                disabled: isSubmitting || !isApprovalFormValid,
                testId: `${CLASS_NAME}-confirm-button`,
                onClick: () => {
                    void handleFormSubmission();
                },
            }}
        >
            <Form
                className={`${CLASS_NAME}-Form`}
                data-testid={`${CLASS_NAME}-Form`}
                style={{ width: '95%' }}
            >
                {showProductLevelForm && (
                    <ProductLevelApprovalForm
                        formState={approvalFormState.productLevel}
                        approvalReasons={blocklistReasons}
                        updateForm={updateProductForm}
                        withTitle={showTrackLevelForm}
                    />
                )}
                {showTrackLevelForm && (
                    <TrackLevelApprovalForm
                        formState={approvalFormState.trackLevel}
                        approvalReasons={paiReasons}
                        infringedTracks={infringedTracks}
                        updateForm={updateTrackForm}
                        withTitle={showProductLevelForm}
                    />
                )}

                {showSingleNoteForm && (
                    <Form.Group
                        controlId="additional-notes-approve"
                        data-testid="form-group-additional-notes-approval"
                    >
                        <Form.Label>{$t('common.additionalNotes')}</Form.Label>
                        <Form.Control
                            as="textarea"
                            data-testid="form-control-additional-notes-approval"
                            rows={24}
                            value={approvalFormState.singleNote}
                            placeholder={$t(`${INTL_PREFIX}.notesPlaceholder`)}
                            onChange={event =>
                                updateSingleNoteForm(event.currentTarget.value)
                            }
                        />
                    </Form.Group>
                )}
            </Form>

            {showAttributesModal && (
                <Modal
                    testId="missing-audio-attributes-modal"
                    className={`${CLASS_NAME}-audio-attribute-modal`}
                    title={$t(`${INTL_PREFIX}.audioAttributeModalTitle`)}
                    isOpen={showAttributesModal}
                    onRequestClose={() => setShowAttributesModal(false)}
                    onConfirm={submitApproval}
                    confirmButtonProps={{
                        title: $t(
                            `${INTL_PREFIX}.audioAttributeModalApproveButton`
                        ),
                    }}
                >
                    <div className={`${CLASS_NAME}-audio-attribute-modal-body`}>
                        <p>
                            {$tx(`${INTL_PREFIX}.audioAttributeModalBody`, {
                                bold: ({ children }) => <b>{children}</b>,
                            })}
                        </p>
                    </div>
                </Modal>
            )}
        </Sidecar>
    );
};

export default ProductModalApprovalSidecarV2;
