// src/app/account/page.tsx
"use client";

import React, { useState, useEffect } from "react";
import { Formik, Form, Field } from "formik";
import * as Yup from "yup";
import { useSelector, useDispatch } from "react-redux";
import { RootState, AppDispatch } from "@/redux/store";
import { fetchConnectionStatus } from "@/features/autoDm/autoDmThunk";
import { useConnectionStatus } from "@/hooks/useConnectionStatus";
import { useToast } from "@/components/ui/ToastContext";
import { logger } from "@/lib/logger";
// import { TrackingIdManager } from "@/components/TrackingIdManager";
import { AddTrackingIdModal } from "@/components/AddTrackingIdModal";
import { useTrackingIds } from "@/hooks/useTrackingIds";
import apiClient from "@/lib/apiClient";
import { PlatformDetailsResponse, PlatformsListResponse, PlatformBasic, SavePlatformDataRequest, SavePlatformDataResponse, SavePlatformData } from "@/types/platform";
import { useRouter } from "next/navigation";
import { X, Trash2 } from "react-feather";

interface AccountValues {
    firstName: string;
    lastName: string;
    email: string;
    phone: string;
    platforms: { [key: string]: string }; // Dynamic platform URLs
    instagramUsername: string;
    trackingIds?: {
        [platformName: string]: string[];
    };
}

// Dynamic validation schema based on platforms
const createValidationSchema = (platforms: PlatformBasic[]) => {
    const platformValidations: Record<string, Yup.StringSchema> = {};

    platforms.forEach(platform => {
        if (platform.is_active) {
            // Make platform URLs optional - users can update just specific platforms
            platformValidations[`platforms.${platform.name.toLowerCase()}`] = Yup.string()
                .url("Please enter a valid URL")
                .optional(); // Make it optional instead of required
        }
    });

    return Yup.object({
        firstName: Yup.string().required("First name is required"),
        lastName: Yup.string().required("Last name is required"),
        email: Yup.string().email("Invalid email format").required("Email is required"),
        phone: Yup.string()
            .matches(/^(\+?\d{1,3}[- ]?)?\d{10}$/, "Please enter a valid phone number")
            .required("Phone number is required"),
        platforms: Yup.object().shape(platformValidations),
        instagramUsername: Yup.string().required("Instagram username is required"),
    });
};

// Default initial values to prevent controlled/uncontrolled switching
const getDefaultInitialValues = (): AccountValues => ({
    firstName: "",
    lastName: "",
    email: "",
    phone: "",
    platforms: {},
    instagramUsername: "",
    trackingIds: {}
});

export default function AccountPage() {
    const toast = useToast();
    const dispatch = useDispatch<AppDispatch>();
    
    // Ensure connection status is fetched consistently across all pages
    useConnectionStatus();

    // Get data from Redux store
    const { loading: autoDmLoading } = useSelector((state: RootState) => state.autoDm);

    // Always start with default values, never null
    const [initialValues, setInitialValues] = useState<AccountValues>(getDefaultInitialValues());
    // const [formKey, setFormKey] = useState(0);
    const [isLoading, setIsLoading] = useState(true);
    const [platforms, setPlatforms] = useState<PlatformBasic[]>([]);
    const [validationSchema, setValidationSchema] = useState(createValidationSchema([]));
    const [platformDetailsLoaded, setPlatformDetailsLoaded] = useState(false);

    // Modal state
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [currentPlatform, setCurrentPlatform] = useState<string>('');

    // Delete account modal state
    const [showDeleteConfirmation, setShowDeleteConfirmation] = useState(false);
    const [isDeleting, setIsDeleting] = useState(false);

    // Initialize tracking IDs with empty object to prevent undefined values
    const { trackingIds, addTrackingId, setTrackingIdsForPlatform } = useTrackingIds({});

    // Router for navigation
    const router = useRouter();

    // Fetch connection status and partner details from Redux
    useEffect(() => {
        setIsLoading(true);
        dispatch(fetchConnectionStatus())
            .unwrap()
            .then((result: { connected: boolean; username?: string; partnerDetails?: Record<string, unknown> }) => {
                if (result.partnerDetails) {
                    // Initialize form values from Redux store
                    setInitialValues({
                        firstName: String(result.partnerDetails.first_name || ""),
                        lastName: String(result.partnerDetails.last_name || ""),
                        email: String(result.partnerDetails.email || ""),
                        phone: `${String(result.partnerDetails.countryCode || "")} ${String(result.partnerDetails.phone || "")}`.trim(),
                        platforms: {},
                        instagramUsername: result.username || "",
                        trackingIds: {}
                    });
                } else {
                    // Use default values if no partner details
                    setInitialValues(getDefaultInitialValues());
                }
                setIsLoading(false);
            })
            .catch((err: unknown) => {
                logger.error("Failed to load account data:", err);
                // Use default values if Redux call fails
                setInitialValues(getDefaultInitialValues());
                setIsLoading(false);
                toast("Failed to load account data. Please refresh the page.");
            });
    }, [dispatch, toast]);

    // Fetch active platforms first
    useEffect(() => {
        apiClient.get<PlatformsListResponse>("/accounts/platforms")
            .then((response) => {
                if (response.data?.success) {
                    const activePlatforms = (response.data.data?.platforms || []).filter(p => p?.is_active && p?.id);
                    setPlatforms(activePlatforms);

                    // Update validation schema with active platforms
                    setValidationSchema(createValidationSchema(activePlatforms));

                    // Initialize platform URLs with empty strings (never undefined)
                    const platformUrls: { [key: string]: string } = {};
                    activePlatforms.forEach(platform => {
                        if (platform?.name) {
                            platformUrls[platform.name.toLowerCase()] = "";
                        }
                    });

                    // Update initial values with empty platform URLs
                    setInitialValues(prev => ({
                        ...prev,
                        platforms: platformUrls
                    }));
                }
            })
            .catch((error) => {
                logger.error("Failed to load platforms:", error);
                toast("Failed to load platforms");
            });
    }, []);

    // Fetch platform details (URLs and tracking IDs) if available - only once after platforms are loaded
    useEffect(() => {
        if (platforms.length > 0 && !platformDetailsLoaded) {
            // Only fetch details if we have platforms and details haven't been loaded yet
            apiClient.get<PlatformDetailsResponse>("/accounts/platform-details")
                .then((response) => {
                    if (response.data?.success) {
                        const platformData = response.data.data?.platforms || [];
                        logger.log("Platform data:", platformData);
                        // Update platform URLs and tracking IDs from details
                        const platformUrls: { [key: string]: string } = { ...initialValues.platforms };
                        const platformTrackingIds: { [key: string]: string[] } = {};

                        platformData.forEach(platform => {
                            const platformName = platform?.name?.toLowerCase();
                            logger.log("Platform name:", platformName);
                            if (platformName && platformUrls.hasOwnProperty(platformName)) {
                                platformUrls[platformName] = (platform.store_front_url || ""); // Always use empty string, never undefined
                                logger.log("Platform URL:", platformUrls[platformName]);
                                platformTrackingIds[platformName] = (platform.tracking_ids || []).map(tid => tid?.tracking_id || "");
                            }
                        });

                        // Update initial values with platform data
                        setInitialValues(prev => ({
                            ...prev,
                            platforms: platformUrls,
                            trackingIds: platformTrackingIds
                        }));
                        logger.log("Initial values:", initialValues, "Platform tracking IDs:", platformTrackingIds, "Platform URLs:", platformUrls);
                        // Initialize tracking IDs state - ensure platformTrackingIds is always an object
                        if (Object.keys(platformTrackingIds).length > 0) {
                            Object.entries(platformTrackingIds).forEach(([platform, ids]) => {
                                setTrackingIdsForPlatform(platform, ids);
                            });
                        }

                        setPlatformDetailsLoaded(true); // Mark details as loaded
                    }
                })
                .catch((error) => {
                    logger.error("Failed to load platform details:", error);
                    // Don't show error toast as this is optional data
                    setPlatformDetailsLoaded(true); // Mark as loaded even on error to prevent retries
                });
        }
    }, [platforms.length, platformDetailsLoaded, setTrackingIdsForPlatform]); // Include setTrackingIdsForPlatform in dependencies

    // const handleAddTrackingId = (platform: string) => {
    //     setCurrentPlatform(platform);
    //     setIsModalOpen(true);
    // };

    const handleSaveTrackingId = (trackingId: string) => {
        addTrackingId(currentPlatform, trackingId);
    };

    const handleCloseModal = () => {
        setIsModalOpen(false);
        setCurrentPlatform('');
    };

    // Delete account functions
    const handleDeleteAccount = () => {
        setShowDeleteConfirmation(true);
    };

    const closeDeleteConfirmation = () => {
        setShowDeleteConfirmation(false);
    };

    const confirmDeleteAccount = async () => {
        setIsDeleting(true);
        try {
            const response = await apiClient.delete('/partner/account');

            if (response.data.success) {
                toast(response.data.message || "Account deleted successfully");
                // Clear all local storage and session storage
                localStorage.clear();
                sessionStorage.clear();
                // Logout user and redirect to contact page
                router.push('/contact');
            } else {
                toast("Failed to delete account. Please try again.");
            }
        } catch (error) {
            logger.error("Failed to delete account:", error);
            toast("Failed to delete account. Please try again.");
        } finally {
            setIsDeleting(false);
            setShowDeleteConfirmation(false);
        }
    };

    // Check if URLs are valid to show tracking ID sections
    // const shouldShowTrackingIds = (url: string | undefined): boolean => {
    // const shouldShowTrackingIds = (): boolean => {
    //     // Show tracking ID section for all platforms initially, regardless of URL
    //     // This allows users to add tracking IDs even before they add platform URLs
    //     return true;
    // };

    if (isLoading || autoDmLoading) {
        return (
            <div className="text-center py-20">
                <div className="spinner-border" role="status">
                    <span className="visually-hidden">Loading...</span>
                </div>
                <p className="mt-3">Loading account...</p>
            </div>
        );
    }

    // Remove the null check since initialValues will always have values
    return (
        <div className="pcoded-main-container bg-light webContent">
            <div className="pcoded-content">
                <Formik
                    // key={formKey}
                    initialValues={initialValues}
                    enableReinitialize
                    validationSchema={validationSchema}
                    onSubmit={async (values, { setSubmitting }) => {
                        try {
                            // Prepare platform data for API - only include platforms with data
                            const platformData: SavePlatformData[] = platforms
                                .map(platform => {
                                    const platformName = platform?.name?.toLowerCase() || 'unknown';
                                    const platformUrls = values.platforms || {};
                                    const platformTrackingIds = trackingIds[platformName] || [];
                                    const storeFrontUrl = platformUrls[platformName] || "";

                                    // Only include platforms that have a URL or tracking IDs
                                    if (!storeFrontUrl.trim() && platformTrackingIds.length === 0) {
                                        return null; // Skip platforms with no data
                                    }

                                    return {
                                        platform_id: platform?.id || 0,
                                        store_front_url: storeFrontUrl,
                                        tracking_ids: platformTrackingIds
                                            .map((trackingId) => {
                                                // For now, we'll treat all tracking IDs as new since we don't have ID mapping
                                                // In a real implementation, you'd need to maintain ID mapping between UI state and API data
                                                return {
                                                    tracking_id: trackingId,
                                                    is_active: true
                                                };
                                            })
                                            .filter(tid => tid.tracking_id.trim() !== '') // Remove empty tracking IDs
                                    };
                                })
                                .filter((platform): platform is SavePlatformData => platform !== null); // Type-safe filter

                            const requestBody: SavePlatformDataRequest = {
                                platforms: platformData
                            };

                            logger.log("Request body:", requestBody);
                            // Only proceed if there are platforms to save
                            if (platformData.length === 0) {
                                toast("No platform data to save");
                                return;
                            }

                            // Call the save API
                            const response = await apiClient.post<SavePlatformDataResponse>("/accounts/save-platform-data", requestBody);

                            if (response.data?.success) {
                                toast("Platform data saved successfully");

                                // Reload the data after successful save
                                try {
                                    // Reload platform details to get updated data
                                    const detailsResponse = await apiClient.get<PlatformDetailsResponse>("/accounts/platform-details");
                                    if (detailsResponse.data?.success) {
                                        const platformData = detailsResponse.data.data?.platforms || [];

                                        // Update platform URLs and tracking IDs from details
                                        const platformUrls: { [key: string]: string } = { ...values.platforms };
                                        const platformTrackingIds: { [key: string]: string[] } = {};

                                        platformData.forEach(platform => {
                                            const platformName = platform?.name?.toLowerCase();
                                            if (platformName && platformUrls.hasOwnProperty(platformName)) {
                                                platformUrls[platformName] = (platform.store_front_url || "");
                                                platformTrackingIds[platformName] = (platform.tracking_ids || []).map(tid => tid?.tracking_id || "");
                                            }
                                        });

                                        // Update initial values with fresh data
                                        setInitialValues(prev => ({
                                            ...prev,
                                            platforms: platformUrls,
                                            trackingIds: platformTrackingIds
                                        }));

                                        // Reset tracking IDs state with fresh data
                                        if (Object.keys(platformTrackingIds).length > 0) {
                                            Object.entries(platformTrackingIds).forEach(([platform, ids]) => {
                                                setTrackingIdsForPlatform(platform, ids);
                                            });
                                        }

                                        // Reset the platform details loaded flag
                                        setPlatformDetailsLoaded(false);
                                    }
                                } catch (reloadError) {
                                    logger.error("Failed to reload platform data:", reloadError);
                                    // Don't show error toast for reload failure
                                }
                            } else {
                                toast("Failed to save platform data");
                            }
                        } catch (err: unknown) {
                            logger.error("Failed to save platform data:", err);
                            if (err && typeof err === 'object' && 'response' in err && err.response && typeof err.response === 'object' && 'data' in err.response && err.response.data && typeof err.response.data === 'object' && 'message' in err.response.data) {
                                toast(String(err.response.data.message));
                            } else if (err && typeof err === 'object' && 'response' in err && err.response && typeof err.response === 'object' && 'data' in err.response && err.response.data && typeof err.response.data === 'object' && 'error' in err.response.data) {
                                toast(String(err.response.data.error));
                            } else {
                                toast("Something went wrong. Please try again.");
                            }
                        } finally {
                            setSubmitting(false);
                        }
                    }}
                >
                    {/* {({ isSubmitting, errors, touched }) => ( */}
                    {({ values, errors, touched }) => (
                        <Form>
                            {/* Header */}

                            <div className="row align-items-center">
                                <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 mb-md-0 mb-2 text-md-start text-center">
                                    <h3 className="subHeading mb-0">Account</h3>
                                </div>
                                <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 d-flex justify-content-md-end justify-content-center text-md-start text-center">
                                    <div className="d-md-flex justify-content-md-end justify-content-center gap-2 w-100">
                                        {/* Cancel → bump key to remount & reload from API */}
                                        {/* <button
                                                type="button"
                                                className="mb-2 mb-md-0 small-btn btn-second my-btn-100"
                                                onClick={() => {
                                                    setFormKey((k) => k + 1);
                                                    setPlatformDetailsLoaded(false); // Reset flag to allow reloading
                                                }}
                                            >
                                                Cancel
                                            </button> */}
                                        {/* Save → submits Formik */}
                                        {/* <button
                                                type="submit"
                                                className="button btn-first small-btn"
                                                disabled={isSubmitting}
                                            >
                                                {isSubmitting ? "Saving..." : "Save"}
                                            </button> */}
                                    </div>
                                </div>
                            </div>

                            {/* Form Body */}
                            <div className="row mb-3">
                                <div className="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-12">
                                    <div className="platform-cards">
                                        <div className="card bg-white border-0 shadow-sm rounded-3 mb-3 my-3 p-3 p-md-4 pb-2">
                                            <h3 className="thirdHeading mb-3">BASICS</h3>

                                            {/* <div className="alert alert-info mb-3" role="alert">
                                                    <i className="fa fa-info-circle me-2"></i>
                                                    <strong>Note:</strong> The basic information below is loaded from your account profile and cannot be edited. 
                                                    To update your personal information, please contact your account administrator.
                                                </div> */}

                                            <div className="row profile-fields">
                                                <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-12 mb-3">
                                                    <label htmlFor="firstName" className="fw-bolder mb-1">
                                                        First Name <span className="text-danger">*</span>
                                                    </label>
                                                    <Field
                                                        id="firstName"
                                                        type="text"
                                                        name="firstName"
                                                        className="form-control rounded-3"
                                                        placeholder="Enter your first name"
                                                        readOnly
                                                        disabled
                                                        style={{
                                                            backgroundColor: '#f8f9fa',
                                                            cursor: 'not-allowed',
                                                            opacity: 0.7
                                                        }}
                                                    />
                                                </div>
                                                <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-12 mb-3">
                                                    <label htmlFor="lastName" className="fw-bolder mb-1">
                                                        Last Name <span className="text-danger">*</span>
                                                    </label>
                                                    <Field
                                                        id="lastName"
                                                        type="text"
                                                        name="lastName"
                                                        className="form-control rounded-3"
                                                        placeholder="Enter your last name"
                                                        readOnly
                                                        disabled
                                                        style={{
                                                            backgroundColor: '#f8f9fa',
                                                            cursor: 'not-allowed',
                                                            opacity: 0.7
                                                        }}
                                                    />
                                                </div>
                                                <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-12 mb-3">
                                                    <label htmlFor="email" className="fw-bolder mb-1">
                                                        Email ID <span className="text-danger">*</span>
                                                    </label>
                                                    <Field
                                                        id="email"
                                                        type="email"
                                                        name="email"
                                                        className="form-control rounded-3"
                                                        placeholder="Enter your email address"
                                                        readOnly
                                                        disabled
                                                        style={{
                                                            backgroundColor: '#f8f9fa',
                                                            cursor: 'not-allowed',
                                                            opacity: 0.7
                                                        }}
                                                    />
                                                </div>
                                                <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-12 mb-3">
                                                    <label htmlFor="phone" className="fw-bolder mb-1">
                                                        Mobile Number <span className="text-danger">*</span>
                                                    </label>
                                                    <Field
                                                        id="phone"
                                                        type="tel"
                                                        name="phone"
                                                        className="form-control rounded-3"
                                                        placeholder="Enter your phone number"
                                                        maxLength={15}
                                                        readOnly
                                                        disabled
                                                        style={{
                                                            backgroundColor: '#f8f9fa',
                                                            cursor: 'not-allowed',
                                                            opacity: 0.7
                                                        }}
                                                    />
                                                </div>
                                            </div>

                                            {/* <h3 className="thirdHeading mt-3 mb-2">PLATFORMS</h3> */}

                                            {/* Dynamic platform cards */}
                                            {/* {platforms && platforms.length > 0 && platforms.map((platform) => (
                                                    <React.Fragment key={platform?.name || 'unknown'}>
                                                        <div className="platform-card links-ulr-card card px-0 mb-0" style={{border: 'none'}}>
                                                            <div className="card-body d-block d-md-flex justify-content-between align-items-center p-0 w-100">
                                                                <div className="url-logo-area mb-0 w-100">
                                                                    <img
                                                                        src={(platform?.platform_logo || `img/${platform?.name?.toLowerCase() || 'unknown'}.svg`)}
                                                                        alt={`${platform?.name || 'Unknown'} logo`}
                                                                        className="url-logo-input"
                                                                    />
                                                                    <Field
                                                                        type="url"
                                                                        name={`platforms.${platform?.name?.toLowerCase() || 'unknown'}`}
                                                                        className={`form-control platform-form-control platform-input-clr mb-0 w-100 ${
                                                                            errors.platforms && errors.platforms[platform?.name?.toLowerCase() || 'unknown'] && touched.platforms && touched.platforms[platform?.name?.toLowerCase() || 'unknown'] ? 'is-invalid' : ''
                                                                        }`}
                                                                        placeholder={`Enter your ${platform?.name || 'Unknown'} Storefront URL`}
                                                                        style={{border: 'none'}}
                                                                    />
                                                                </div>
                                                            </div>
                                                            <ErrorMessage name={`platforms.${platform?.name?.toLowerCase() || 'unknown'}`} component="div" className="invalid-feedback d-block ms-3" />
                                                        </div>

                                                    
                                                        <TrackingIdManager
                                                            platform={platform?.name?.toLowerCase() || 'unknown'}
                                                            trackingIds={(trackingIds && trackingIds[platform?.name?.toLowerCase() || 'unknown']) || []}
                                                            onAddId={() => handleAddTrackingId(platform?.name?.toLowerCase() || 'unknown')}
                                                            onRemoveId={(index) => removeTrackingId(platform?.name?.toLowerCase() || 'unknown', index)}
                                                            logo={(platform?.platform_logo || `img/${platform?.name?.toLowerCase() || 'unknown'}.svg`)}
                                                            logoAlt={`${platform?.name || 'Unknown'} logo`}
                                                            isVisible={shouldShowTrackingIds()}
                                                        />
                                                    </React.Fragment>
                                                ))} */}

                                            {/* Instagram Username */}
                                            <div className="platform-card links-ulr-card px-0 card mb-0" style={{ border: 'none' }}>
                                                <div className="card-body p-0 w-100">
                                                    <div className="url-logo-area d-flex mb-2 w-100">
                                                        {/* <span className="label-required mb-0">*</span> */}
                                                        <img
                                                            src="img/Instagram.webp"
                                                            alt="Instagram logo"
                                                            className="url-logo-input"
                                                        />
                                                        <Field
                                                            type="text"
                                                            name="instagramUsername"
                                                            className={`form-control platform-form-control mb-0 w-100 ${errors.instagramUsername && touched.instagramUsername ? 'is-invalid' : ''
                                                                }`}
                                                            placeholder={!values.instagramUsername ? "User not connected" : values.instagramUsername}
                                                            readOnly
                                                            required
                                                            style={{
                                                                border: 'none', cursor: 'not-allowed',
                                                            }}
                                                        />
                                                    </div>
                                                    {/* Commented out error message as field is read-only */}
                                                    {/* <ErrorMessage name="instagramUsername" component="div" className="invalid-feedback d-block ms-3" /> */}
                                                    <small className="mb-0 d-block my-text-small">
                                                        To update your Instagram account, reach out to your Brand Manager.
                                                    </small>
                                                </div>
                                            </div>

                                            {/* Delete Account Section */}
                                            <div className="platform-card links-ulr-card px-0 card mb-0 mt-4" style={{ border: 'none' }}>
                                                <div className="card-body p-0 w-100">
                                                    <div className="d-flex justify-content-between align-items-center mb-3">
                                                        <h4 className="text-danger mb-0">Delete Account</h4>
                                                    </div>
                                                    <p className="text-muted mb-3">
                                                        ⚠️ This action cannot be undone. Your account, including all campaigns, settings, and personal data will be permanently removed from our servers.
                                                    </p>
                                                    <button
                                                        type="button"
                                                        className="btn btn-outline-danger"
                                                        style={{
                                                            color: 'var(--bs-body-color)',
                                                            borderColor: '#dc3545'
                                                        }}
                                                        onClick={handleDeleteAccount}
                                                    >
                                                        <Trash2 size={16} className="me-2" />
                                                        Delete Account
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </Form>
                    )}
                </Formik>

                {/* Add Tracking ID Modal */}
                <AddTrackingIdModal
                    isOpen={isModalOpen}
                    onClose={handleCloseModal}
                    onSave={handleSaveTrackingId}
                    platform={currentPlatform || ""}
                    platformName={(currentPlatform && currentPlatform.charAt(0).toUpperCase() + currentPlatform.slice(1)) || ""}
                />

                {/* Delete Account Confirmation Modal */}
                {showDeleteConfirmation && (
                    <>
                        {/* Backdrop */}
                        <div
                            className="modal-backdrop fade show"
                            style={{
                                position: 'fixed',
                                top: 0,
                                left: 0,
                                width: '100vw',
                                height: '100vh',
                                backgroundColor: 'rgba(0, 0, 0, 0.5)',
                                zIndex: 1040,
                                cursor: 'pointer'
                            }}
                            onClick={closeDeleteConfirmation}
                            title="Click outside to close"
                        />

                        {/* Modal */}
                        <section
                            className="modal fade my-modal show d-block"
                            style={{
                                position: 'fixed',
                                top: 0,
                                left: 0,
                                width: '100vw',
                                height: '100vh',
                                zIndex: 1050
                            }}
                            aria-hidden="false"
                            onClick={closeDeleteConfirmation}
                        >
                            <div className="modal-dialog modal-dialog-centered" onClick={(e) => e.stopPropagation()}>
                                <div className="modal-content" onClick={(e) => e.stopPropagation()}>
                                    <div className="modal-body text-center p-4">
                                        <div className="modal-name mb-0 d-flex justify-content-end">
                                            <button
                                                type="button"
                                                className="btn-close"
                                                onClick={closeDeleteConfirmation}
                                                aria-label="Close"
                                            >
                                                <X size={20} />
                                            </button>
                                        </div>

                                        <div className="text-center mb-4">
                                            {/* <div className="bg-danger bg-opacity-10 rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style={{width: '60px', height: '60px'}}>
                                            <Trash2 size={30} className="text-danger" />
                                        </div> */}
                                            <h4 className="modalHeading mb-3">Are you sure you want to delete your account?</h4>
                                            <p className="px-2 mb-0 text-muted">
                                                This action is permanent and cannot be undone.
                                            </p>
                                        </div>

                                        <div className="d-flex gap-3 justify-content-center">
                                            <button
                                                type="button"
                                                className="btn btn-secondary modalCancel px-4"
                                                onClick={closeDeleteConfirmation}
                                                disabled={isDeleting}
                                            >
                                                Cancel
                                            </button>
                                            <button
                                                type="button"
                                                className="btn modalAction px-4"
                                                // style={{
                                                //     color: 'var(--bs-body-color)',
                                                //     borderColor: '#dc3545'
                                                // }}
                                                onClick={confirmDeleteAccount}
                                                disabled={isDeleting}
                                            >
                                                {isDeleting ? (
                                                    <>
                                                        <span className="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
                                                        Deleting...
                                                    </>
                                                ) : (
                                                    'Delete Account'
                                                )}
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </section>
                    </>
                )}
            </div>
        </div>
    );
}