import type { JSX } from 'react';
import React, { useState } from 'react';
import { GlyphButton, Highlight, Label } from '@theorchard/suite-components';
import { Page, useFeatureFlag } from '@theorchard/suite-frontend';
import { CONTRACT_TYPE_MAP } from 'src/apollo/type-constants/contract';
import { generalSectionStyling } from 'src/components/contract-detail/constants';
import ContractRenewalSection from 'src/components/contract-detail/contract-renewal-section';
import { ContractLifecycleEditGeneralContractInformation } from 'src/components/contract-lifecycle-edit/contract-lifecycle-edit-general-contract-information';
import RestrictedByAbacusProfileWrapper from 'src/components/restricted-by-abacus-profile-wrapper';
import TruncatedText from 'src/components/shared/truncated-text';
import { CONTRACT_TYPES, USER_FEATURES } from 'src/constants';
import { getAccountDetail } from 'src/urls/frontend-royalties';
import type { AbacusContractAccount } from 'src/types/abacus-contract';
import type { ContractEditGeneralInfo } from 'src/types/abacus-contract-lifecycle';

export interface ContractGeneralDetailSectionPropType {
    account: AbacusContractAccount;
    contractName: string;
    contractType: string;
    initialStartDate?: string | null | undefined;
    referenceSigningEntityName: string;
    runControllerName: string;
    runControllerId: string;
    isExcludedFromAccountingRun?: boolean;
    isPaythroughContract: boolean;
    isPrimaryContract: boolean;
    executionDate?: string | null | undefined;
    sapProfitCenterDisplayName?: string | null;
}

export const ContractGeneralDetailSection: React.FC<
    ContractGeneralDetailSectionPropType
> = ({
    account,
    contractName,
    contractType,
    initialStartDate,
    referenceSigningEntityName,
    runControllerName,
    runControllerId,
    isExcludedFromAccountingRun,
    isPaythroughContract,
    isPrimaryContract,
    executionDate,
    sapProfitCenterDisplayName,
}) => {
    const [
        isEditingContractGeneralDetails,
        setIsEditingContractGeneralDetails,
    ] = useState<boolean>(false);

    const paymentEntityName =
        account?.accountPaymentTerm?.paymentEntity?.paymentEntityName;

    const contractGeneralEditInfo: ContractEditGeneralInfo = {
        accountId: account?.accountId,
        contractName,
        contractType,
        initialStartDate,
        executionDate,
        runControllerName,
        runControllerId,
        isExcludedFromAccountingRun,
        isPaythroughContract,
        isPrimaryContract,
        contracts: account?.contracts || [],
    };

    const renderExcludedTag = (): JSX.Element | undefined => {
        if (isExcludedFromAccountingRun) {
            return (
                <Highlight
                    className="ContractDetail-general-details-highlight"
                    variant="error"
                >
                    Excluded
                </Highlight>
            );
        }
        return (
            <Highlight
                className="ContractDetail-general-details-highlight"
                variant="success"
            >
                Included
            </Highlight>
        );
    };

    const isFeaturePrimaryContractEnabled = useFeatureFlag(
        USER_FEATURES.ABACUS_PRIMARY_CONTRACT
    );

    const isFeatureSingleSupplyChainCompanyCodesEnabled = useFeatureFlag(
        USER_FEATURES.ABACUS_SINGLE_SUPPLY_CHAIN_COMPANY_CODES
    );

    return (
        <div
            className="ContractDetail-general-details"
            style={{ ...generalSectionStyling }}
        >
            <>
                <div>
                    <>
                        <h3 className="ContractDetail-general-details-header-block">
                            General
                        </h3>
                        <RestrictedByAbacusProfileWrapper>
                            <GlyphButton
                                className="ContractDetail-general-details-editButton"
                                onClick={() =>
                                    setIsEditingContractGeneralDetails(
                                        !isEditingContractGeneralDetails
                                    )
                                }
                                variant="secondary"
                                name="edit"
                            />
                        </RestrictedByAbacusProfileWrapper>
                        <ContractLifecycleEditGeneralContractInformation
                            accountName={account?.accountName}
                            isSidecarOpen={isEditingContractGeneralDetails}
                            onRequestCloseSidecar={() =>
                                setIsEditingContractGeneralDetails(false)
                            }
                            contractGeneralInfo={contractGeneralEditInfo}
                        />
                    </>
                </div>
                <hr />
                <Page.Grid>
                    <Page.Col md={3} className="AccountInfo">
                        <div className="AccountInfo-div">
                            <div className="AccountInfo-label">
                                <h4>Account</h4>
                            </div>
                            <div
                                className="AccountInfo-name"
                                data-testid="account-info-name"
                            >
                                <Label text="Name" />
                                <TruncatedText
                                    placement="top"
                                    routeUrl={getAccountDetail(
                                        account?.accountId
                                    )}
                                    useLink={true}
                                    value={account?.accountName}
                                />
                            </div>
                            <div
                                className="AccountInfo-id"
                                data-testid="account-info-id"
                            >
                                <Label text="ID" />
                                <TruncatedText
                                    placement="top"
                                    value={account?.accountId}
                                />
                            </div>
                            <div
                                className="AccountInfo-paid-by"
                                data-testid="account-info-paid-by"
                            >
                                <Label text="Paid By" />
                                {paymentEntityName ? paymentEntityName : '-'}
                            </div>
                        </div>
                    </Page.Col>
                    <Page.Col md={9}>
                        <Page.Grid>
                            {/* ROW 1 */}
                            <Page.Col md={3}>
                                <Label text="Contract Type" />
                                {CONTRACT_TYPE_MAP[contractType]}
                            </Page.Col>
                            <Page.Col md={3}>
                                <Label text="Initial Period Start Date" />
                                <TruncatedText
                                    placement="top"
                                    value={
                                        initialStartDate
                                            ? initialStartDate
                                            : '-'
                                    }
                                />
                            </Page.Col>
                            <Page.Col md={3}>
                                <Label text="Execution Date" />
                                {executionDate ? executionDate : '-'}
                            </Page.Col>
                            <Page.Col md={3} />
                            {/* ROW 2 */}
                            <Page.Col
                                md={3}
                                className="ContractDetail-general-details-row"
                            >
                                <Label text="Signing Entity" />
                                <TruncatedText
                                    placement="top"
                                    value={referenceSigningEntityName}
                                />
                            </Page.Col>
                            {isFeatureSingleSupplyChainCompanyCodesEnabled && (
                                <Page.Col
                                    md={3}
                                    className="ContractDetail-general-details-row"
                                >
                                    <Label text="SAP Profit Center" />
                                    <TruncatedText
                                        placement="top"
                                        value={
                                            sapProfitCenterDisplayName ?? '-'
                                        }
                                    />
                                </Page.Col>
                            )}
                            <Page.Col
                                md={3}
                                className="ContractDetail-general-details-row"
                            >
                                <Label text="Run Controller" />
                                <TruncatedText
                                    placement="top"
                                    value={runControllerName}
                                />
                                &nbsp;
                                {renderExcludedTag()}
                            </Page.Col>
                            <Page.Col
                                md={
                                    isFeatureSingleSupplyChainCompanyCodesEnabled
                                        ? 3
                                        : 6
                                }
                            />
                            {/* ROW 3 */}
                            {isFeaturePrimaryContractEnabled &&
                                contractType ===
                                    CONTRACT_TYPES.DISTRIBUTION && (
                                    <Page.Col
                                        md={3}
                                        className="ContractDetail-general-details-row"
                                    >
                                        <Label text="Is Primary Contract" />
                                        {isPrimaryContract ? 'Yes' : 'No'}
                                    </Page.Col>
                                )}
                            <Page.Col
                                md={3}
                                className="ContractDetail-general-details-row"
                            >
                                <Label text="Flowthrough Contract" />
                                {isPaythroughContract ? 'Yes' : 'No'}
                            </Page.Col>
                        </Page.Grid>
                    </Page.Col>
                </Page.Grid>
                <hr />
                <ContractRenewalSection />
            </>
        </div>
    );
};

export default ContractGeneralDetailSection;
