Untitled

mail@pastecode.io avatar
unknown
plain_text
12 days ago
58 kB
2
Indexable
Never
import React, { useState, useEffect, useContext } from "react";
import { Formik, Form, Field, useField, useFormikContext } from "formik";
import { Row, Col, FormGroup, Card, CardBody, Container, button } from "reactstrap";
import AxiosService from "../../../services/AxiosService";
import * as Yup from "yup";
import "bootstrap/dist/css/bootstrap.min.css";
import "antd/dist/antd.css";
import CorporateContext from "./CorporateContextApi";
import { parseISO, differenceInYears } from 'date-fns';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import { MdCalendarToday } from 'react-icons/md';

const DatePickerField = ({ name, index, maxDate, ...props }) => {
    const { setFieldValue, values, touched, errors } = useFormikContext();  // Access Formik's setFieldValue and values
    const [field] = useField(name);  // Use the name for the field

    return (
        <div className="relative w-full crm-datepicker">
            <DatePicker
                {...field}
                {...props}
                selected={
                    values.shareholders[index]?.[name.split('.')[1]]  // Extract the correct field (e.g., dob or dobLE)
                        ? moment(values.shareholders[index][name.split('.')[1]], 'DD-MM-YYYY').toDate()
                        : null
                }
                onChange={val => {
                    if (val === null) {
                        setFieldValue(name, '');  // Clear the value when no date is selected
                    } else {
                        const formattedDate = moment(val).format('DD-MM-YYYY');
                        setFieldValue(name, formattedDate);  // Set the formatted date
                    }
                }}
                maxDate={maxDate}
                dateFormat="dd-MM-yyyy"
                placeholderText="Date Of Birth"
                peekNextMonth
                showMonthDropdown
                showYearDropdown
                dropdownMode="select"
                className={`bg-bgray-50 dark:bg-darkblack-500 dark:text-white p-4 rounded-lg h-14 w-full border-0 focus:border focus:border-success-300 focus:ring-0 ${touched.shareholders?.[index]?.[name.split('.')[1]] && errors.shareholders?.[index]?.[name.split('.')[1]]
                    ? "border-red-500"
                    : ""
                    }`}
            />
        </div>
    );
};
const getDefaultPersonData = () => ({
    fullName: '',
    dob: '',
    residentialAddress: '',
    postCode: '',
    country: '',
    percentageOfShare: '',
    legalEntityName: '',
    dobLE: '',
    legalEntityAddress: '',
    postCodeLE: '',
    countryLE: ''
});
const fetchCountries = async () => {
    try {
        const response = await AxiosService.get("/api/countries");
        return response.data.data;
    } catch (error) {
        console.error("Error fetching countries:", error);
        return [];
    }
};

const ShareholdersDirectorsForm = ({ kycResponse, fetchKycData }) => {
    const { nextPage, prev, corporateId } = useContext(CorporateContext);
    const [countries, setCountries] = useState([]);
    const [id, setId] = useState("");
    const [isNaturalHS, setIsNaturalHS] = useState(true);
    const [flage, setFlage] = useState(true);
    const [initialValuesShrhlder, setInitialValuesShrhlder] = useState({
        shareholders: [],
        directors: []
    });

    useEffect(() => {
        window.scrollTo(0, 0);
        const loadCountries = async () => {
            const fetchedCountries = await fetchCountries();
            setCountries(fetchedCountries);
        };
        loadCountries();
    }, []);



    const handleAddShareholderForm = (formikProps) => {
        // Add new shareholder with default structure
        const updatedForms = [...formikProps.values.shareholders, getDefaultPersonData()];
    
        // Update the formik values
        formikProps.setFieldValue('shareholders', updatedForms);
        setFlage(true)
    
        console.log("Updated Shareholders", updatedForms);  // Debugging purposes
    };
    

    const handleRemoveShareholderForm = (formikProps, index) => {
        const updatedForms = [...formikProps.values.shareholders];
        updatedForms.splice(index, 1);
        formikProps.setFieldValue('shareholders', updatedForms);
    };
    const handleAddDirectorForm = (formikProps) => {
        const updatedForms = [...formikProps.values.directors, getDefaultPersonData()];
        formikProps.setFieldValue('directors', updatedForms);
        
        console.log("Updated Directors", updatedForms);
    };

    const handleRemoveDirectorForm = (formikProps, index) => {
        const updatedForms = [...formikProps.values.directors];
        updatedForms.splice(index, 1);
        formikProps.setFieldValue('directors', updatedForms);
    };

    const validationSchema = Yup.object().shape({
        shareholders: Yup.array().of(
            Yup.object().shape({
                fullName: Yup.string().required("Full Name is required"),
                dob: Yup.date()
                    .required('Date of Birth is required')
                    .transform((value, originalValue) => {
                        // Convert from DD-MM-YYYY to a valid Date object
                        const parsedDate = moment(originalValue, 'DD-MM-YYYY', true);
                        return parsedDate.isValid() ? parsedDate.toDate() : new Date('');  // Return a valid date or empty
                    })
                    .test(
                        'is-18-years-old',
                        'Shareholder must be at least 18 years old',
                        value => {
                            // Check if the value is a valid date
                            return value && differenceInYears(new Date(), value) >= 18;
                        }
                    ),
                residentialAddress: Yup.string().required("Residential Address is required"),
                postCode: Yup.string()
                    .matches(/^\d+$/, "The Postal Code must be numeric"),
                // .required("Postal Code is required."),
                country: Yup.string().required("Country is required"),
                percentageOfShare: Yup.number()
                    .required("Percentage of Shareholding is required")
                    .min(0, "Percentage must be at least 0")
                    .max(100, "Percentage cannot be more than 100")
            })
        ),
        directors: Yup.array().of(
            Yup.object().shape({
                fullName: Yup.string().required("Full Name is required"),
                dob: Yup.string()
                    .required('Date of Birth is required')
                    .test('is-valid-date', 'Invalid date format', value => {
                        // Validate if it's a valid DD-MM-YYYY format
                        return moment(value, 'DD-MM-YYYY', true).isValid();
                    })
                    .test('is-18-years-old', 'Shareholder must be at least 18 years old', value => {
                        // Check if the date is at least 18 years ago
                        const parsedDate = moment(value, 'DD-MM-YYYY');
                        return moment().diff(parsedDate, 'years') >= 18;
                    }),
                residentialAddress: Yup.string().required("Residential Address is required"),
                postCode: Yup.string()
                    .matches(/^\d+$/, "The Postal Code must be numeric"),
                // .required("Postal Code is required."),
                country: Yup.string().required("Country is required"),
            })
        ),
    });
    const validationSchemaB = Yup.object().shape({
        shareholders: Yup.array().of(
            Yup.object().shape({

                legalEntityName: Yup.string().required("Legal Entity Name is required"),
                dobLE: Yup.string()
                    .required('Date of Birth is required')
                    .test('is-valid-date', 'Invalid date format', value => {
                        return moment(value, 'DD-MM-YYYY', true).isValid();
                    }),
                // .test('is-18-years-old', 'Shareholder must be at least 18 years old', value => {
                //     const parsedDate = moment(value, 'DD-MM-YYYY');
                //     return moment().diff(parsedDate, 'years') >= 18;
                // }),
                legalEntityAddress: Yup.string().required("Legal Entity Residential Address is required"),
                postCodeLE: Yup.string()
                    .matches(/^\d+$/, "The Postal Code must be numeric"),
                // .required("Legal Entity Postal Code is required."),
                countryLE: Yup.string().required("Legal Entity Country is required"),
            })
        ),
        directors: Yup.array().of(
            Yup.object().shape({
                fullName: Yup.string().required("Full Name is required"),
                dob: Yup.date()
                    .required('Date of Birth is required'),
                // .test(
                //     'is-18-years-old',
                //     'Director must be at least 18 years old',
                //     value => {
                //         return differenceInYears(new Date(), new Date(value)) >= 18;
                //     }
                // ),
                residentialAddress: Yup.string().required("Residential Address is required"),
                postCode: Yup.string()
                    .matches(/^\d+$/, "The Postal Code must be numeric"),
                // .required("Postal Code is required."),
                country: Yup.string().required("Country is required"),
            })
        ),
    });



    const handleSubmit = (values) => {
        const payload = {
            _id: corporateId,
            shareholders: values.shareholders.map(shareholder => {
                if (isNaturalHS) {
                    // Submit Natural person data
                    return {
                        self: {
                            name: shareholder.fullName,
                            dateOfBirth: shareholder.dob
                                ? moment(shareholder.dob, "DD-MM-YYYY").format("YYYY-MM-DD")
                                : null,
                            address: shareholder.residentialAddress,
                            country: shareholder.country,
                            postCode: shareholder.postCode,
                            sharePercentage: shareholder.percentageOfShare || 0
                        }
                    };
                } else {
                    // Submit Legal entity data
                    return {
                        legal: {
                            name: shareholder.legalEntityName,
                            dateOfBirth: shareholder.dobLE
                                ? moment(shareholder.dobLE, "DD-MM-YYYY").format("YYYY-MM-DD")
                                : null,
                            address: shareholder.legalEntityAddress,
                            country: shareholder.countryLE,
                            postCode: shareholder.postCodeLE
                        }
                    };
                }
            }),
            directors: values.directors.map(director => ({
                self: {
                    name: director.fullName,
                    dateOfBirth: director.dob
                        ? moment(director.dob, "DD-MM-YYYY").format("YYYY-MM-DD")
                        : null,
                    address: director.residentialAddress,
                    country: director.country,
                    postCode: director.postCode
                }
            }))
        };

        AxiosService.post("/api/corp-onboarding", payload)
            .then(response => {
                console.log("API Response:", response.data);
                setId();
                nextPage();
            })
            .catch(error => {
                console.error("Error submitting data:", error);
            });
    };

    const getDefaultPersonData = () => ({
        fullName: '',
        dob: '',
        residentialAddress: '',
        postCode: '',
        country: '',
        percentageOfShare: '',
        legalEntityName: '',
        dobLE: '',
        legalEntityAddress: '',
        postCodeLE: '',
        countryLE: ''
    });

    const parseDate = (date) => {
        return date ? new Date(date) : '';
    };

    const initialValues = {
        shareholders: Array.isArray(kycResponse?.shareholders) && kycResponse.shareholders.length > 0
            ? kycResponse.shareholders.map(shareholder => {
                return {
                    fullName: shareholder.self?.name || '',
                    dob: shareholder.self?.dateOfBirth
                        ? moment(shareholder.self?.dateOfBirth, "YYYY-MM-DD").format("DD-MM-YYYY")
                        : '',
                    residentialAddress: shareholder.self?.address || '',
                    postCode: shareholder.self?.postCode || '',
                    country: shareholder.self?.country || '',
                    percentageOfShare: shareholder.self?.sharePercentage || '',
                    legalEntityName: shareholder.legal?.name || '',
                    dobLE: shareholder.legal?.dateOfBirth
                        ? moment(shareholder.legal?.dateOfBirth, "YYYY-MM-DD").format("DD-MM-YYYY")
                        : '',
                    legalEntityAddress: shareholder.legal?.address || '',
                    postCodeLE: shareholder.legal?.postCode || '',
                    countryLE: shareholder.legal?.country || ''
                };
            })
            : [getDefaultPersonData()],

        directors: Array.isArray(kycResponse?.directors) && kycResponse.directors.length > 0
            ? kycResponse.directors.map(director => {
                return {
                    fullName: director.self?.name || '',
                    dob: director.self?.dateOfBirth
                        ? moment(director.self?.dateOfBirth, "YYYY-MM-DD").format("DD-MM-YYYY")
                        : '',
                    residentialAddress: director.self?.address || '',
                    postCode: director.self?.postCode || '',
                    country: director.self?.country || '',
                };
            })
            : [getDefaultPersonData()],
    };


    const theme = localStorage.getItem('theme');
    console.log("flage",flage);

    return (
        <Container className="">
            <Formik
                enableReinitialize={true}
                initialValues={initialValues}
                validationSchema={flage ? validationSchema : validationSchemaB}
                // validationSchema={flage && validationSchema }
                onSubmit={handleSubmit}
            >
                {(formikProps) => (

                    <Form>
                        <div className="w-full xl:px-0 mt-4 pb-3 xl:pb-12 sm:pt-2 pt-2 shadow">
                            <div className={`w-full rounded-lg ${theme === 'dark' ? 'bg-darkblack-600' : 'bg-white'} px-4 py-4`}>
                                <Row className="mb-2">
                                    <Col>
                                        <h1 className="text-2xl font-bold mt-2 leading-[24px] text-customBlue dark:text-YellowLime">Shareholders and Directors Information</h1>
                                    </Col>

                                </Row>
                                {formikProps.values.shareholders.map((_, index) => (
                                    <ShareholderDetailsForm
                                        setFlage={setFlage}
                                        setIsNaturalHS={setIsNaturalHS}
                                        key={index}
                                        index={index}
                                        countries={countries}
                                        initialValues={initialValues}
                                        // formikPropsValues={formikProps.values()}
                                        formikProps={formikProps}
                                        removeForm={(index) => handleRemoveShareholderForm(formikProps, index)}
                                        addShareholderForm={() => handleAddShareholderForm(formikProps)}
                                    />
                                ))}
                                {formikProps.values.directors.map((_, index) => (
                                    <DirectorDetailsForm
                                        key={index}
                                        index={index}
                                        initialValues={initialValues}
                                        countries={countries}
                                        formikProps={formikProps}
                                        removeForm={(index) => handleRemoveDirectorForm(formikProps, index)}
                                        addDirectorForm={() => handleAddDirectorForm(formikProps)}

                                    />
                                ))}
                                <Row>
                                    <Col lg={6}><button className="rounded-lg bg-gray-300 text-black font-semibold mt-10 py-3.5 px-4" type="button"
                                        onClick={() => {
                                            prev()
                                            fetchKycData()
                                        }}>Back</button></Col>
                                    <Col lg={6} className="text-right">
                                        <div className="text-right">
                                            <button className={`${theme === 'dark' ? 'bg-YellowLime text-black' : 'bg-customBlue text-white'} rounded-lg font-semibold mt-10 py-3.5 px-4`} type="submit" >Next</button>
                                        </div>
                                    </Col>
                                </Row>
                            </div>
                        </div>
                    </Form>
                )}
            </Formik>
        </Container>
    );
};
export default ShareholdersDirectorsForm;
const ShareholderDetailsForm = ({ index, countries, formikProps, removeForm, addShareholderForm, setIsNaturalHS, setFlage }) => {
    const [isNatural, setIsNatural] = useState(true);
    let emp=["natural"]
    const handleRadioChange = (e) => {
        setIsNatural(e.target.value === 'natural');
        setFlage(e.target.value === 'natural' ? true : false)
        setIsNaturalHS(e.target.value === 'natural' ? true : false)
        if(emp.length==0){
            emp.push(e.target.value)
        }
        else{
            if (!emp.includes(e.target.value)) { 
                  emp.push(e.target.value)
                  setFlage(null) 
                }
        }
        console.log("empp",emp);
    };
    
    const theme = localStorage.getItem('theme');
    return (

        <Card className="mb-4">
            <div className={`w-full rounded-lg ${theme === 'dark' ? 'bg-darkblack-600' : 'bg-white'}`}>
                <CardBody>
                    <Row className="mb-4">
                        <Col>
                            <h1 className="text-2xl font-semibold leading-[24px] text-customBlue dark:text-YellowLime">Shareholder-{index + 1}</h1>
                        </Col>
                        <Col className="text-right">
                            {index > 0 ? <button type="button" className="mb-2 bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-full" onClick={() => { removeForm(index); }}>
                                Delete
                            </button> : ""}
                        </Col>
                    </Row>
                    <Row>
                        <Col lg={12} className="mb-4">
                            <h3 className="text-lg font-semibold mb-3 dark:text-white">
                                Select Entity Type
                            </h3>
                            <FormGroup className="">
                                <label className="me-3 dark:text-white">
                                    <input
                                        type="radio"
                                        value="natural"
                                        checked={isNatural}
                                        onChange={handleRadioChange}
                                        className="me-1"
                                    />
                                    Natural
                                </label>
                                <label className="me-3 dark:text-white">
                                    <input
                                        type="radio"
                                        value="legal"
                                        checked={!isNatural}
                                        onChange={handleRadioChange}
                                        className="me-1"
                                    />
                                    Legal
                                </label>
                            </FormGroup>
                        </Col>
                    </Row>




                    {/* Displaying current state for testing */}
                    <p>{isNatural ? <>
                        <Row>
                            <Col lg={6} className="mb-3">
                                <h3 className="text-lg font-semibold mb-4 leading-[24px] text-bgray-900 dark:text-white">Natural Person</h3>
                                <FormGroup className="mb-4">
                                    <label htmlFor={`shareholders[${index}].fullName`} className="text-base font-bold leading-[24px] text-bgray-900 dark:text-white">
                                        Full Name <span className="required-asterisk">*</span>
                                    </label>
                                    <Field
                                        type="text"
                                        name={`shareholders[${index}].fullName`}
                                        // value={shareholder.fullName}
                                        placeholder="Enter your Full Name"
                                        className={`bg-bgray-50 dark:bg-darkblack-500 dark:text-white p-4 rounded-lg h-14 w-full border-0 focus:border focus:border-success-300 focus:ring-0  ${formikProps.touched.shareholders?.[index]?.fullName && formikProps.errors.shareholders?.[index]?.fullName
                                            ? "border-red-500"
                                            : ""
                                            }`}
                                    />
                                    {formikProps.touched.shareholders?.[index]?.fullName && formikProps.errors.shareholders?.[index]?.fullName && (
                                        <div className="text-red-500 text-sm mt-1">{formikProps.errors.shareholders[index].fullName}</div>
                                    )}
                                </FormGroup>
                            </Col>
                            <Col lg={6} className="mb-3 mt-12">
                                <FormGroup key={index} className="mb-4">
                                    <label htmlFor={`shareholders[${index}].dob`} className="text-base font-bold leading-[24px] text-bgray-900 dark:text-white">
                                        Date of Birth <span className="required-asterisk">*</span>
                                    </label>
                                    <div className="relative w-full crm-datepicker">
                                        <DatePickerField
                                            placeholder="Date Of Birth"
                                            name={`shareholders[${index}].dob`}
                                            maxDate={moment().subtract(18, "years").toDate()}
                                            index={index}
                                            className="bg-bgray-50 dark:bg-darkblack-500 dark:text-white p-4 rounded-lg h-14 border-0 focus:border focus:border-success-300 focus:ring-0 w-full pr-12" // Ensure padding-right is set so text doesn't overlap with the icon
                                        />
                                        <span className="absolute right-4 top-1/2 transform -translate-y-1/2 calendar-iconS flex items-center text-gray-500 dark:text-white">
                                            <MdCalendarToday />
                                        </span>
                                    </div>
                                    {formikProps.touched.shareholders?.[index]?.dob && formikProps.errors.shareholders?.[index]?.dob && (
                                        <div className="text-red-500 text-sm mt-1">{formikProps.errors.shareholders[index].dob}</div>
                                    )}
                                </FormGroup>
                            </Col>
                        </Row>
                        <Row>
                            <Col lg={6} className="mb-3">
                                <FormGroup className="mb-4">
                                    <label htmlFor={`shareholders[${index}].residentialAddress`} className="text-base font-bold leading-[24px] text-bgray-900 dark:text-white">
                                        Residential Address <span className="required-asterisk">*</span>
                                    </label>
                                    <Field
                                        type="text"
                                        name={`shareholders[${index}].residentialAddress`}
                                        placeholder="Enter your Residential Address"
                                        className={`bg-bgray-50 dark:bg-darkblack-500 dark:text-white p-4 rounded-lg h-14 w-full border-0 focus:border focus:border-success-300 focus:ring-0  ${formikProps.touched.shareholders?.[index]?.residentialAddress && formikProps.errors.shareholders?.[index]?.residentialAddress
                                            ? "border-red-500"
                                            : ""
                                            }`}
                                    />
                                    {formikProps.touched.shareholders?.[index]?.residentialAddress && formikProps.errors.shareholders?.[index]?.residentialAddress && (
                                        <div className="text-red-500 text-sm mt-1">{formikProps.errors.shareholders[index].residentialAddress}</div>
                                    )}
                                </FormGroup>
                            </Col>
                            <Col lg={6} className="mb-3">
                                <FormGroup className="mb-4">
                                    <label htmlFor={`shareholders[${index}].postCode`} className="text-base font-bold leading-[24px] text-bgray-900 dark:text-white">
                                        Post Code
                                    </label>
                                    <Field
                                        type="text"
                                        name={`shareholders[${index}].postCode`}
                                        placeholder="Enter your Post Code"
                                        className={`bg-bgray-50 dark:bg-darkblack-500 dark:text-white p-4 rounded-lg h-14 w-full border-0 focus:border focus:border-success-300 focus:ring-0  ${formikProps.touched.shareholders?.[index]?.postCode && formikProps.errors.shareholders?.[index]?.postCode
                                            ? "border-red-500"
                                            : ""
                                            }`}
                                    />
                                    {formikProps.touched.shareholders?.[index]?.postCode && formikProps.errors.shareholders?.[index]?.postCode && (
                                        <div className="text-red-500 text-sm mt-1">{formikProps.errors.shareholders[index].postCode}</div>
                                    )}
                                </FormGroup>
                            </Col>
                        </Row>
                        <Row>
                            <Col lg={6} className="mb-3">
                                <FormGroup className="mb-4">
                                    <label htmlFor={`shareholders[${index}].country`} className="text-base font-bold leading-[24px] text-bgray-900 dark:text-white">
                                        Country <span className="required-asterisk">*</span>
                                    </label>
                                    <Field
                                        as="select"
                                        name={`shareholders[${index}].country`}
                                        className={`bg-bgray-50 dark:bg-darkblack-500 dark:text-white rounded-lg h-14 w-full border-0 focus:border focus:border-success-300 focus:ring-0 ${formikProps.touched.shareholders?.[index]?.country && formikProps.errors.shareholders?.[index]?.country
                                            ? "border-red-500"
                                            : ""
                                            }`}
                                    >
                                        <option value="">Select Country</option>
                                        {countries.map((country) => (
                                            <option key={country._id} value={country.name}>
                                                {country.name}
                                            </option>
                                        ))}
                                    </Field>
                                    {formikProps.touched.shareholders?.[index]?.country && formikProps.errors.shareholders?.[index]?.country && (
                                        <div className="text-red-500 text-sm mt-1">{formikProps.errors.shareholders[index].country}</div>
                                    )}
                                </FormGroup>
                            </Col>
                            <Col lg={6} className="mb-3">
                                <FormGroup className="mb-4">
                                    <label htmlFor={`shareholders[${index}].percentageOfShare`} className="text-base font-bold leading-[24px] text-bgray-900 dark:text-white">
                                    Percentage of Shareholding <span className="required-asterisk">*</span>
                                    </label>
                                    <Field
                                        type="number"
                                        name={`shareholders[${index}].percentageOfShare`}
                                        id="percentageOfShare"
                                        placeholder="Enter Percentage of Shareholding"
                                        className={`bg-bgray-50 dark:bg-darkblack-500 dark:text-white p-4 rounded-lg h-14 w-full border-0 focus:border focus:border-success-300 focus:ring-0  ${formikProps.touched.shareholders?.[index]?.percentageOfShare && formikProps.errors.shareholders?.[index]?.percentageOfShare
                                            ? "border-red-500"
                                            : ""
                                            }`}
                                    />
                                    {formikProps.touched.shareholders?.[index]?.percentageOfShare && formikProps.errors.shareholders?.[index]?.percentageOfShare && (
                                        <div className="text-red-500 text-sm mt-1">{formikProps.errors.shareholders[index].percentageOfShare}</div>
                                    )}
                                </FormGroup>
                            </Col>
                        </Row></> : <>
                        <Row>
                            <Col lg={6} className="mb-3">
                                <h3 className="text-lg font-semibold mb-4 leading-[24px] text-bgray-900 dark:text-white">Legal Entity</h3>
                                <FormGroup className="mb-4">
                                    <label htmlFor={`shareholders[${index}].legalEntityName`} className="text-base font-bold leading-[24px] text-bgray-900 dark:text-white">
                                        Legal Entity Name <span className="required-asterisk">*</span>
                                    </label>
                                    <Field
                                        type="text"
                                        name={`shareholders[${index}].legalEntityName`}
                                        placeholder="Enter your Legal Full Name"
                                        className={`bg-bgray-50 dark:bg-darkblack-500 dark:text-white p-4 rounded-lg h-14 w-full border-0 focus:border focus:border-success-300 focus:ring-0  ${formikProps.touched.shareholders?.[index]?.legalEntityName && formikProps.errors.shareholders?.[index]?.legalEntityName
                                            ? "border-red-500"
                                            : ""
                                            }`}
                                    />
                                    {formikProps.touched.shareholders?.[index]?.legalEntityName && formikProps.errors.shareholders?.[index]?.legalEntityName && (
                                        <div className="text-red-500 text-sm mt-1">{formikProps.errors.shareholders[index].legalEntityName}</div>
                                    )}
                                </FormGroup>
                            </Col>
                            <Col lg={6} className="mb-3 mt-12">
                                <FormGroup key={index} className="mb-4">
                                    <label htmlFor={`shareholders[${index}].dobLE`} className="text-base font-bold leading-[24px] text-bgray-900 dark:text-white">
                                    Date of incorporation <span className="required-asterisk">*</span>
                                    </label>
                                    <div className="relative w-full crm-datepicker">
                                        <DatePickerField
                                            maxDate={null}
                                            name={`shareholders[${index}].dobLE`}
                                            index={index}
                                            className="bg-bgray-50 dark:bg-darkblack-500 dark:text-white p-4 rounded-lg h-14 border-0 focus:border focus:border-success-300 focus:ring-0 w-full pr-12" // Ensure padding-right is set so text doesn't overlap with the icon
                                        />
                                        <span className="absolute right-4 top-1/2 transform -translate-y-1/2 calendar-iconS flex items-center text-gray-500 dark:text-white">
                                            <MdCalendarToday />
                                        </span>
                                    </div>
                                    {formikProps.touched.shareholders?.[index]?.dobLE && formikProps.errors.shareholders?.[index]?.dobLE && (
                                        <div className="text-red-500 text-sm mt-1">{formikProps.errors.shareholders[index].dobLE}</div>
                                    )}
                                </FormGroup>
                            </Col>
                        </Row>
                        <Row>
                            <Col lg={6} className="mb-3">
                                <FormGroup className="mb-4">
                                    <label htmlFor={`shareholders[${index}].legalEntityAddress`} className="text-base font-bold leading-[24px] text-bgray-900 dark:text-white">
                                        Legal Entity Residential Address <span className="required-asterisk">*</span>
                                    </label>
                                    <Field
                                        type="text"
                                        name={`shareholders[${index}].legalEntityAddress`}
                                        placeholder="Enter your Legal Residential Address"
                                        className={`bg-bgray-50 dark:bg-darkblack-500 dark:text-white p-4 rounded-lg h-14 w-full border-0 focus:border focus:border-success-300 focus:ring-0  ${formikProps.touched.shareholders?.[index]?.legalEntityAddress && formikProps.errors.shareholders?.[index]?.legalEntityAddress
                                            ? "border-red-500"
                                            : ""
                                            }`}
                                    />
                                    {formikProps.touched.shareholders?.[index]?.legalEntityAddress && formikProps.errors.shareholders?.[index]?.legalEntityAddress && (
                                        <div className="text-red-500 text-sm mt-1">{formikProps.errors.shareholders[index].legalEntityAddress}</div>
                                    )}
                                </FormGroup>
                            </Col>
                            <Col lg={6} className="mb-3">
                                <FormGroup className="mb-4">
                                    <label htmlFor={`shareholders[${index}].postCodeLE`} className="text-base font-bold leading-[24px] text-bgray-900 dark:text-white">
                                        Post Code 
                                    </label>
                                    <Field
                                        type="text"
                                        name={`shareholders[${index}].postCodeLE`}
                                        placeholder="Enter your Legal Post Code"
                                        className={`bg-bgray-50 dark:bg-darkblack-500 dark:text-white p-4 rounded-lg h-14 w-full border-0 focus:border focus:border-success-300 focus:ring-0  ${formikProps.touched.shareholders?.[index]?.postCodeLE && formikProps.errors.shareholders?.[index]?.postCodeLE
                                            ? "border-red-500"
                                            : ""
                                            }`}
                                    />
                                    {formikProps.touched.shareholders?.[index]?.postCodeLE && formikProps.errors.shareholders?.[index]?.postCodeLE && (
                                        <div className="text-red-500 text-sm mt-1">{formikProps.errors.shareholders[index].postCodeLE}</div>
                                    )}
                                </FormGroup>
                            </Col>
                        </Row>
                        <Row>
                            <Col lg={6} className="mb-3">
                                <FormGroup className="mb-4">
                                    <label htmlFor={`shareholders[${index}].countryLE`} className="text-base font-bold leading-[24px] text-bgray-900 dark:text-white">
                                        Country <span className="required-asterisk">*</span>
                                    </label>
                                    <Field
                                        as="select"
                                        name={`shareholders[${index}].countryLE`}
                                        className={`bg-bgray-50 dark:bg-darkblack-500 dark:text-white rounded-lg h-14 w-full border-0 focus:border focus:border-success-300 focus:ring-0  ${formikProps.touched.shareholders?.[index]?.countryLE && formikProps.errors.shareholders?.[index]?.countryLE
                                            ? "border-red-500"
                                            : ""
                                            }`}
                                    >
                                        <option value="">Select Country</option>
                                        {countries.map((country) => (
                                            <option key={country._id} value={country.name}>
                                                {country.name}
                                            </option>
                                        ))}
                                    </Field>
                                    {formikProps.touched.shareholders?.[index]?.countryLE && formikProps.errors.shareholders?.[index]?.countryLE && (
                                        <div className="text-red-500 text-sm mt-1">{formikProps.errors.shareholders[index].countryLE}</div>
                                    )}
                                </FormGroup>
                            </Col></Row></>}</p>
                    <Row className="h-10">
                        <Col lg={12} className="text-right">
                            <button type="button"
                                className={`${theme === 'dark' ? 'bg-YellowLime text-black' : 'bg-customBlue text-white'} rounded-full font-semibold py-2 px-3.5`}
                                // className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-full" 
                                onClick={addShareholderForm}>
                                Add Shareholder
                            </button>
                        </Col>
                    </Row>
                </CardBody>
            </div>
        </Card >
    );
};


const DirectorDetailsForm = ({ index, countries, formikProps, removeForm, addDirectorForm }) => {
    const theme = localStorage.getItem('theme');
    const handleCopyShareholder = (e, directorIndex) => {
        const isChecked = e.target.checked;
        
        // Access the corresponding shareholder (matching index)
        const correspondingShareholder = formikProps.values.shareholders[directorIndex];
        
        if (isChecked && correspondingShareholder) {
            // Copy shareholder data to director
            formikProps.setFieldValue(`directors[${directorIndex}].fullName`, correspondingShareholder.fullName);
            formikProps.setFieldValue(`directors[${directorIndex}].dob`, correspondingShareholder.dob);
            formikProps.setFieldValue(`directors[${directorIndex}].residentialAddress`, correspondingShareholder.residentialAddress);
            formikProps.setFieldValue(`directors[${directorIndex}].postCode`, correspondingShareholder.postCode);
            formikProps.setFieldValue(`directors[${directorIndex}].country`, correspondingShareholder.country);
            
            // Trigger validation for the copied fields
            formikProps.validateField(`directors[${directorIndex}].fullName`);
            formikProps.validateField(`directors[${directorIndex}].dob`);
            formikProps.validateField(`directors[${directorIndex}].residentialAddress`);
            formikProps.validateField(`directors[${directorIndex}].postCode`);
            formikProps.validateField(`directors[${directorIndex}].country`);
        } else {
            // Clear the director fields if checkbox is unchecked
            formikProps.setFieldValue(`directors[${directorIndex}].fullName`, '');
            formikProps.setFieldValue(`directors[${directorIndex}].dob`, '');
            formikProps.setFieldValue(`directors[${directorIndex}].residentialAddress`, '');
            formikProps.setFieldValue(`directors[${directorIndex}].postCode`, '');
            formikProps.setFieldValue(`directors[${directorIndex}].country`, '');
            
            // Optionally trigger validation on clear
            formikProps.validateField(`directors[${directorIndex}].fullName`);
            formikProps.validateField(`directors[${directorIndex}].dob`);
            formikProps.validateField(`directors[${directorIndex}].residentialAddress`);
            formikProps.validateField(`directors[${directorIndex}].postCode`);
            formikProps.validateField(`directors[${directorIndex}].country`);
        }
    };
    
    return (
        <Card className="mb-4">
            <div className={`w-full rounded-lg ${theme === 'dark' ? 'bg-darkblack-600' : 'bg-white'}`}>
                <CardBody>
                    <Row className="mb-4">
                        <Col lg={12} className="mb-3">
                            <FormGroup className="flex items-center">
                            <input
                                id={`directors[${index}].copyShareholder`} // Ensure id matches
                                type="checkbox"
                                name={`directors[${index}].copyShareholder`}
                                className="h-5 w-5 text-customBlue focus:ring-customBlue"
                                onChange={(e) => handleCopyShareholder(e, index)}
                            />
                                <label
                                    htmlFor={`directors[${index}].copyShareholder`}
                                    className="text-base font-semibold text-bgray-900 dark:text-white ml-2"
                                >
                                    Same as shareholder
                                </label>
                            </FormGroup>
                        </Col>
                        <Col>
                            <h2 className="text-2xl font-semibold leading-[24px] text-customBlue dark:text-YellowLime">
                                Director-{index + 1}
                            </h2>
                        </Col>
                        <Col className="text-right">
                            {index > 0 ? (
                                <button
                                    type="button"
                                    className="mb-2 bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-full"
                                    onClick={() => removeForm(index)}
                                >
                                    Delete
                                </button>
                            ) : ""}
                        </Col>
                    </Row>

                    {/* Natural Person Section */}
                    <Row>
                        <Col lg={12} className="mb-3">
                            <h3 className="text-lg font-semibold mb-4 leading-[24px] text-bgray-900 dark:text-white">
                                Natural Person <span className="required-asterisk">*</span>
                            </h3>
                        </Col>
                    </Row>

                    {/* Other form fields in two columns per row */}
                    <Row>
                        <Col lg={6} className="mb-3">
                            <FormGroup className="mb-4">
                                <label
                                    htmlFor={`directors[${index}].fullName`}
                                    className="text-base font-bold leading-[24px] text-bgray-900 dark:text-white"
                                >
                                    Full Name <span className="required-asterisk">*</span>
                                </label>
                                <Field
                                    type="text"
                                    name={`directors[${index}].fullName`}
                                    placeholder="Enter your Legal Full Name"
                                    className={`bg-bgray-50 dark:bg-darkblack-500 dark:text-white p-4 rounded-lg h-14 w-full border-0 focus:border focus:border-success-300 focus:ring-0 ${formikProps.touched.directors?.[index]?.fullName && formikProps.errors.directors?.[index]?.fullName
                                        ? "border-red-500"
                                        : ""
                                        }`}
                                />
                                {formikProps.touched.directors?.[index]?.fullName && formikProps.errors.directors?.[index]?.fullName && (
                                    <div className="text-red-500 text-sm mt-1">{formikProps.errors.directors[index].fullName}</div>
                                )}
                            </FormGroup>
                        </Col>
                        <Col lg={6} className="mb-3">
                            <FormGroup className="mb-4">
                                <label
                                    htmlFor={`directors[${index}].dob`}
                                    className="text-base font-bold leading-[24px] text-bgray-900 dark:text-white"
                                >
                                    Date of Birth <span className="required-asterisk">*</span>
                                </label>
                                <div className="relative w-full crm-datepicker">
                                    <DatePickerField
                                        name={`directors[${index}].dob`}
                                        maxDate={moment().subtract(18, "years").toDate()}
                                        index={index}
                                        className="bg-bgray-50 dark:bg-darkblack-500 dark:text-white p-4 rounded-lg h-14 border-0 focus:border focus:border-success-300 focus:ring-0 w-full pr-12" // Ensure padding-right is set so text doesn't overlap with the icon
                                    />
                                    <span className="absolute right-4 top-1/2 transform -translate-y-1/2 calendar-iconS flex items-center text-gray-500 dark:text-white">
                                        <MdCalendarToday />
                                    </span>
                                </div>

                                {formikProps.touched.directors?.[index]?.dob && formikProps.errors.directors?.[index]?.dob && (
                                    <div className="text-red-500 text-sm mt-1">{formikProps.errors.directors[index].dob}</div>
                                )}
                            </FormGroup>
                        </Col>
                    </Row>

                    <Row>
                        <Col lg={6} className="mb-3">
                            <FormGroup className="mb-4">
                                <label
                                    htmlFor={`directors[${index}].residentialAddress`}
                                    className="text-base font-bold leading-[24px] text-bgray-900 dark:text-white"
                                >
                                    Residential Address <span className="required-asterisk">*</span>
                                </label>
                                <Field
                                    type="text"
                                    name={`directors[${index}].residentialAddress`}
                                    placeholder="Enter your Legal Residential Address"
                                    className={`bg-bgray-50 dark:bg-darkblack-500 dark:text-white p-4 rounded-lg h-14 w-full border-0 focus:border focus:border-success-300 focus:ring-0 ${formikProps.touched.directors?.[index]?.residentialAddress && formikProps.errors.directors?.[index]?.residentialAddress
                                        ? "border-red-500"
                                        : ""
                                        }`}
                                />
                                {formikProps.touched.directors?.[index]?.residentialAddress && formikProps.errors.directors?.[index]?.residentialAddress && (
                                    <div className="text-red-500 text-sm mt-1">{formikProps.errors.directors[index].residentialAddress}</div>
                                )}
                            </FormGroup>
                        </Col>
                        <Col lg={6} className="mb-3">
                            <FormGroup className="mb-4">
                                <label
                                    htmlFor={`directors[${index}].postCode`}
                                    className="text-base font-bold leading-[24px] text-bgray-900 dark:text-white"
                                >
                                    Post Code
                                </label>
                                <Field
                                    type="text"
                                    name={`directors[${index}].postCode`}
                                    placeholder="Enter your Legal Post Code"
                                    className={`bg-bgray-50 dark:bg-darkblack-500 dark:text-white p-4 rounded-lg h-14 w-full border-0 focus:border focus:border-success-300 focus:ring-0 ${formikProps.touched.directors?.[index]?.postCode && formikProps.errors.directors?.[index]?.postCode
                                        ? "border-red-500"
                                        : ""
                                        }`}
                                />
                                {formikProps.touched.directors?.[index]?.postCode && formikProps.errors.directors?.[index]?.postCode && (
                                    <div className="text-red-500 text-sm mt-1">{formikProps.errors.directors[index].postCode}</div>
                                )}
                            </FormGroup>
                        </Col>
                    </Row>

                    <Row>
                        <Col lg={6} className="mb-3">
                            <FormGroup className="mb-4">
                                <label
                                    htmlFor={`directors[${index}].country`}
                                    className="text-base font-bold leading-[24px] text-bgray-900 dark:text-white"
                                >
                                    Country <span className="required-asterisk">*</span>
                                </label>
                                <Field
                                    as="select"
                                    name={`directors[${index}].country`}
                                    className={`bg-bgray-50 dark:bg-darkblack-500 dark:text-white rounded-lg h-14 w-full border-0 focus:border focus:border-success-300 focus:ring-0 ${formikProps.touched.directors?.[index]?.country && formikProps.errors.directors?.[index]?.country
                                        ? "border-red-500"
                                        : ""
                                        }`}
                                >
                                    <option value="">Select Country</option>
                                    {countries.map((country) => (
                                        <option key={country._id} value={country.name}>
                                            {country.name}
                                        </option>
                                    ))}
                                </Field>
                                {formikProps.touched.directors?.[index]?.country && formikProps.errors.directors?.[index]?.country && (
                                    <div className="text-red-500 text-sm mt-1">{formikProps.errors.directors[index].country}</div>
                                )}
                            </FormGroup>
                        </Col>
                    </Row>

                    <Row className="h-10">
                        <Col lg={12} className="text-right">
                            <button
                                type="button"
                                className={`${theme === 'dark' ? 'bg-YellowLime text-black' : 'bg-customBlue text-white'} mb-2 rounded-full font-semibold py-2 px-4`}
                                onClick={addDirectorForm}
                            >
                                Add Director
                            </button>
                        </Col>
                    </Row>
                </CardBody>
            </div>
        </Card>
    );
};






Leave a Comment