import React, {ReactNode, useState} from 'react';
import ConfirmationModal from "../../../../UI/Modal/ActionsModal/ConfirmationModal";
import CustomFormSection from '../../../../UI/Forms/CustomFormSection/CustomFormSection';
import CustomLabel from '../../../../UI/Forms/CustomLabel/CustomLabel';
import CustomDatePicker from '../../../../UI/Forms/CustomDateTimePicker/CustomDatePicker';
import {LocalizationProvider} from '@mui/x-date-pickers';
import {AdapterDayjs} from '@mui/x-date-pickers/AdapterDayjs';
import dayjs, {Dayjs} from 'dayjs';
import CustomTextField from "../../../../UI/Forms/CustomTextField/CustomTextField";
import CustomCheckbox from "../../../../UI/Forms/CustomCheckbox/CustomCheckbox";

type ExtendCardModalProps = {
    children?: ReactNode
    close: any
    newCard: (dateFrom: Dayjs | string | null, dateTo: Dayjs | string | null, projectCode: string, initA1: boolean) => any
    currentDate: Dayjs | string | null
    currentDateFrom?: Dayjs | string | null
    existingRequest?: any
}

const ExtendCardModal = ({children, newCard, close, currentDate, currentDateFrom = null, existingRequest = null}: ExtendCardModalProps) => {

    const [dateFrom, setDateFrom] = useState<Dayjs | null | string>(currentDateFrom ?? dayjs())
    const [date, setDate] = useState<Dayjs | null | string>(currentDate)
    const [projectCode, setProjectCode] = useState<string>('')
    const [initA1, setinitA1] = useState<boolean>(false)

    // ⚠️ Assumption: the check endpoint returns null/falsy when there's no active
    // request, truthy when one exists. Unverified against the real API contract.
    const hasActiveRequest = Boolean(existingRequest)

    const handleProjectCodeChange = (value: string) => {
        // only digits, max 5 characters
        if (/^\d{0,5}$/.test(value)) {
            setProjectCode(value)
        }
    }

    const isProjectCodeValid = projectCode.length === 5

    const isDisabled = hasActiveRequest
        ? false
        : (date === null || dateFrom === null || (!isProjectCodeValid && initA1))

    return (

        <ConfirmationModal
            FormButtonSubmitText={hasActiveRequest ? 'OK' : 'ΑΝΑΝΕΩΣΗ ΚΑΡΤΑΣ'}
            FormButtonCancelText={'ΑΚΥΡΩΣΗ'}
            onClose={() => close()}
            title={'Ανανέωση κάρτας πύλης'}
            text={
                hasActiveRequest
                    ? ''
                    : `Συμπληρώστε τη νέα ημερομηνία λήξης της κάρτας πύλης.<br/> Εφόσον απαιτείται, μπορείτε να αρχικοποιήσετε και το Α1.`
            }
            modalAction={hasActiveRequest ? () => close() : () => newCard(dateFrom, date, projectCode, initA1)}
            className={'edit-card-date'}
            isDisabled={isDisabled}
        >

            {hasActiveRequest ? (
                <div className={'form'}>
                    <CustomFormSection theme={'default'}>
                        <div className={'d-flex align-items-center justify-content-center'}>
                            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <circle cx="8" cy="8" r="7" stroke="--generic-block-border-hover" stroke-width="1.3"/>
                                <circle cx="8" cy="4.8" r="0.9" fill="--generic-block-border-hover"/>
                                <rect x="7.3" y="7" width="1.4" height="5" rx="0.7" fill="--generic-block-border-hover"/>
                            </svg>
                            <p style={{fontSize:'16px',marginLeft:'10px',textAlign:'center', color:'--generic-block-border-hover'}}>Η υποβολή νέου αιτήματος δεν είναι διαθέσιμη <b>όσο εκκρεμεί</b> άλλο αίτημα.</p>
                        </div>
                    </CustomFormSection>
                </div>
            ) : (
                <div className={'form'}>
                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                        <div className={'row w-100 flex-column'}>
                            <CustomFormSection theme={'default'}>
                                <div className='row justify-content-center mb-5'>
                                    <div className={'col-6 '}>
                                        <CustomLabel>
                                            ΚΑΡΤΑ ΠΥΛΗΣ ΑΠΟ:
                                        </CustomLabel>
                                        <CustomDatePicker class='extend-card-date-from' value={dateFrom} readOnly={false} onChange={(newValue: Dayjs) => setDateFrom(newValue)}/>
                                    </div>
                                    <div className={'col-6 '}>
                                        <CustomLabel>
                                            ΚΑΡΤΑ ΠΥΛΗΣ ΕΩΣ:
                                        </CustomLabel>
                                        <CustomDatePicker class='extend-card-date' value={date} readOnly={false} onChange={(newValue: Dayjs) => setDate(newValue)}/>
                                    </div>
                                </div>
                                {children}
                            </CustomFormSection>
                            <CustomFormSection theme={'default'}>
                                <div className='row justify-content-center'>
                                    <div className={initA1 ? 'col-6' : 'col-12'} style={{ display: 'flex', alignItems: 'flex-start', gap: '8px' }}>
                                        <CustomCheckbox
                                            label={
                                                <div style={{ display: 'flex', flexDirection: 'column' }}>
                    <span style={{ fontWeight: 600, color: '--generic-block-border-hover', fontSize: '14px' }}>
                        Αρχικοποίηση εντύπου Α1
                    </span>
                                                    <span style={{ fontSize: '12px', color: '--title-color', marginTop: '2px' }}>
                        Με ίδια περίοδο ισχύος με την κάρτα πύλης.
                    </span>
                                                </div>
                                            }
                                            name="init_a1"
                                            checked={initA1}
                                            onChange={() => { setinitA1(!initA1) }}
                                            checkedBackgroundColor="#61C765"
                                            checkmarkColor="#FFFFFF"
                                        />
                                    </div>
                                    {initA1 &&
                                        <div className={'col-6'}>
                                            <CustomLabel req={initA1 && true}>
                                                Κωδικός Έργου:
                                            </CustomLabel>
                                            <CustomTextField
                                                type='text'
                                                inputMode='numeric'
                                                maxLength={5}
                                                value={projectCode}
                                                onChange={handleProjectCodeChange}
                                                placeholder={'π.χ. 12345'}
                                                required={initA1 && true}
                                            />
                                        </div>
                                    }

                                </div>
                            </CustomFormSection>
                        </div>

                    </LocalizationProvider>
                </div>
            )}

        </ConfirmationModal>
    );
}

export default ExtendCardModal;