import React, {FormEvent, useEffect, useState} from 'react';
import MakeCustomSelect from "../../UI/Forms/CustomSelect/MakeCustomSelect";
import CustomLabel from "../../UI/Forms/CustomLabel/CustomLabel";
import CustomFileUpload from "../../UI/Forms/CustomFileUpload/CustomFileUpload";
import CustomFormSection from "../../UI/Forms/CustomFormSection/CustomFormSection";
import ActionModal from "../../UI/Modal/ActionsModal/ActionModal";
import FormButtonsContainer from "../../UI/Forms/FormButton/FormButtonsContainer";
import FormButtonSubmit from "../../UI/Forms/FormButton/FormButtonSubmit";
import Typography from "../../UI/Typography/Typography";
import InputFake from "../../UI/Typography/InputFake";
import {useSearchParams} from "react-router-dom";
import {CustomSelectOptions} from "../../../models/ReactComponents";

const SELECT_ALL_VALUE = -1;

type AddFileModalProps = {
    close: () => void
    collaborator?: any
    handleFileUpload: (data: Record<string, any>) => Promise<boolean>
    roleProp?: string
    month?: number
    year?: string
    selectableYears: CustomSelectOptions
    projects?: string[]
    availableMonths?: number[]
    preselectedMonths?: number[]
    monthOptions: { value: number; name: string }[]  // ← replaces greekMonths import
}

type FormDataType = {
    role: string
    selectedMonths: number[]
    file_category_id: number
    subfolder_id: number
    user_hash_id: any
    file: File | null
    year: string | undefined
}

const UploadAlfaEnaModal = ({
                                close, month, year, projects, collaborator,
                                roleProp, handleFileUpload,
                                availableMonths = [],
                                preselectedMonths = [],
                                monthOptions,              // ← new prop
                            }: AddFileModalProps) => {

    const [searchParams, setSearchParams] = useSearchParams();

    const availableMonthOptions = monthOptions.filter((m: { value: number; name: string }) => availableMonths.includes(m.value));
    const allMonthValues = availableMonthOptions.map((m: { value: number; name: string }) => m.value);
    const selectWithAllOption = [
        { value: SELECT_ALL_VALUE, name: 'Επιλογή όλων' },
        ...availableMonthOptions,
    ];

    const [formData, setFormData] = useState<FormDataType>({
        role: roleProp ?? '',
        selectedMonths: preselectedMonths,
        file_category_id: 0,
        subfolder_id: 9,
        user_hash_id: collaborator.user.hash_id,
        file: null,
        year: year
    });

    const handleFormSubmit = async (e: FormEvent) => {
        e.preventDefault();
        if (await handleFileUpload(formData)) {
            close();
        }
    }

    useEffect(() => {
        if (month) {
            setFormData(prev => ({...prev, selectedMonths: [Number(month)]}));
        }
    }, [month]);

    useEffect(() => {
        if (year) {
            setFormData(prev => ({...prev, year}));
        }
    }, [year]);

    const allowedExtensions = ['.xls', '.xlsx', '.xlsm', '.xlsb', '.xltx', '.xltm', '.csv'];

    const isValidFileType = formData.file
        ? allowedExtensions.some(ext => formData.file!.name.toLowerCase().endsWith(ext))
        : false;

    const isFormValid = formData.selectedMonths.filter(m => m !== 0).length > 0
        && !!formData.file
        && isValidFileType;

    const handleMonthChange = (v: number[]) => {
        const selectedAll = v.includes(SELECT_ALL_VALUE);
        const prevSelectedAll = formData.selectedMonths.length === allMonthValues.length;

        let newMonths: number[];

        if (selectedAll && !prevSelectedAll) {
            newMonths = [SELECT_ALL_VALUE, ...allMonthValues];
        } else if (!selectedAll && prevSelectedAll) {
            newMonths = [];
        } else if (selectedAll && v.length < allMonthValues.length + 1) {
            newMonths = v.filter(x => x !== SELECT_ALL_VALUE);
        } else if (!selectedAll && v.length === allMonthValues.length) {
            newMonths = [SELECT_ALL_VALUE, ...allMonthValues];
        } else {
            newMonths = v;
        }

        const realMonths = newMonths.filter(m => m !== SELECT_ALL_VALUE);

        setFormData({...formData, selectedMonths: realMonths});

        if (realMonths.length === 0) {
            setSearchParams(prev => { prev.delete('month'); return prev; });
        } else if (realMonths.length === 1) {
            setSearchParams(prev => { prev.set('month', realMonths[0].toString()); return prev; });
        } else {
            setSearchParams(prev => { prev.delete('month'); return prev; });
        }
    };

    const selectValue = formData.selectedMonths.length === allMonthValues.length
        ? [SELECT_ALL_VALUE, ...formData.selectedMonths]
        : formData.selectedMonths;

    return (
        <ActionModal
            onClose={close}
            hasCloseButton
            title={<>Υποβολή Δελτίου Κίνησης
                / <span>{collaborator.user.firstname} {collaborator.user.lastname}</span></>}
        >
            <form onSubmit={handleFormSubmit}>
                <Typography tag={'p'} fontSize={'1.6rem'} color='#707070' marginBottom={'30px'}>Επιλέξτε <b>τον μήνα ή
                    τους μήνες</b> τους οποίους δηλώνετε και στη συνέχεια πατήστε <b>Υποβολή Αρχείου</b>.</Typography>
                <CustomFormSection>
                    <div className='row'>
                        <div className={'col-12 col-xxl-6'}>
                            <CustomLabel>Έτος απασχόλησης :</CustomLabel>
                            <InputFake><b>{year}</b></InputFake>
                        </div>
                        <div className={'col-12 col-xxl-6'}>
                            <CustomLabel>Έργα απασχόλησης έτους:</CustomLabel>
                            <InputFake hasCopy={false}>
                                <b>{projects?.join(', ')}</b>
                            </InputFake>
                        </div>
                    </div>
                </CustomFormSection>
                <CustomFormSection>
                    <div className="row justify-content-center g-5">
                        <div className="col-12">
                            <CustomLabel>ΕΠΙΛΕΞΤΕ ΜΗΝΑ Η ΜΗΝΕΣ</CustomLabel>
                            <MakeCustomSelect
                                multiple
                                options={selectWithAllOption}
                                handleChange={handleMonthChange}
                                value={selectValue}
                            />
                        </div>
                        <div className="col-12">
                            <CustomFileUpload
                                id="upload-alfa-ena-excel"
                                file={formData.file}
                                disabled={formData.selectedMonths.filter(m => m !== 0).length === 0}
                                accept={allowedExtensions.join(',')}
                                onChange={(f: any) => setFormData(prev => ({...prev, file: f}))}
                            />
                        </div>
                    </div>
                </CustomFormSection>
                <FormButtonsContainer justify={'center'}>
                    <FormButtonSubmit disabled={!isFormValid}>ΥΠΟΒΟΛΗ ΑΡΧΕΙΟΥ</FormButtonSubmit>
                </FormButtonsContainer>
            </form>
        </ActionModal>
    );
}

export default UploadAlfaEnaModal;
