import React, { useEffect, useMemo, useRef } from 'react';
import { Select } from '@theorchard/suite-components';
import type { ListViewItem } from '@theorchard/suite-components';

interface ProfitCenterItem {
    companyCode: string;
    displayName: string;
    referenceSapProfitCenterId: string;
}

export interface ReferenceSapProfitCenterDropdownProps {
    className?: string;
    id: string;
    isClearable?: boolean;
    isDisabled?: boolean;
    name: string;
    onChange: (e: ListViewItem | undefined) => void;
    placeholder?: string;
    value: string | null;
    testId?: string;
    sapProfitCenters: Record<string, ProfitCenterItem[]>;
    signingEntityId: string;
}

export const ReferenceSapProfitCenterDropdown: React.FC<
    ReferenceSapProfitCenterDropdownProps
> = ({
    className = '',
    id,
    isClearable = false,
    isDisabled = false,
    name,
    onChange,
    placeholder = 'Select',
    value,
    testId,
    sapProfitCenters,
    signingEntityId,
}) => {
    const authorizedProfitCenters = sapProfitCenters[signingEntityId];

    const hasAutoSelected = useRef(false);

    const options = useMemo<ListViewItem[]>(() => {
        hasAutoSelected.current = false;
        if (!authorizedProfitCenters) return [];

        return authorizedProfitCenters.map(
            ({ companyCode, displayName, referenceSapProfitCenterId }) => ({
                value: referenceSapProfitCenterId,
                label: displayName,
                subtitle: companyCode,
            })
        );
    }, [authorizedProfitCenters, signingEntityId]);

    useEffect(() => {
        if (options.length === 1 && !value && !hasAutoSelected.current) {
            hasAutoSelected.current = true;
            onChange(options[0]);
        }
    }, [options, value, onChange]);

    return (
        <Select
            className={`SelectSapProfitCenter ${className}`}
            disabled={isDisabled}
            id={id}
            hideClearButton={!isClearable}
            name={name}
            onChange={onChange}
            options={options}
            placeholder={placeholder}
            selectedValue={value || undefined}
            testId={testId}
        />
    );
};

export default ReferenceSapProfitCenterDropdown;
