import React, { useState } from 'react';
import { Box, Input, Text, VStack, HStack } from '@chakra-ui/react';
import { SlCloudUpload } from 'react-icons/sl';
import PhoneInput from 'react-phone-input-2';

const OnboardingDirectorDetails = () => {
    const [directorForms, setDirectorForms] = useState([
        { id: 1, directorName: '', directorEmail: '', directorPhone: '', selectedPanImage: '', selectedAadharImage: '' }
    ]);

    const [directorFormErrors, setDirectorFormErrors] = useState([]);

    // Add new director form
    const handleAddDirector = () => {
        setDirectorForms([
            ...directorForms,
            { id: directorForms.length + 1, directorName: '', directorEmail: '', directorPhone: '', selectedPanImage: '', selectedAadharImage: '' }
        ]);
    };

    // Update the form field for a particular director
    const handleFieldChange = (index, field, value) => {
        const updatedForms = [...directorForms];
        updatedForms[index][field] = value;
        setDirectorForms(updatedForms);
    };

    // Handle file upload for PAN and Aadhar
    const handleFileUpload = (index, field, event) => {
        const file = event.target.files[0];
        if (file) {
            const updatedForms = [...directorForms];
            updatedForms[index][field] = file.name; // Store file name (or file object)
            setDirectorForms(updatedForms);
        }
    };

    // Basic validation for each field
    const validateForm = () => {
        const errors = directorForms.map((directorForm) => {
            let formErrors = {};

            if (!directorForm.directorName) {
                formErrors.directorName = "Director Name is required.";
            }

            if (!directorForm.directorEmail || !/\S+@\S+\.\S+/.test(directorForm.directorEmail)) {
                formErrors.directorEmail = "Please enter a valid email address.";
            }

            if (!directorForm.directorPhone || directorForm.directorPhone.length < 10) {
                formErrors.directorPhone = "Phone number is required and should be at least 10 digits.";
            }

            if (!directorForm.selectedPanImage) {
                formErrors.selectedPanImage = "Please upload a PAN file.";
            }

            if (!directorForm.selectedAadharImage) {
                formErrors.selectedAadharImage = "Please upload an Aadhar file.";
            }

            return formErrors;
        });

        setDirectorFormErrors(errors);

        // Check if all forms are valid (no errors in any form)
        const isValid = errors.every((formErrors) => Object.keys(formErrors).length === 0);
        return isValid;
    };

    // Handle form submission
    const handleSubmit = () => {
        if (validateForm()) {
            console.log("Form is valid, proceed with submission.");
        } else {
            console.log("Form has errors.");
        }
    };

    return (
        <Box>
            <Text color={'#49475A'} fontWeight={500} fontSize={'sm'} mb={1}>
                Add director details
            </Text>
            <Text color={'#49475A'} fontWeight={500} fontSize={'xs'}>
                Lorem ipsum dolor sit amet, adipiscing elit.
            </Text>

            {directorForms?.map((directorForm, index) => (
                <Box key={index} mb={6}>
                    <Text color={'#49475A'} fontWeight={600} fontSize={'sm'} mb={2}>
                        Director {index + 1}
                    </Text>
                    <Box
                        as="form"
                        bg={"#f7f7fb"}
                        p={4}
                        borderRadius={"md"}
                        boxShadow={"md"}
                    >
                        {/* Director Name Field */}
                        <Box mb={3}>
                            <Text color={"#344054"} fontSize={"xs"} fontWeight={500} mb={1}>
                                Director Name
                            </Text>
                            <Input
                                type='text'
                                border="1px solid #e2e8f0"
                                borderRadius="md"
                                fontSize={"sm"}
                                fontWeight={500}
                                bg={"#fff"}
                                placeholder="Enter director name"
                                value={directorForm.directorName}
                                onChange={(e) => handleFieldChange(index, 'directorName', e.target.value)}
                            />
                            {directorFormErrors[index]?.directorName && (
                                <Text color="red.500" fontSize="xs">{directorFormErrors[index].directorName}</Text>
                            )}
                        </Box>

                        {/* Director Email Field */}
                        <Box mb={3}>
                            <Text color={"#344054"} fontSize={"xs"} fontWeight={500} mb={1}>
                                Email
                            </Text>
                            <Input
                                type='email'
                                border="1px solid #e2e8f0"
                                borderRadius="md"
                                fontSize={"sm"}
                                fontWeight={500}
                                bg={"#fff"}
                                placeholder="Enter email"
                                value={directorForm.directorEmail}
                                onChange={(e) => handleFieldChange(index, 'directorEmail', e.target.value)}
                            />
                            {directorFormErrors[index]?.directorEmail && (
                                <Text color="red.500" fontSize="xs">{directorFormErrors[index].directorEmail}</Text>
                            )}
                        </Box>

                        {/* Director Phone Number */}
                        <Box mb={3}>
                            <Text
                                color={"#344054"}
                                fontSize={"xs"}
                                fontWeight={500}
                                mb={1}
                            >
                                Phone Number
                            </Text>
                            <PhoneInput
                                country={"in"}
                                value={directorForm.directorPhone}
                                onChange={(value) => handleFieldChange(index, 'directorPhone', value)}
                                inputStyle={{
                                    width: "100%",
                                    borderRadius: "md",
                                    paddingLeft: "6",
                                    border: "1px solid #e2e8f0",
                                    height: "40px"
                                }}
                                buttonStyle={{
                                    border: "none",
                                    borderRadius: "8px 0 0 8px",
                                    backgroundColor: "transparent",
                                }}
                            />
                            {directorFormErrors[index]?.directorPhone && (
                                <Text color="red.500" fontSize="xs">{directorFormErrors[index].directorPhone}</Text>
                            )}
                        </Box>

                        {/* Upload Pan */}
                        <Box mb={3}>
                            <Text color={"#344054"} fontSize={"xs"} fontWeight={500} mb={1}>
                                Upload Pan
                            </Text>
                            <Box my={2}
                                position="relative"
                                onClick={() => document.getElementById(`pan-file-input-${index}`).click()}
                            >
                                <VStack
                                    border={"1px dashed #D0D5DD"}
                                    boxShadow={"md"}
                                    borderRadius={"md"}
                                    bg={"#faf8fd"}
                                    p={4}
                                    h={"28"}
                                    justifyContent={"center"}
                                    cursor="pointer"
                                >
                                    <SlCloudUpload color={"#191D23"} size={30} />
                                    <Text
                                        color={"#191D23"}
                                        fontWeight={"500"}
                                        fontSize={"sm"}
                                        mt={'2'}
                                        mb={0}
                                    >
                                        {directorForm.selectedPanImage || "Drag and drop files here or Choose file"}
                                    </Text>
                                </VStack>
                                <input
                                    type="file"
                                    id={`pan-file-input-${index}`}
                                    style={{ display: 'none' }}
                                    onChange={(e) => handleFileUpload(index, 'selectedPanImage', e)}
                                />
                            </Box>
                            {directorFormErrors[index]?.selectedPanImage && (
                                <Text color="red.500" fontSize="xs">{directorFormErrors[index].selectedPanImage}</Text>
                            )}
                        </Box>

                        {/* Upload Aadhar */}
                        <Box mb={3}>
                            <Text color={"#344054"} fontSize={"xs"} fontWeight={500} mb={1}>
                                Upload Aadhar
                            </Text>
                            <Box my={2}
                                position="relative"
                                onClick={() => document.getElementById(`aadhar-file-input-${index}`).click()}
                            >
                                <VStack
                                    border={"1px dashed #D0D5DD"}
                                    boxShadow={"md"}
                                    borderRadius={"md"}
                                    bg={"#faf8fd"}
                                    p={4}
                                    h={"28"}
                                    justifyContent={"center"}
                                    cursor="pointer"
                                >
                                    <SlCloudUpload color={"#191D23"} size={30} />
                                    <Text
                                        color={"#191D23"}
                                        fontWeight={"500"}
                                        fontSize={"sm"}
                                        mt={'2'}
                                        mb={0}
                                    >
                                        {directorForm.selectedAadharImage || "Drag and drop files here or Choose file"}
                                    </Text>
                                </VStack>
                                <input
                                    type="file"
                                    id={`aadhar-file-input-${index}`}
                                    style={{ display: 'none' }}
                                    onChange={(e) => handleFileUpload(index, 'selectedAadharImage', e)}
                                />
                            </Box>
                            {directorFormErrors[index]?.selectedAadharImage && (
                                <Text color="red.500" fontSize="xs">{directorFormErrors[index].selectedAadharImage}</Text>
                            )}
                        </Box>
                    </Box>
                </Box>
            ))}

            <Box>
                <Text
                    color={'#6311CB'}
                    fontWeight={600}
                    fontSize={'sm'} mt={4}
                    cursor="pointer"
                    onClick={() => handleAddDirector()}
                >
                    + Add director {directorForms.length + 1}
                </Text>
            </Box>

            <Box mt={6}>
                <Text
                    as="button"
                    bg={'#6311CB'}
                    color={"white"}
                    fontWeight={600}
                    fontSize={'sm'}
                    p={2}
                    borderRadius={"md"}
                    onClick={() => handleSubmit()}
                >
                    Submit
                </Text>
            </Box>
        </Box>
    );
};

export default OnboardingDirectorDetails;
