// import React, { useState } from 'react'
// import Grid from '@mui/material/Grid'
// import Card from '@mui/material/Card'
// import Box from '@mui/material/Box'
// import Stack from '@mui/material/Stack'
// import Divider from '@mui/material/Divider'
// import TextField from '@mui/material/TextField'
// import Typography from '@mui/material/Typography'
// import FormControlLabel from '@mui/material/FormControlLabel'
// import Switch from '@mui/material/Switch'
// import Button from '@mui/material/Button'

// const SecurityMeasure = () => {
//   // Security measures state
//   const [securityMeasures, setSecurityMeasures] = useState({
//     securityDescription: '',
//     applyFor3DSecure: false,
//     useCVC: false,
//     applyForAVS: false,
//     mpi6Used: '',
//   })

//   // Handle input changes
//   const handleSecurityChange = (e: React.ChangeEvent<HTMLInputElement>) => {
//     const { name, value, type, checked } = e.target
//     setSecurityMeasures(prev => ({
//       ...prev,
//       [name]: type === 'checkbox' ? checked : value
//     }))
//   }

//   const handleSubmit = (e: React.FormEvent) => {
//     e.preventDefault()
//     const formData = {
//       ...securityMeasures,
//     }
//     console.log('Form submitted:', formData)
//     alert('Form submitted successfully! Check console for data.')
//   }

//   return (
//     <Box sx={{ bgcolor: 'background.default'}}>
//       <Card sx={{ borderRadius: 0, boxShadow: 'none' }}>
//         <form onSubmit={handleSubmit}>
//           <Box sx={{ p: 0 }}>
//             {/* Header */}
//             <Box sx={{ mb: 5 }}>
//               <Typography variant="h5" sx={{ fontWeight: 600, mb: 0.5, color: 'text.primary' }}>
//                 Security Measures
//               </Typography>
//               <Divider sx={{ mb: 4 }} />
//             </Box>

//             <Grid container spacing={3}>
//               {/* Describe ALL security measures */}
//               <Grid item xs={12}>
//                 <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 1 }}>
//                   Describe ALL security measures AND fraud/chargeback handling (in detail)
//                 </Typography>
//                 <TextField
//                   fullWidth
//                   multiline
//                   rows={6}
//                   name="securityDescription"
//                   value={securityMeasures.securityDescription}
//                   onChange={handleSecurityChange}
//                   placeholder="Please describe in detail all security measures implemented and how fraud/chargebacks are handled..."
//                   helperText="Include information about fraud detection systems, chargeback management procedures, customer verification processes, and any other relevant security measures"
//                 />
//               </Grid>

//               {/* 3D Secure */}
//               <Grid item xs={12}>
//                 <FormControlLabel
//                   control={
//                     <Switch
//                       checked={securityMeasures.applyFor3DSecure}
//                       onChange={handleSecurityChange}
//                       name="applyFor3DSecure"
//                     />
//                   }
//                   label="Would you like to apply for 3D Secure (MasterCard SecureCode, VerifiedByVisa)"
//                 />
//                 <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2 }}>
//                   3D Secure adds an extra layer of security for online transactions
//                 </Typography>

//                 {securityMeasures.applyFor3DSecure && (
//                   <Box sx={{ mt: 3, ml: 2 }}>
//                     <TextField
//                       fullWidth
//                       name="mpi6Used"
//                       label="If Yes, what MPI 6 will be used?"
//                       value={securityMeasures.mpi6Used}
//                       onChange={handleSecurityChange}
//                       placeholder="Please specify the MPI 6 provider"
//                       helperText="MPI (Merchant Plugin Interface) is required for 3D Secure integration"
//                     />
//                   </Box>
//                 )}
//               </Grid>

//               {/* CVC */}
//               <Grid item xs={12}>
//                 <FormControlLabel
//                   control={
//                     <Switch
//                       checked={securityMeasures.useCVC}
//                       onChange={handleSecurityChange}
//                       name="useCVC"
//                     />
//                   }
//                   label="Will you use CVC (Card Verification Code; printed on credit card)"
//                 />
//                 <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2 }}>
//                   CVC/CVV verification helps prevent fraudulent transactions
//                 </Typography>
//               </Grid>

//               {/* AVS */}
//               <Grid item xs={12}>
//                 <FormControlLabel
//                   control={
//                     <Switch
//                       checked={securityMeasures.applyForAVS}
//                       onChange={handleSecurityChange}
//                       name="applyForAVS"
//                     />
//                   }
//                   label="Would you like to apply for AVS (Address Verification)"
//                 />
//                 <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2 }}>
//                   AVS verifies the cardholder's billing address to reduce fraud
//                 </Typography>
//               </Grid>
//             </Grid>

//             <Divider sx={{ my: 4 }} />

//             {/* Buttons */}
//             <Stack direction="row" spacing={2} justifyContent="flex-end">
//               <Button
//                 type="button"
//                 variant="outlined"
//                 size="large"
//                 sx={{ textTransform: 'none' }}
//               >
//                 Previous
//               </Button>
//               <Button
//                 type="submit"
//                 variant="contained"
//                 size="large"
//                 sx={{ textTransform: 'none', px: 4 }}
//               >
//                 SUBMIT
//               </Button>
//             </Stack>
//           </Box>
//         </form>
//       </Card>
//     </Box>
//   )
// }

// export default SecurityMeasure


// api integrate ////////
// import React, { useState, useEffect } from 'react'
// import Grid from '@mui/material/Grid'
// import Card from '@mui/material/Card'
// import Box from '@mui/material/Box'
// import Stack from '@mui/material/Stack'
// import Divider from '@mui/material/Divider'
// import TextField from '@mui/material/TextField'
// import Typography from '@mui/material/Typography'
// import FormControlLabel from '@mui/material/FormControlLabel'
// import Switch from '@mui/material/Switch'
// import Button from '@mui/material/Button'
// import CircularProgress from '@mui/material/CircularProgress'
// import Alert from '@mui/material/Alert'
// import Skeleton from '@mui/material/Skeleton'
// import toast, { Toaster } from 'react-hot-toast'

// import axiosInstance from 'src/configs/axios'
// import endpoints from 'src/configs/endpoints'

// interface SecurityMeasureProps {
//   onNext?: () => void
//   onPrevious?: () => void
// }

// interface ValidationErrors {
//   [key: string]: string
// }

// interface SecurityMeasureType {
//   application_id: string
//   apply_for_3d_secure: boolean
//   describe_details: string
//   card_verification_code: boolean
//   apply_for_avs: boolean
//   mpi_used: string
// }

// const SecurityMeasure = ({ onNext, onPrevious }: SecurityMeasureProps) => {
//   const [loading, setLoading] = useState<boolean>(false)
//   const [fetchingData, setFetchingData] = useState<boolean>(true)
//   const [error, setError] = useState<string | null>(null)
//   const [isEditMode, setIsEditMode] = useState<boolean>(false)

//   // Static Application ID
//   const STATIC_APPLICATION_ID = 64100818

//   // Security measures state
//   const [securityMeasures, setSecurityMeasures] = useState<SecurityMeasureType>({
//     application_id: String(STATIC_APPLICATION_ID),
//     apply_for_3d_secure: false,
//     describe_details: '',
//     card_verification_code: false,
//     apply_for_avs: false,
//     mpi_used: '',
//   })

//   // Validation errors
//   const [errors, setErrors] = useState<ValidationErrors>({})

//   // Fetch existing security measure data
//   useEffect(() => {
//     fetchSecurityMeasureData()
//   }, [])

//   const fetchSecurityMeasureData = async () => {
//     setFetchingData(true)
//     setError(null)

//     try {
//       const response = await axiosInstance.get(
//         `${endpoints.merchantApplication.getApplicationDetails}${STATIC_APPLICATION_ID}`
//       )

//       console.log('GET Security Measure Response:', response.data)

//       // Check if response has securityMeasure data
//       if (response.data && response.data.securityMeasure) {
//         const formData = response.data.securityMeasure
//         console.log('Existing record found, prefilling data:', formData)
//         setIsEditMode(true)
//         prefillFormData(formData)
//         // No toast message - data is visibly prefilled
//       } else {
//         console.log('No existing record found, will create new record on submit')
//         setIsEditMode(false)
//         // Reset to default empty state
//         setSecurityMeasures({
//           application_id: String(STATIC_APPLICATION_ID),
//           apply_for_3d_secure: false,
//           describe_details: '',
//           card_verification_code: false,
//           apply_for_avs: false,
//           mpi_used: '',
//         })
//         // No toast message - just show blank form
//       }
//     } catch (err: any) {
//       console.error('Error fetching security measure data:', err)
//       // Only show error for genuine failures (500, network errors, etc.)
//       if (err.response?.status === 404) {
//         console.log('No record found (404), will create new record on submit')
//         setIsEditMode(false)
//         setSecurityMeasures({
//           application_id: String(STATIC_APPLICATION_ID),
//           apply_for_3d_secure: false,
//           describe_details: '',
//           card_verification_code: false,
//           apply_for_avs: false,
//           mpi_used: '',
//         })
//         // No toast message for 404 - just show blank form
//       } else {
//         // Only show error for non-404 errors (500, network errors, etc.)
//         toast.error('Failed to load security measure data. Please try again.')
//       }
//     } finally {
//       setFetchingData(false)
//     }
//   }

//   // Prefill form with existing data
//   const prefillFormData = (data: any) => {
//     console.log('Prefilling security measure data:', data)

//     // Map the response fields to our state
//     setSecurityMeasures({
//       application_id: data.applicationId || data.application_id || String(STATIC_APPLICATION_ID),
//       apply_for_3d_secure: data.applyFor3dSecure || data.apply_for_3d_secure || false,
//       describe_details: data.describeDetails || data.Describe_details || data.describe_details || '',  // Fixed mapping
//       card_verification_code: data.cardVerificationCode || data.card_verification_code || false,
//       apply_for_avs: data.applyForAvs || data.apply_for_avs || false,
//       mpi_used: data.mpiUsed || data.mpi_used || '',
//     })
//   }

//   // Handle input changes
//   const handleSecurityChange = (e: React.ChangeEvent<HTMLInputElement>) => {
//     const { name, value, type, checked } = e.target
//     setSecurityMeasures(prev => ({
//       ...prev,
//       [name]: type === 'checkbox' ? checked : value
//     }))
    
//     if (errors[name]) {
//       setErrors(prev => ({ ...prev, [name]: '' }))
//     }
//   }

//   const buildRequestBody = () => {
//     return {
//       application_id: String(STATIC_APPLICATION_ID),
//       apply_for_3d_secure: securityMeasures.apply_for_3d_secure,
//       Describe_details: securityMeasures.describe_details || '',
//       card_verification_code: securityMeasures.card_verification_code,
//       apply_for_avs: securityMeasures.apply_for_avs,
//       mpi_used: securityMeasures.mpi_used || '',
//     }
//   }

//   const handleSubmit = async (e: React.FormEvent) => {
//     e.preventDefault()

//     setLoading(true)
//     setError(null)

//     const requestBody = buildRequestBody()

//     console.log('Submit Mode:', isEditMode ? 'UPDATE (PUT)' : 'CREATE (POST)')
//     console.log('Request Body:', JSON.stringify(requestBody, null, 2))

//     try {
//       let response

//       if (isEditMode) {
//         // UPDATE existing record using PUT
//         response = await axiosInstance.put(
//           `${endpoints.merchantApplication.securityMeasure}${STATIC_APPLICATION_ID}`,
//           requestBody
//         )
//         console.log('PUT Response:', response.data)
//         toast.success('Security measure updated successfully!')

//         // After successful update, refresh to get the updated data
//         setTimeout(() => {
//           fetchSecurityMeasureData()
//         }, 1000)
//       } else {
//         // CREATE new record using POST
//         response = await axiosInstance.post(
//           endpoints.merchantApplication.securityMeasure,
//           requestBody
//         )
//         console.log('POST Response:', response.data)
//         toast.success('Security measure created successfully!')
//         setIsEditMode(true)

//         // After successful create, refresh to get the created data
//         setTimeout(() => {
//           fetchSecurityMeasureData()
//         }, 1000)
//       }

//       if (response.data) {
//         if (onNext) {
//           setTimeout(() => {
//             onNext()
//           }, 1500)
//         }
//       }
//     } catch (err: any) {
//       console.error('API Error:', err)
//       console.error('Error Response:', err.response?.data)

//       let errorMessage = isEditMode
//         ? 'Failed to update security measure. Please try again.'
//         : 'Failed to create security measure. Please try again.'

//       if (err.response?.data) {
//         if (err.response.data.content) {
//           if (typeof err.response.data.content === 'object') {
//             const errorObj = err.response.data.content
//             const errorMessages = Object.entries(errorObj).map(([key, value]) => {
//               return `${key}: ${value}`
//             }).join(', ')
//             errorMessage = errorMessages
//             toast.error(errorMessages)

//             const fieldErrors: ValidationErrors = {}
//             Object.entries(errorObj).forEach(([key, value]) => {
//               fieldErrors[key] = Array.isArray(value) ? value[0] : String(value)
//             })
//             setErrors(fieldErrors)
//           } else {
//             errorMessage = err.response.data.content
//             toast.error(errorMessage)
//           }
//         } else if (err.response.data.message) {
//           errorMessage = err.response.data.message
//           toast.error(errorMessage)
//         } else {
//           toast.error(errorMessage)
//         }
//       } else {
//         toast.error(errorMessage)
//       }

//       setError(errorMessage)
//     } finally {
//       setLoading(false)
//     }
//   }

//   if (fetchingData) {
//     return (
//       <Box sx={{ p: 6 }}>
//         <Card sx={{ p: 6 }}>
//           <Skeleton variant="text" height={60} />
//           <Skeleton variant="rectangular" height={400} />
//           <Skeleton variant="text" height={60} />
//           <Skeleton variant="rectangular" height={200} />
//         </Card>
//       </Box>
//     )
//   }

//   return (
//     <Box sx={{ bgcolor: 'background.default', minHeight: '100vh' }}>
//       <Toaster position="top-right" />
//       <Card sx={{ borderRadius: 0, boxShadow: 'none' }}>
//         <form onSubmit={handleSubmit}>
//           <Box sx={{ p: { xs: 2, sm: 3, md: 4 } }}>
//             {/* Header */}
//             <Box sx={{ mb: 4 }}>
//               <Typography variant="h4" sx={{ fontWeight: 600, color: 'text.primary', mb: 1 }}>
//                 Security Measures
//               </Typography>
//               <Typography variant="body2" sx={{ color: 'text.secondary' }}>
//                 Application ID: <strong>{STATIC_APPLICATION_ID}</strong>
//                 {isEditMode && (
//                   <span style={{ marginLeft: '8px', color: '#4caf50' }}>
//                     (Editing existing record)
//                   </span>
//                 )}
//                 {!isEditMode && (
//                   <span style={{ marginLeft: '8px', color: '#ff9800' }}>
//                     (Creating new record)
//                   </span>
//                 )}
//               </Typography>
//               <Divider sx={{ mt: 2 }} />
//             </Box>

//             {/* Info Alert */}
//             <Alert severity="info" sx={{ mb: 3 }}>
//               <Typography variant="body2">
//                 {isEditMode 
//                   ? 'You can edit any field. All changes will be updated via PUT request.'
//                   : 'Fill the form to create a new record. You can edit later.'}
//               </Typography>
//             </Alert>

//             {/* Error Alert */}
//             {error && (
//               <Alert severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
//                 {error}
//               </Alert>
//             )}

//             <Grid container spacing={3}>
//               {/* Describe ALL security measures */}
//               <Grid item xs={12}>
//                 <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 1 }}>
//                   Describe ALL security measures AND fraud/chargeback handling (in detail)
//                 </Typography>
//                 <TextField
//                   fullWidth
//                   multiline
//                   rows={6}
//                   name="describe_details"
//                   value={securityMeasures.describe_details}
//                   onChange={handleSecurityChange}
//                   placeholder="Please describe in detail all security measures implemented and how fraud/chargebacks are handled..."
//                   helperText="Include information about fraud detection systems, chargeback management procedures, customer verification processes, and any other relevant security measures"
//                   error={!!errors.describe_details}
//                 />
//               </Grid>

//               {/* 3D Secure */}
//               <Grid item xs={12}>
//                 <FormControlLabel
//                   control={
//                     <Switch
//                       checked={securityMeasures.apply_for_3d_secure}
//                       onChange={handleSecurityChange}
//                       name="apply_for_3d_secure"
//                     />
//                   }
//                   label="Would you like to apply for 3D Secure (MasterCard SecureCode, VerifiedByVisa)"
//                 />
//                 <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2 }}>
//                   3D Secure adds an extra layer of security for online transactions
//                 </Typography>

//                 {securityMeasures.apply_for_3d_secure && (
//                   <Box sx={{ mt: 3, ml: 2 }}>
//                     <TextField
//                       fullWidth
//                       name="mpi_used"
//                       label="If Yes, what MPI 6 will be used?"
//                       value={securityMeasures.mpi_used}
//                       onChange={handleSecurityChange}
//                       placeholder="Please specify the MPI 6 provider"
//                       helperText="MPI (Merchant Plugin Interface) is required for 3D Secure integration"
//                       error={!!errors.mpi_used}
//                     />
//                   </Box>
//                 )}
//               </Grid>

//               {/* CVC */}
//               <Grid item xs={12}>
//                 <FormControlLabel
//                   control={
//                     <Switch
//                       checked={securityMeasures.card_verification_code}
//                       onChange={handleSecurityChange}
//                       name="card_verification_code"
//                     />
//                   }
//                   label="Will you use CVC (Card Verification Code; printed on credit card)"
//                 />
//                 <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2 }}>
//                   CVC/CVV verification helps prevent fraudulent transactions
//                 </Typography>
//               </Grid>

//               {/* AVS */}
//               <Grid item xs={12}>
//                 <FormControlLabel
//                   control={
//                     <Switch
//                       checked={securityMeasures.apply_for_avs}
//                       onChange={handleSecurityChange}
//                       name="apply_for_avs"
//                     />
//                   }
//                   label="Would you like to apply for AVS (Address Verification)"
//                 />
//                 <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2 }}>
//                   AVS verifies the cardholder's billing address to reduce fraud
//                 </Typography>
//               </Grid>
//             </Grid>

//             <Divider sx={{ my: 4 }} />

//             {/* Buttons */}
//             <Stack direction="row" spacing={2} justifyContent="flex-end">
//               <Button
//                 type="button"
//                 variant="outlined"
//                 size="large"
//                 onClick={onPrevious}
//                 sx={{ textTransform: 'none' }}
//                 disabled={loading}
//               >
//                 Previous
//               </Button>
//               <Button
//                 type="submit"
//                 variant="contained"
//                 size="large"
//                 disabled={loading}
//                 sx={{ textTransform: 'none', px: 4 }}
//               >
//                 {loading ? <CircularProgress size={24} color="inherit" /> : (isEditMode ? 'Update' : 'Submit')}
//               </Button>
//             </Stack>
//           </Box>
//         </form>
//       </Card>
//     </Box>
//   )
// }

// export default SecurityMeasure


// application id get from props previous page ///////////////////////
// import React, { useState, useEffect } from 'react'
// import Grid from '@mui/material/Grid'
// import Card from '@mui/material/Card'
// import Box from '@mui/material/Box'
// import Stack from '@mui/material/Stack'
// import Divider from '@mui/material/Divider'
// import TextField from '@mui/material/TextField'
// import Typography from '@mui/material/Typography'
// import FormControlLabel from '@mui/material/FormControlLabel'
// import Switch from '@mui/material/Switch'
// import Button from '@mui/material/Button'
// import CircularProgress from '@mui/material/CircularProgress'
// import Alert from '@mui/material/Alert'
// import Skeleton from '@mui/material/Skeleton'
// import toast, { Toaster } from 'react-hot-toast'

// import axiosInstance from 'src/configs/axios'
// import endpoints from 'src/configs/endpoints'

// interface SecurityMeasureProps {
//   onNext?: () => void
//   onPrevious?: () => void
//   applicationId: string
// }

// interface ValidationErrors {
//   [key: string]: string
// }

// interface SecurityMeasureType {
//   application_id: string
//   apply_for_3d_secure: boolean
//   describe_details: string
//   card_verification_code: boolean
//   apply_for_avs: boolean
//   mpi_used: string
// }

// const SecurityMeasure = ({ onNext, onPrevious, applicationId }: SecurityMeasureProps) => {
//   const [loading, setLoading] = useState<boolean>(false)
//   const [fetchingData, setFetchingData] = useState<boolean>(true)
//   const [error, setError] = useState<string | null>(null)
//   const [isEditMode, setIsEditMode] = useState<boolean>(false)

//   // Security measures state
//   const [securityMeasures, setSecurityMeasures] = useState<SecurityMeasureType>({
//     application_id: applicationId,
//     apply_for_3d_secure: false,
//     describe_details: '',
//     card_verification_code: false,
//     apply_for_avs: false,
//     mpi_used: '',
//   })

//   // Validation errors
//   const [errors, setErrors] = useState<ValidationErrors>({})

//   // Fetch existing security measure data
//   useEffect(() => {
//     if (applicationId) {
//       fetchSecurityMeasureData()
//     }
//   }, [applicationId])

//   const fetchSecurityMeasureData = async () => {
//     if (!applicationId) {
//       console.log('No applicationId provided')
//       setFetchingData(false)
//       return
//     }

//     setFetchingData(true)
//     setError(null)

//     try {
//       const response = await axiosInstance.get(
//         `${endpoints.merchantApplication.getApplicationDetails}${applicationId}`
//       )

//       console.log('GET Security Measure Response:', response.data)

//       // Check if response has securityMeasure data
//       if (response.data && response.data.securityMeasure) {
//         const formData = response.data.securityMeasure
//         console.log('Existing record found, prefilling data:', formData)
//         setIsEditMode(true)
//         prefillFormData(formData)
//         // No toast message - data is visibly prefilled
//       } else {
//         console.log('No existing record found, will create new record on submit')
//         setIsEditMode(false)
//         // Reset to default empty state
//         setSecurityMeasures({
//           application_id: applicationId,
//           apply_for_3d_secure: false,
//           describe_details: '',
//           card_verification_code: false,
//           apply_for_avs: false,
//           mpi_used: '',
//         })
//         // No toast message - just show blank form
//       }
//     } catch (err: any) {
//       console.error('Error fetching security measure data:', err)
//       // Only show error for genuine failures (500, network errors, etc.)
//       if (err.response?.status === 404) {
//         console.log('No record found (404), will create new record on submit')
//         setIsEditMode(false)
//         setSecurityMeasures({
//           application_id: applicationId,
//           apply_for_3d_secure: false,
//           describe_details: '',
//           card_verification_code: false,
//           apply_for_avs: false,
//           mpi_used: '',
//         })
//         // No toast message for 404 - just show blank form
//       } else {
//         // Only show error for non-404 errors (500, network errors, etc.)
//         toast.error('Failed to load security measure data. Please try again.')
//       }
//     } finally {
//       setFetchingData(false)
//     }
//   }

//   // Prefill form with existing data
//   const prefillFormData = (data: any) => {
//     console.log('Prefilling security measure data:', data)

//     // Map the response fields to our state
//     setSecurityMeasures({
//       application_id: data.applicationId || data.application_id || applicationId,
//       apply_for_3d_secure: data.applyFor3dSecure || data.apply_for_3d_secure || false,
//       describe_details: data.describeDetails || data.Describe_details || data.describe_details || '',
//       card_verification_code: data.cardVerificationCode || data.card_verification_code || false,
//       apply_for_avs: data.applyForAvs || data.apply_for_avs || false,
//       mpi_used: data.mpiUsed || data.mpi_used || '',
//     })
//   }

//   // Handle input changes
//   const handleSecurityChange = (e: React.ChangeEvent<HTMLInputElement>) => {
//     const { name, value, type, checked } = e.target
//     setSecurityMeasures(prev => ({
//       ...prev,
//       [name]: type === 'checkbox' ? checked : value
//     }))
    
//     if (errors[name]) {
//       setErrors(prev => ({ ...prev, [name]: '' }))
//     }
//   }

//   const buildRequestBody = () => {
//     return {
//       application_id: applicationId,
//       apply_for_3d_secure: securityMeasures.apply_for_3d_secure,
//       Describe_details: securityMeasures.describe_details || '',
//       card_verification_code: securityMeasures.card_verification_code,
//       apply_for_avs: securityMeasures.apply_for_avs,
//       mpi_used: securityMeasures.mpi_used || '',
//     }
//   }

//   const handleSubmit = async (e: React.FormEvent) => {
//     e.preventDefault()
//     console.log('SUBMIT CALLED');
//     setLoading(true)
//     setError(null)

//     const requestBody = buildRequestBody()

//     console.log('Submit Mode:', isEditMode ? 'UPDATE (PUT)' : 'CREATE (POST)')
//     console.log('Application ID:', applicationId)
//     console.log('Request Body:', JSON.stringify(requestBody, null, 2))

//     try {
//       let response

//       if (isEditMode) {
//         // UPDATE existing record using PUT
//         response = await axiosInstance.put(
//           `${endpoints.merchantApplication.securityMeasure}${applicationId}`,
//           requestBody
//         )
//         console.log('PUT Response:', response.data)
//         toast.success('Security measure updated successfully!')

//         // After successful update, refresh to get the updated data
//         setTimeout(() => {
//           fetchSecurityMeasureData()
//         }, 1000)
//       } else {
//         // CREATE new record using POST
//         response = await axiosInstance.post(
//           endpoints.merchantApplication.securityMeasure,
//           requestBody
//         )
//         console.log('POST Response:', response.data)
//         toast.success('Security measure created successfully!')
//         setIsEditMode(true)

//         // After successful create, refresh to get the created data
//         setTimeout(() => {
//           fetchSecurityMeasureData()
//         }, 1000)
//       }

//       if (response.data) {
//         if (onNext) {
//           setTimeout(() => {
//             onNext()
//           }, 1500)
//         }
//       }
//     } catch (err: any) {
//       console.error('API Error:', err)
//       console.error('Error Response:', err.response?.data)

//       let errorMessage = isEditMode
//         ? 'Failed to update security measure. Please try again.'
//         : 'Failed to create security measure. Please try again.'

//       if (err.response?.data) {
//         if (err.response.data.content) {
//           if (typeof err.response.data.content === 'object') {
//             const errorObj = err.response.data.content
//             const errorMessages = Object.entries(errorObj).map(([key, value]) => {
//               return `${key}: ${value}`
//             }).join(', ')
//             errorMessage = errorMessages
//             toast.error(errorMessages)

//             const fieldErrors: ValidationErrors = {}
//             Object.entries(errorObj).forEach(([key, value]) => {
//               fieldErrors[key] = Array.isArray(value) ? value[0] : String(value)
//             })
//             setErrors(fieldErrors)
//           } else {
//             errorMessage = err.response.data.content
//             toast.error(errorMessage)
//           }
//         } else if (err.response.data.message) {
//           errorMessage = err.response.data.message
//           toast.error(errorMessage)
//         } else {
//           toast.error(errorMessage)
//         }
//       } else {
//         toast.error(errorMessage)
//       }

//       setError(errorMessage)
//     } finally {
//       setLoading(false)
//     }
//   }

//   if (fetchingData) {
//     return (
//       <Box sx={{ p: 6 }}>
//         <Card sx={{ p: 6 }}>
//           <Skeleton variant="text" height={60} />
//           <Skeleton variant="rectangular" height={400} />
//           <Skeleton variant="text" height={60} />
//           <Skeleton variant="rectangular" height={200} />
//         </Card>
//       </Box>
//     )
//   }

//   return (
//     <Box sx={{ bgcolor: 'background.default', minHeight: '100vh' }}>
//       <Card sx={{ borderRadius: 0, boxShadow: 'none' }}>
//         <form onSubmit={handleSubmit}>
//           <Box sx={{ p: { xs: 2, sm: 3, md: 4 } }}>
//             {/* Header */}
//             <Box sx={{ mb: 4 }}>
//               <Typography variant="h4" sx={{ fontWeight: 600, color: 'text.primary', mb: 1 }}>
//                 Security Measures
//               </Typography>
//               <Typography variant="body2" sx={{ color: 'text.secondary' }}>
//                 Application ID: <strong>{applicationId}</strong>
//                 {isEditMode && (
//                   <span style={{ marginLeft: '8px', color: '#4caf50' }}>
//                     (Editing existing record)
//                   </span>
//                 )}
//                 {!isEditMode && (
//                   <span style={{ marginLeft: '8px', color: '#ff9800' }}>
//                     (Creating new record)
//                   </span>
//                 )}
//               </Typography>
//               <Divider sx={{ mt: 2 }} />
//             </Box>

//             {/* Info Alert */}
//             <Alert severity="info" sx={{ mb: 3 }}>
//               <Typography variant="body2">
//                 {isEditMode 
//                   ? 'You can edit any field. All changes will be updated via PUT request.'
//                   : 'Fill the form to create a new record. You can edit later.'}
//               </Typography>
//             </Alert>

//             {/* Error Alert */}
//             {error && (
//               <Alert severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
//                 {error}
//               </Alert>
//             )}

//             <Grid container spacing={3}>
//               {/* Describe ALL security measures */}
//               <Grid item xs={12}>
//                 <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 1 }}>
//                   Describe ALL security measures AND fraud/chargeback handling (in detail)
//                 </Typography>
//                 <TextField
//                   fullWidth
//                   multiline
//                   rows={6}
//                   name="describe_details"
//                   value={securityMeasures.describe_details}
//                   onChange={handleSecurityChange}
//                   placeholder="Please describe in detail all security measures implemented and how fraud/chargebacks are handled..."
//                   helperText="Include information about fraud detection systems, chargeback management procedures, customer verification processes, and any other relevant security measures"
//                   error={!!errors.describe_details}
//                 />
//               </Grid>

//               {/* 3D Secure */}
//               <Grid item xs={12}>
//                 <FormControlLabel
//                   control={
//                     <Switch
//                       checked={securityMeasures.apply_for_3d_secure}
//                       onChange={handleSecurityChange}
//                       name="apply_for_3d_secure"
//                     />
//                   }
//                   label="Would you like to apply for 3D Secure (MasterCard SecureCode, VerifiedByVisa)"
//                 />
//                 <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2 }}>
//                   3D Secure adds an extra layer of security for online transactions
//                 </Typography>

//                 {securityMeasures.apply_for_3d_secure && (
//                   <Box sx={{ mt: 3, ml: 2 }}>
//                     <TextField
//                       fullWidth
//                       name="mpi_used"
//                       label="If Yes, what MPI 6 will be used?"
//                       value={securityMeasures.mpi_used}
//                       onChange={handleSecurityChange}
//                       placeholder="Please specify the MPI 6 provider"
//                       helperText="MPI (Merchant Plugin Interface) is required for 3D Secure integration"
//                       error={!!errors.mpi_used}
//                     />
//                   </Box>
//                 )}
//               </Grid>

//               {/* CVC */}
//               <Grid item xs={12}>
//                 <FormControlLabel
//                   control={
//                     <Switch
//                       checked={securityMeasures.card_verification_code}
//                       onChange={handleSecurityChange}
//                       name="card_verification_code"
//                     />
//                   }
//                   label="Will you use CVC (Card Verification Code; printed on credit card)"
//                 />
//                 <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2 }}>
//                   CVC/CVV verification helps prevent fraudulent transactions
//                 </Typography>
//               </Grid>

//               {/* AVS */}
//               <Grid item xs={12}>
//                 <FormControlLabel
//                   control={
//                     <Switch
//                       checked={securityMeasures.apply_for_avs}
//                       onChange={handleSecurityChange}
//                       name="apply_for_avs"
//                     />
//                   }
//                   label="Would you like to apply for AVS (Address Verification)"
//                 />
//                 <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2 }}>
//                   AVS verifies the cardholder's billing address to reduce fraud
//                 </Typography>
//               </Grid>
//             </Grid>

//             <Divider sx={{ my: 4 }} />

//             {/* Buttons */}
//             <Stack direction="row" spacing={2} justifyContent="flex-end">
//               <Button
//                 type="button"
//                 variant="outlined"
//                 size="large"
//                 onClick={onPrevious}
//                 sx={{ textTransform: 'none' }}
//                 disabled={loading}
//               >
//                 Previous
//               </Button>
//               <Button
//                 type="submit"
//                 variant="contained"
//                 size="large"
//                 disabled={loading}
//                 sx={{ textTransform: 'none', px: 4 }}
//               >
//                 {loading ? <CircularProgress size={24} color="inherit" /> : (isEditMode ? 'Update' : 'Submit')}
//               </Button>
//             </Stack>
//           </Box>
//         </form>
//       </Card>
//     </Box>
//   )
// }

// export default SecurityMeasure


// validation and green tick ///////////////////////////
import React, { useState, useEffect } from 'react'
import Grid from '@mui/material/Grid'
import Card from '@mui/material/Card'
import Box from '@mui/material/Box'
import Stack from '@mui/material/Stack'
import Divider from '@mui/material/Divider'
import TextField from '@mui/material/TextField'
import Typography from '@mui/material/Typography'
import FormControlLabel from '@mui/material/FormControlLabel'
import Switch from '@mui/material/Switch'
import Button from '@mui/material/Button'
import CircularProgress from '@mui/material/CircularProgress'
import Alert from '@mui/material/Alert'
import Skeleton from '@mui/material/Skeleton'
import Chip from '@mui/material/Chip'
import Paper from '@mui/material/Paper'
import toast from 'react-hot-toast'

import axiosInstance from 'src/configs/axios'
import endpoints from 'src/configs/endpoints'

interface SecurityMeasureProps {
  onNext?: () => void
  onPrevious?: () => void
  applicationId: string
}

interface ValidationErrors {
  [key: string]: string
}

interface SecurityMeasureType {
  application_id: string
  apply_for_3d_secure: boolean
  describe_details: string
  card_verification_code: boolean
  apply_for_avs: boolean
  mpi_used: string
}

// ─── Live Validators ──────────────────────────────────────────────────────────

const validateDescribeDetails = (val: string): string => {
  if (!val) return ''
  if (val.trim().length < 10)
    return 'Please provide at least 10 characters of detail. e.g. We use fraud detection systems and chargeback management procedures.'
  if (val.trim().length > 5000)
    return 'Description must not exceed 5000 characters.'
  if (/[<>@#\\]/.test(val))
    return 'Special characters like < > @ # \\ are not allowed.'
  return ''
}

const validateMPIUsed = (val: string): string => {
  if (!val) return ''
  if (val.trim().length < 2)
    return 'MPI provider name must be at least 2 characters. e.g. MasterCard SecureCode'
  if (val.trim().length > 200)
    return 'MPI provider name must not exceed 200 characters.'
  if (/[<>@#\\]/.test(val))
    return 'Special characters like < > @ # \\ are not allowed. e.g. MasterCard SecureCode'
  return ''
}

// ─── Helper: "Not Provided" Chip ─────────────────────────────────────────────────
const NotAddedChip = () => (
  <Chip
    label="Not Provided"
    size="small"
    sx={{
      height: 20,
      fontSize: '0.625rem',
      fontWeight: 500,
      backgroundColor: '#fff3e0',
      color: '#e65100',
      border: '1px solid',
      borderColor: '#ffb74d',
      '& .MuiChip-label': { px: 1, py: 0.25 },
    }}
  />
)

// ─── Helper: Green Tick Chip ──────────────────────────────────────────────────
const GreenTickChip = () => (
  <Chip
    label="✓"
    size="small"
    sx={{
      height: 20,
      minWidth: 20,
      fontSize: '0.75rem',
      fontWeight: 600,
      backgroundColor: '#e8f5e9',
      color: '#2e7d32',
      borderRadius: '50%',
      '& .MuiChip-label': { px: 0.75, display: 'flex', alignItems: 'center', justifyContent: 'center' },
    }}
  />
)

// ─── Helper: Status Chip for Switches ────────────────────────────────────────
const StatusChip = ({ value, isEditMode }: { value: boolean; isEditMode: boolean }) => {
  if (!isEditMode) return null
  return value ? <GreenTickChip /> : <NotAddedChip />
}

// ─── Field Label with status indicator ───────────────────────────────────────
const FieldLabel = ({
  label,
  value,
  isEditMode,
}: {
  label: string
  value: string | null | undefined
  isEditMode: boolean
}) => {
  const filled = value !== null && value !== undefined && String(value).trim() !== ''
  return (
    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5, flexWrap: 'wrap' }}>
      <Typography variant="body2" sx={{ fontWeight: 500, color: 'text.secondary' }}>
        {label}
      </Typography>
      {isEditMode && filled && <GreenTickChip />}
      {isEditMode && !filled && <NotAddedChip />}
    </Box>
  )
}

// ─── SmartTextField ───────────────────────────────────────────────────────────
const SmartTextField = ({
  label,
  name,
  value,
  onChange,
  error,
  helperText,
  placeholder,
  type,
  select,
  children,
  InputLabelProps,
  multiline,
  rows,
  isEditMode,
  disabled,
}: any) => {
  const filled = value !== null && value !== undefined && String(value).trim() !== ''
  return (
    <Box>
      <FieldLabel label={label} value={value} isEditMode={isEditMode} />
      <TextField
        fullWidth
        name={name}
        value={value}
        onChange={onChange}
        error={!!error}
        helperText={helperText}
        placeholder={placeholder}
        type={type}
        select={select}
        InputLabelProps={InputLabelProps}
        multiline={multiline}
        rows={rows}
        disabled={disabled}
        sx={{
          '& .MuiOutlinedInput-root': {
            '& fieldset': { borderColor: isEditMode && filled ? '#A5D6A7' : undefined },
            '&:hover fieldset': { borderColor: isEditMode && filled ? '#66BB6A' : undefined },
          },
        }}
      >
        {children}
      </TextField>
    </Box>
  )
}

// ─── SmartSwitch ──────────────────────────────────────────────────────────────
const SmartSwitch = ({
  label,
  checked,
  onChange,
  name,
  isEditMode,
  helperText,
}: {
  label: string
  checked: boolean
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void
  name: string
  isEditMode: boolean
  helperText?: string
}) => {
  return (
    <Box>
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, flexWrap: 'wrap' }}>
        <FormControlLabel
          control={
            <Switch
              checked={checked}
              onChange={onChange}
              name={name}
              color="primary"
            />
          }
          label={label}
        />
        <StatusChip value={checked} isEditMode={isEditMode} />
      </Box>
      {helperText && (
        <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2 }}>
          {helperText}
        </Typography>
      )}
    </Box>
  )
}

// ─── Main Component ───────────────────────────────────────────────────────────
const SecurityMeasure = ({ onNext, onPrevious, applicationId }: SecurityMeasureProps) => {
  const [loading, setLoading] = useState<boolean>(false)
  const [fetchingData, setFetchingData] = useState<boolean>(true)
  const [error, setError] = useState<string | null>(null)
  const [isEditMode, setIsEditMode] = useState<boolean>(false)

  // Security measures state
  const [securityMeasures, setSecurityMeasures] = useState<SecurityMeasureType>({
    application_id: applicationId,
    apply_for_3d_secure: false,
    describe_details: '',
    card_verification_code: false,
    apply_for_avs: false,
    mpi_used: '',
  })

  // Validation errors
  const [errors, setErrors] = useState<ValidationErrors>({})

  // ─── Live validation router ───────────────────────────────────────────────
  const runLiveValidation = (field: string, value: string): string => {
    switch (field) {
      case 'describe_details':
        return validateDescribeDetails(value)
      case 'mpi_used':
        return validateMPIUsed(value)
      default:
        return ''
    }
  }

  // ─── Helper to check if any error exists ────────────────────────────────
  const hasAnyError = Object.values(errors).some(msg => msg !== '')

  // Fetch existing security measure data
  useEffect(() => {
    if (applicationId) {
      fetchSecurityMeasureData()
    }
  }, [applicationId])

  const fetchSecurityMeasureData = async () => {
    if (!applicationId) {
      setFetchingData(false)
      return
    }

    setFetchingData(true)
    setError(null)

    try {
      const response = await axiosInstance.get(
        `${endpoints.merchantApplication.getApplicationDetails}${applicationId}`
      )

      if (response.data && response.data.securityMeasure) {
        const formData = response.data.securityMeasure
        setIsEditMode(true)
        prefillFormData(formData)
      } else {
        setIsEditMode(false)
        setSecurityMeasures({
          application_id: applicationId,
          apply_for_3d_secure: false,
          describe_details: '',
          card_verification_code: false,
          apply_for_avs: false,
          mpi_used: '',
        })
      }
    } catch (err: any) {
      console.error('Error fetching security measure data:', err)
      if (err.response?.status === 404) {
        setIsEditMode(false)
        setSecurityMeasures({
          application_id: applicationId,
          apply_for_3d_secure: false,
          describe_details: '',
          card_verification_code: false,
          apply_for_avs: false,
          mpi_used: '',
        })
      } else {
        toast.error('Failed to load security measure data. Please try again.')
      }
    } finally {
      setFetchingData(false)
    }
  }

  // Prefill form with existing data
  const prefillFormData = (data: any) => {
    setSecurityMeasures({
      application_id: data.applicationId || data.application_id || applicationId,
      apply_for_3d_secure: data.applyFor3dSecure || data.apply_for_3d_secure || false,
      describe_details: data.describeDetails || data.Describe_details || data.describe_details || '',
      card_verification_code: data.cardVerificationCode || data.card_verification_code || false,
      apply_for_avs: data.applyForAvs || data.apply_for_avs || false,
      mpi_used: data.mpiUsed || data.mpi_used || '',
    })
  }

  // Handle input changes
  const handleSecurityChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type, checked } = e.target
    const newVal = type === 'checkbox' ? checked : value
    
    setSecurityMeasures(prev => ({
      ...prev,
      [name]: newVal
    }))
    
    // Run live validation for text fields
    if (type !== 'checkbox') {
      const errorMsg = runLiveValidation(name, value)
      setErrors(prev => ({ ...prev, [name]: errorMsg }))
    } else {
      // Clear errors for switch fields
      if (errors[name]) {
        setErrors(prev => ({ ...prev, [name]: '' }))
      }
    }
  }

  const buildRequestBody = () => {
    return {
      application_id: applicationId,
      apply_for_3d_secure: securityMeasures.apply_for_3d_secure,
      Describe_details: securityMeasures.describe_details || '',
      card_verification_code: securityMeasures.card_verification_code,
      apply_for_avs: securityMeasures.apply_for_avs,
      mpi_used: securityMeasures.mpi_used || '',
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    // Check for validation errors
    if (hasAnyError) {
      toast.error('Please fix the validation errors before submitting.')
      return
    }

    setLoading(true)
    setError(null)

    const requestBody = buildRequestBody()

    try {
      let response

      if (isEditMode) {
        response = await axiosInstance.put(
          `${endpoints.merchantApplication.securityMeasure}${applicationId}`,
          requestBody
        )
        toast.success('Security measure updated successfully!')

        setTimeout(() => {
          fetchSecurityMeasureData()
        }, 1000)
      } else {
        response = await axiosInstance.post(
          endpoints.merchantApplication.securityMeasure,
          requestBody
        )
        toast.success('Security measure created successfully!')
        setIsEditMode(true)

        setTimeout(() => {
          fetchSecurityMeasureData()
        }, 1000)
      }

      if (response.data) {
        if (onNext) {
          setTimeout(() => {
            onNext()
          }, 1500)
        }
      }
    } catch (err: any) {
      console.error('API Error:', err)

      let errorMessage = isEditMode
        ? 'Failed to update security measure. Please try again.'
        : 'Failed to create security measure. Please try again.'

      if (err.response?.data) {
        if (err.response.data.content) {
          if (typeof err.response.data.content === 'object') {
            const errorObj = err.response.data.content
            const errorMessages = Object.entries(errorObj).map(([key, value]) => {
              return `${key}: ${value}`
            }).join(', ')
            errorMessage = errorMessages
            toast.error(errorMessages)
          } else {
            errorMessage = err.response.data.content
            toast.error(errorMessage)
          }
        } else if (err.response.data.message) {
          errorMessage = err.response.data.message
          toast.error(errorMessage)
        } else {
          toast.error(errorMessage)
        }
      } else {
        toast.error(errorMessage)
      }

      setError(errorMessage)
    } finally {
      setLoading(false)
    }
  }

  // ─── Section header ───────────────────────────────────────────────────────
  const SectionHeader = ({ color, title }: { color: string; title: string }) => (
    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 3 }}>
      <Box sx={{ width: 4, height: 24, bgcolor: color, borderRadius: 2 }} />
      <Typography variant="h6" sx={{ fontWeight: 600, color: 'text.primary' }}>{title}</Typography>
    </Box>
  )

  if (fetchingData) {
    return (
      <Box sx={{ p: 6 }}>
        <Card sx={{ p: 6 }}>
          <Skeleton variant="text" height={60} />
          <Skeleton variant="rectangular" height={400} />
          <Skeleton variant="text" height={60} />
          <Skeleton variant="rectangular" height={200} />
        </Card>
      </Box>
    )
  }

  return (
    <Box sx={{ bgcolor: 'background.default', minHeight: '100vh' }}>
      <Card sx={{ borderRadius: 0, boxShadow: 'none' }}>
        <form onSubmit={handleSubmit}>
          <Box sx={{ p: { xs: 2, sm: 3, md: 4 } }}>

            {/* Header */}
            <Box sx={{ mb: 4 }}>
              <Typography variant="h4" sx={{ fontWeight: 600, color: 'text.primary', mb: 1 }}>
                Security Measures
              </Typography>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, flexWrap: 'wrap' }}>
                <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                  Application ID: <strong>{applicationId}</strong>
                </Typography>
                <Chip
                  label={isEditMode ? 'Editing Existing Record' : 'Creating New Record'}
                  size="small"
                  sx={{
                    backgroundColor: isEditMode ? '#e8f5e9' : '#fff3e0',
                    color: isEditMode ? '#2e7d32' : '#e65100',
                    fontWeight: 500,
                  }}
                />
              </Box>
              <Divider sx={{ mt: 2 }} />
            </Box>

            {/* Info Alert */}
            <Alert severity="info" sx={{ mb: 3 }}>
              <Typography variant="body2">
                {isEditMode
                  ? 'You can edit any field. Green ✓ indicates enabled/filled fields, orange "Not Provided" indicates disabled/missing information.'
                  : 'Fill the form to create a new record.'}
              </Typography>
            </Alert>

            {/* Validation error banner */}
            {/* {hasAnyError && (
              <Alert severity="warning" sx={{ mb: 3 }}>
                Some fields have invalid values. Please review and correct them before saving.
              </Alert>
            )}

            {error && (
              <Alert severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
                {error}
              </Alert>
            )} */}

            {/* Security Measures Section */}
            <Paper elevation={0} sx={{ mb: 4, p: 3, bgcolor: 'background.paper', borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
              <SectionHeader color="primary.main" title="Security Measures Configuration" />

              <Grid container spacing={3}>
                {/* Describe ALL security measures */}
                <Grid item xs={12}>
                  <SmartTextField
                    label="Describe ALL security measures AND fraud/chargeback handling"
                    name="describe_details"
                    value={securityMeasures.describe_details}
                    onChange={handleSecurityChange}
                    error={errors.describe_details}
                    helperText={errors.describe_details || 'Include information about fraud detection systems, chargeback management procedures, customer verification processes, and any other relevant security measures'}
                    placeholder="Please describe in detail all security measures implemented and how fraud/chargebacks are handled..."
                    multiline
                    rows={6}
                    isEditMode={isEditMode}
                  />
                </Grid>

                {/* 3D Secure */}
                <Grid item xs={12}>
                  <Box sx={{ p: 2, bgcolor: '#f5f5f5', borderRadius: 1 }}>
                    <SmartSwitch
                      label="Would you like to apply for 3D Secure (MasterCard SecureCode, VerifiedByVisa)"
                      checked={securityMeasures.apply_for_3d_secure}
                      onChange={handleSecurityChange}
                      name="apply_for_3d_secure"
                      isEditMode={isEditMode}
                      helperText="3D Secure adds an extra layer of security for online transactions"
                    />

                    {securityMeasures.apply_for_3d_secure && (
                      <Box sx={{ mt: 3, ml: 2 }}>
                        <SmartTextField
                          label="MPI (Merchant Plugin Interface) Provider"
                          name="mpi_used"
                          value={securityMeasures.mpi_used}
                          onChange={handleSecurityChange}
                          error={errors.mpi_used}
                          helperText={errors.mpi_used || 'MPI is required for 3D Secure integration'}
                          placeholder="Please specify the MPI provider (e.g., MasterCard SecureCode)"
                          isEditMode={isEditMode}
                        />
                      </Box>
                    )}
                  </Box>
                </Grid>

                {/* CVC */}
                <Grid item xs={12}>
                  <Box sx={{ p: 2, bgcolor: '#f5f5f5', borderRadius: 1 }}>
                    <SmartSwitch
                      label="Will you use CVC (Card Verification Code; printed on credit card)"
                      checked={securityMeasures.card_verification_code}
                      onChange={handleSecurityChange}
                      name="card_verification_code"
                      isEditMode={isEditMode}
                      helperText="CVC/CVV verification helps prevent fraudulent transactions"
                    />
                  </Box>
                </Grid>

                {/* AVS */}
                <Grid item xs={12}>
                  <Box sx={{ p: 2, bgcolor: '#f5f5f5', borderRadius: 1 }}>
                    <SmartSwitch
                      label="Would you like to apply for AVS (Address Verification)"
                      checked={securityMeasures.apply_for_avs}
                      onChange={handleSecurityChange}
                      name="apply_for_avs"
                      isEditMode={isEditMode}
                      helperText="AVS verifies the cardholder's billing address to reduce fraud"
                    />
                  </Box>
                </Grid>
              </Grid>
            </Paper>

            <Divider sx={{ my: 3 }} />

            {/* Buttons */}
            <Stack direction="row" spacing={2} justifyContent="flex-end">
              <Button
                type="button"
                variant="outlined"
                size="large"
                onClick={onPrevious}
                sx={{ textTransform: 'none' }}
                disabled={loading}
              >
                Previous
              </Button>
              <Button
                type="submit"
                variant="contained"
                size="large"
                disabled={loading || hasAnyError}
                sx={{
                  py: 1.5,
                  px: 4,
                  borderRadius: 2,
                  textTransform: 'none',
                  fontSize: '1rem',
                  fontWeight: 600,
                  boxShadow: 2,
                  '&:hover': { boxShadow: 4 },
                }}
              >
                {loading ? <CircularProgress size={24} color="inherit" /> : (isEditMode ? 'Update' : 'Submit')}
              </Button>
            </Stack>

          </Box>
        </form>
      </Card>
    </Box>
  )
}

export default SecurityMeasure