import React, { useRef, useState } from 'react';
import { YYYY_MM_DD } from '@theorchard/accounting-apps-shared';
import {
    Alert,
    Col,
    DatePicker,
    Form,
    HelpTooltip,
    Row,
    Switch,
} from '@theorchard/suite-components';
import { useFeatureFlag } from '@theorchard/suite-frontend';
import { TOOLTIP_EXECUTION_DATE } from 'src/apollo/type-constants/contract';
import {
    CONTRACT_TYPES,
    UPDATE_RUN_CONTROLLER_ALERT_TITLE,
    UPDATE_RUN_CONTROLLER_ALERT_MESSAGE,
    USER_FEATURES,
} from '../../constants';
import { RunControllerSelect } from '../contract-lifecycle-shared/run-controller-select';
import type { ContractEditGeneralInfo } from 'src/types/abacus-contract-lifecycle';

export interface ContractLifecycleEditContractFromPropsTypes {
    contract: ContractEditGeneralInfo;
    disableSaveButton: (param: boolean) => void;
    errorMsg: string | null;
    handleFormChange: (
        formField: string,
        inputValue: string | boolean | null | undefined
    ) => void;
    shouldRemovePrimaryContract: boolean;
}

export const ContractLifecycleEditContractFrom: React.FC<
    ContractLifecycleEditContractFromPropsTypes
> = ({
    contract,
    disableSaveButton,
    errorMsg,
    handleFormChange,
    shouldRemovePrimaryContract,
}) => {
    const [runControllerUpdated, setRunControllerUpdated] = useState(false);
    const originalRunControllerId = useRef(Number(contract.runControllerId));
    const isEditRunControllerFFEnabled = useFeatureFlag(
        USER_FEATURES.ABACUS_CONTRACT_EDIT_RUN_CONTROLLER
    );

    // ACC-9395: TODO remove FF abacus_primary_contract
    const isFeaturePrimaryContractEnabled = useFeatureFlag(
        USER_FEATURES.ABACUS_PRIMARY_CONTRACT
    );

    const messageToMarkContractNonPrimary = (
        <div>
            This contract is set as the account&apos;s primary contract. If you
            remove this status, the account will not have a primary contract
            assigned.
        </div>
    );

    return (
        <>
            <Form>
                <Row>
                    <Col>
                        <Form.Group>
                            <Form.Label>Contract Name</Form.Label>
                            <Form.Control
                                data-testid="contractNameInput"
                                maxLength={180}
                                name="contractName"
                                onChange={(
                                    e: React.ChangeEvent<HTMLInputElement>
                                ) => {
                                    if (!e.target.value)
                                        disableSaveButton(true);
                                    else disableSaveButton(false);
                                    handleFormChange(
                                        e.target.name,
                                        e.target.value
                                    );
                                }}
                                placeholder="Enter Contract Name"
                                type="text"
                                value={contract?.contractName || ''}
                            />
                        </Form.Group>
                    </Col>
                </Row>
                <Row>
                    <Col>
                        <Form.Group>
                            <div className="DatePicker">
                                <Form.Label>Execution Date</Form.Label>
                                <span className="DatePicker-optional-text">
                                    (optional)
                                </span>
                                <span className="DatePicker-help-tooltip">
                                    <HelpTooltip
                                        id="executionDate"
                                        message={TOOLTIP_EXECUTION_DATE}
                                    />
                                </span>
                            </div>
                            <DatePicker
                                className="DatePicker-date"
                                onChange={date =>
                                    handleFormChange('executionDate', date)
                                }
                                placeholder={YYYY_MM_DD}
                                selectedValue={
                                    contract?.executionDate || undefined
                                }
                                testId="executionDate"
                            />
                        </Form.Group>
                    </Col>
                    <Col>
                        <Form.Group>
                            <div className="DatePicker">
                                <Form.Label>
                                    Initial Period Start Date
                                </Form.Label>
                            </div>
                            <DatePicker
                                className="DatePicker-date"
                                onChange={date =>
                                    handleFormChange('initialStartDate', date)
                                }
                                placeholder={YYYY_MM_DD}
                                selectedValue={
                                    contract?.initialStartDate || undefined
                                }
                                testId="initialStartDate"
                            />
                        </Form.Group>
                    </Col>
                </Row>
                <Row>
                    <Col>
                        <Form.Group>
                            <div className="RunController">
                                <Form.Label>Run Controller</Form.Label>
                                {!isEditRunControllerFFEnabled && (
                                    <div className="RunController-name">
                                        {contract?.runControllerName}
                                    </div>
                                )}
                                {isEditRunControllerFFEnabled && (
                                    <RunControllerSelect
                                        contractType={
                                            contract.contractType || ''
                                        }
                                        disabled={!contract.contractType}
                                        onChange={e => {
                                            handleFormChange(
                                                'runControllerId',
                                                e.value
                                            );
                                            setRunControllerUpdated(
                                                Number(e.value) !==
                                                    originalRunControllerId.current
                                            );
                                        }}
                                        testId="runControllerSelect"
                                        value={contract?.runControllerId ?? ''}
                                    />
                                )}
                            </div>
                        </Form.Group>
                    </Col>
                </Row>
                {runControllerUpdated && (
                    <Row>
                        <Col>
                            <Alert
                                variant="warn"
                                title={UPDATE_RUN_CONTROLLER_ALERT_TITLE}
                                text={UPDATE_RUN_CONTROLLER_ALERT_MESSAGE}
                            />
                        </Col>
                    </Row>
                )}
                <Row>
                    <Col>
                        <Switch
                            defaultChecked={
                                !contract?.isExcludedFromAccountingRun ||
                                undefined
                            }
                            id="checked"
                            label="Include in the Run"
                            name="isExcludedFromAccountingRun"
                            onChange={(
                                e: React.ChangeEvent<HTMLInputElement>
                            ) => {
                                handleFormChange(
                                    e.target.name,
                                    !contract.isExcludedFromAccountingRun
                                );
                            }}
                        />
                    </Col>
                </Row>
                <Row>
                    <Col>
                        <Switch
                            defaultChecked={
                                contract?.isPaythroughContract || undefined
                            }
                            id="isPaythroughContract"
                            label="Flowthrough Contract"
                            name="isPaythroughContract"
                            onChange={(
                                e: React.ChangeEvent<HTMLInputElement>
                            ) => {
                                handleFormChange(
                                    e.target.name,
                                    !contract.isPaythroughContract
                                );
                            }}
                        />
                    </Col>
                </Row>
                {isFeaturePrimaryContractEnabled &&
                    contract.contractType === CONTRACT_TYPES.DISTRIBUTION && (
                        <>
                            <Row>
                                <Col>
                                    <Switch
                                        defaultChecked={
                                            contract?.isPrimaryContract ||
                                            undefined
                                        }
                                        id="isPrimaryContract"
                                        label="Is Primary Contract"
                                        name="isPrimaryContract"
                                        onChange={(
                                            e: React.ChangeEvent<HTMLInputElement>
                                        ) => {
                                            handleFormChange(
                                                e.target.name,
                                                !contract.isPrimaryContract
                                            );
                                        }}
                                    />
                                </Col>
                            </Row>
                            {shouldRemovePrimaryContract && (
                                <Row>
                                    <Col>
                                        <Alert
                                            variant="warn"
                                            text={
                                                messageToMarkContractNonPrimary
                                            }
                                            title="Remove Contract as Primary"
                                        />
                                    </Col>
                                </Row>
                            )}
                        </>
                    )}
                <Row>
                    {errorMsg && (
                        <Alert
                            className="ErrorMsg"
                            text={errorMsg}
                            variant="error"
                        />
                    )}
                </Row>
            </Form>
        </>
    );
};
