// import { useState } from 'react'

// // ** MUI Imports
// 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 Switch from '@mui/material/Switch'
// import Divider from '@mui/material/Divider'
// import Checkbox from '@mui/material/Checkbox'
// import TextField from '@mui/material/TextField'
// import Typography from '@mui/material/Typography'
// import MenuItem from '@mui/material/MenuItem'
// import FormGroup from '@mui/material/FormGroup'
// import FormControlLabel from '@mui/material/FormControlLabel'

// const BusinessProfile = () => {
//   const [dynamicDescriptor, setDynamicDescriptor] =
//     useState<boolean>(false)

//   const [bankruptcy, setBankruptcy] =
//     useState<boolean>(false)

//   const [creditCardAcceptance, setCreditCardAcceptance] =
//     useState<boolean>(false)

//   const [violation, setViolation] =
//     useState<boolean>(false)

//   const [affiliateProgram, setAffiliateProgram] =
//     useState<boolean>(false)

//   const [saas, setSaas] =
//     useState<boolean>(false)

//   const cardTypes = [
//     'Maestro',
//     'MasterCard',
//     'VPay',
//     'JCB',
//     'Diners',
//     'Cartes Bancaires',
//     'Rupay',
//     'China Union Pay',
//     'American Express',
//     'Visa',
//     'Other'
//   ]

//   return (
//     <Box>
//       <Card
//         sx={{
//           p: 6,
//           borderRadius: 3,
//           boxShadow: 'none',
//           border: theme => `1px solid ${theme.palette.divider}`
//         }}
//       >
//         <Typography
//           variant='h6'
//           sx={{
//             mb: 6,
//             fontWeight: 700
//           }}
//         >
//           Business Profile
//         </Typography>

//         <Grid container spacing={5}>
//           {/* Description */}
//           <Grid item xs={12}>
//             <TextField
//               fullWidth
//               multiline
//               minRows={4}
//               label='Detailed Description of Products/services sold'
//             />
//           </Grid>

//           {/* Length of business */}
//           <Grid item xs={12} md={4}>
//             <TextField
//               fullWidth
//               label='Length of time in business'
//               placeholder='56'
//             />
//           </Grid>

//           <Grid item xs={12} md={4}>
//             <TextField
//               fullWidth
//               label='Year'
//               placeholder='56 years 5 months 9 days'
//             />
//           </Grid>

//           <Grid item xs={12} md={4}>
//             <TextField
//               select
//               fullWidth
//               label='Merchant Category (MCC)'
//               defaultValue=''
//             >
//               <MenuItem value='retail'>Retail</MenuItem>
//               <MenuItem value='technology'>Technology</MenuItem>
//               <MenuItem value='finance'>Finance</MenuItem>
//             </TextField>
//           </Grid>

//           {/* Website */}
//           <Grid item xs={12} md={6}>
//             <TextField
//               fullWidth
//               label='Website(s) (Comma-Separated)'
//               placeholder='https://example.com'
//             />
//           </Grid>

//           <Grid item xs={12} md={6}>
//             <TextField
//               fullWidth
//               label='Beta Site(s)'
//             />
//           </Grid>

//           {/* Descriptor */}
//           <Grid item xs={12} md={6}>
//             <TextField
//               fullWidth
//               inputProps={{ maxLength: 22 }}
//               label='Credit Card Descriptor (Max 22 Char.)'
//             />
//           </Grid>

//           <Grid item xs={12} md={6}>
//             <TextField
//               fullWidth
//               inputProps={{ maxLength: 12 }}
//               label='DBA/City (Max 12 Char.)'
//             />
//           </Grid>

//           {/* Toggles */}
//           <Grid item xs={12}>
//             <Stack spacing={2}>
//               <FormControlLabel
//                 control={
//                   <Switch
//                     checked={dynamicDescriptor}
//                     onChange={e =>
//                       setDynamicDescriptor(
//                         e.target.checked
//                       )
//                     }
//                   />
//                 }
//                 label="Will You use 'Dynamic Descriptor'"
//               />

//               <FormControlLabel
//                 control={
//                   <Switch
//                     checked={bankruptcy}
//                     onChange={e =>
//                       setBankruptcy(
//                         e.target.checked
//                       )
//                     }
//                   />
//                 }
//                 label='Have you filled for bankruptcy before?'
//               />

//               <FormControlLabel
//                 control={
//                   <Switch
//                     checked={creditCardAcceptance}
//                     onChange={e =>
//                       setCreditCardAcceptance(
//                         e.target.checked
//                       )
//                     }
//                   />
//                 }
//                 label='Have you previously Credit Card acceptance?'
//               />

//               <FormControlLabel
//                 control={
//                   <Switch
//                     checked={violation}
//                     onChange={e =>
//                       setViolation(
//                         e.target.checked
//                       )
//                     }
//                   />
//                 }
//                 label='Have you ever flagged or been in violation of any card schema program?'
//               />
//             </Stack>
//           </Grid>

//           <Grid item xs={12}>
//             <Divider />
//           </Grid>

//           {/* Transaction Values */}
//           <Grid item xs={12} md={4}>
//             <TextField
//               fullWidth
//               label='Estimated monthly sales volume'
//               InputProps={{
//                 startAdornment: (
//                   <Typography sx={{ mr: 2 }}>
//                     USD
//                   </Typography>
//                 )
//               }}
//             />
//           </Grid>

//           <Grid item xs={12} md={4}>
//             <TextField
//               fullWidth
//               label='Average transaction value'
//               InputProps={{
//                 startAdornment: (
//                   <Typography sx={{ mr: 2 }}>
//                     USD
//                   </Typography>
//                 )
//               }}
//             />
//           </Grid>

//           <Grid item xs={12} md={4}>
//             <TextField
//               fullWidth
//               label='Highest transaction value'
//               InputProps={{
//                 startAdornment: (
//                   <Typography sx={{ mr: 2 }}>
//                     USD
//                   </Typography>
//                 )
//               }}
//             />
//           </Grid>

//           {/* Payment Frequency */}
//           <Grid item xs={12}>
//             <Typography
//               variant='subtitle1'
//               sx={{
//                 fontWeight: 700,
//                 mb: 3
//               }}
//             >
//               Payment frequency
//             </Typography>

//             <FormGroup row>
//               <FormControlLabel
//                 control={<Checkbox />}
//                 label='One-time payment'
//               />

//               <FormControlLabel
//                 control={<Checkbox />}
//                 label='Recurring payment'
//               />
//             </FormGroup>
//           </Grid>

//           {/* Origin */}
//           <Grid item xs={12}>
//             <Typography
//               variant='subtitle1'
//               sx={{
//                 fontWeight: 700,
//                 mb: 4
//               }}
//             >
//               ORIGIN OF TRANSACTIONS
//             </Typography>
//           </Grid>

//           {[
//             'Domestic (merchant own country)',
//             'Europe',
//             'USA (Oceania)',
//             'Asia',
//             'Rest of world'
//           ].map(item => (
//             <Grid item xs={12} md={4} key={item}>
//               <TextField
//                 fullWidth
//                 label={item}
//                 placeholder='0%'
//               />
//             </Grid>
//           ))}

//           {/* Method */}
//           <Grid item xs={12}>
//             <Typography
//               variant='subtitle1'
//               sx={{
//                 fontWeight: 700,
//                 mb: 4,
//                 mt: 3
//               }}
//             >
//               METHOD OF ACCEPTANCE
//             </Typography>
//           </Grid>

//           {[
//             'E-commerce / M-Commerce',
//             'Card Present (Point-Of-Sale)',
//             'M-Pos (Mobile POS)',
//             'MOTO (Mail-order/Telephone-order)'
//           ].map(item => (
//             <Grid item xs={12} md={6} key={item}>
//               <TextField
//                 fullWidth
//                 label={item}
//                 placeholder='0%'
//               />
//             </Grid>
//           ))}

//           {/* Delivery */}
//           <Grid item xs={12}>
//             <Typography
//               variant='subtitle1'
//               sx={{
//                 fontWeight: 700,
//                 mb: 4,
//                 mt: 3
//               }}
//             >
//               DELIVERY TIME FOR GOODS/SERVICES
//             </Typography>
//           </Grid>

//           {[
//             'Immediately',
//             'Within 4 weeks',
//             'Within 5-14 weeks',
//             'More than 14 weeks'
//           ].map(item => (
//             <Grid item xs={12} md={6} key={item}>
//               <TextField
//                 fullWidth
//                 label={item}
//                 placeholder='0%'
//               />
//             </Grid>
//           ))}

//           {/* Payment Time */}
//           <Grid item xs={12}>
//             <Typography
//               variant='subtitle1'
//               sx={{
//                 fontWeight: 700,
//                 mb: 3,
//                 mt: 3
//               }}
//             >
//               When does payment take place?
//             </Typography>

//             <FormGroup row>
//               <FormControlLabel
//                 control={<Checkbox />}
//                 label='Upon purchase'
//               />

//               <FormControlLabel
//                 control={<Checkbox />}
//                 label='With download'
//               />

//               <FormControlLabel
//                 control={<Checkbox />}
//                 label='On delivery'
//               />

//               <FormControlLabel
//                 control={<Checkbox />}
//                 label='Other'
//               />
//             </FormGroup>
//           </Grid>

//           {/* Card Types */}
//           <Grid item xs={12}>
//             <Typography
//               variant='subtitle1'
//               sx={{
//                 fontWeight: 700,
//                 mb: 3,
//                 mt: 3
//               }}
//             >
//               Card types applying for
//             </Typography>

//             <Grid container spacing={2}>
//               {cardTypes.map(card => (
//                 <Grid item xs={12} md={3} key={card}>
//                   <FormControlLabel
//                     control={<Checkbox />}
//                     label={card}
//                   />
//                 </Grid>
//               ))}
//             </Grid>
//           </Grid>

//           {/* Toggles */}
//           <Grid item xs={12}>
//             <Stack spacing={2} sx={{ mt: 3 }}>
//               <FormControlLabel
//                 control={
//                   <Switch
//                     checked={affiliateProgram}
//                     onChange={e =>
//                       setAffiliateProgram(
//                         e.target.checked
//                       )
//                     }
//                   />
//                 }
//                 label='Do you offer / make use of affiliate programs?'
//               />

//               <FormControlLabel
//                 control={
//                   <Switch
//                     checked={saas}
//                     onChange={e =>
//                       setSaas(
//                         e.target.checked
//                       )
//                     }
//                   />
//                 }
//                 label='Need Software As A Service'
//               />
//             </Stack>
//           </Grid>
//         </Grid>
//       </Card>
//     </Box>
//   )
// }

// export default 


// 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 MenuItem from '@mui/material/MenuItem'
// import FormControlLabel from '@mui/material/FormControlLabel'
// import Checkbox from '@mui/material/Checkbox'
// import Switch from '@mui/material/Switch'
// import Button from '@mui/material/Button'
// import Radio from '@mui/material/Radio'
// import RadioGroup from '@mui/material/RadioGroup'
// import FormControl from '@mui/material/FormControl'
// import FormLabel from '@mui/material/FormLabel'

// const BusinessProfile = () => {
//   // Main business state
//   const [business, setBusiness] = useState({
//     lengthOfTimeYears: '56',
//     lengthOfTimeMonths: '5',
//     lengthOfTimeDays: '9',
//     merchantCategory: '',
//     creditCardDescriptor: '',
//     dbaCity: '',
//     useDynamicDescriptor: false,
//     filedBankruptcy: false,
//     previouslyAcceptedCreditCard: false,
//     violatedCardSchema: false,
//     estimatedMonthlySales: '',
//     averageTransactionValue: '',
//     highestTransactionValue: '',
//     paymentFrequency: 'one-time',
//     affiliatePrograms: false,
//     needSoftwareAsAService: false,
//   })

//   // Website/Beta Site state
//   const [hasBetaSite, setHasBetaSite] = useState(false)
//   const [websites, setWebsites] = useState([{ url: '', userName: '', password: '' }])

//   // Affiliate programs details state
//   const [affiliateDetails, setAffiliateDetails] = useState('')

//   // Software as a service details state
//   const [softwareDetails, setSoftwareDetails] = useState('')

//   // Origin of transactions percentages
//   const [originPercentages, setOriginPercentages] = useState({
//     domestic: 0,
//     europe: 0,
//     usa: 0,
//     asia: 0,
//     restOfWorld: 0,
//   })

//   // Method of acceptance percentages
//   const [acceptancePercentages, setAcceptancePercentages] = useState({
//     ecommerce: 0,
//     cardPresent: 0,
//     mpos: 0,
//     moto: 0,
//   })

//   // Delivery time percentages
//   const [deliveryPercentages, setDeliveryPercentages] = useState({
//     immediately: 0,
//     within4Weeks: 0,
//     within5To14Weeks: 0,
//     moreThan14Weeks: 0,
//   })

//   // Payment time
//   const [paymentTime, setPaymentTime] = useState('upon-purchase')

//   // Card types
//   const [cardTypes, setCardTypes] = useState({
//     maestro: false,
//     mastercard: false,
//     vpay: false,
//     jcb: false,
//     diners: false,
//     cartesBancaires: false,
//     rupay: false,
//     chinaUnionPay: false,
//     americanExpress: false,
//     visa: false,
//     other: false,
//   })

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

//   // Handle origin percentages
//   const handleOriginChange = (field: string, value: string) => {
//     const numValue = parseInt(value) || 0
//     const newPercentages = { ...originPercentages, [field]: Math.min(100, Math.max(0, numValue)) }
//     setOriginPercentages(newPercentages)
//   }

//   // Handle acceptance percentages
//   const handleAcceptanceChange = (field: string, value: string) => {
//     const numValue = parseInt(value) || 0
//     const newPercentages = { ...acceptancePercentages, [field]: Math.min(100, Math.max(0, numValue)) }
//     setAcceptancePercentages(newPercentages)
//   }

//   // Handle delivery percentages
//   const handleDeliveryChange = (field: string, value: string) => {
//     const numValue = parseInt(value) || 0
//     const newPercentages = { ...deliveryPercentages, [field]: Math.min(100, Math.max(0, numValue)) }
//     setDeliveryPercentages(newPercentages)
//   }

//   // Handle website changes
//   const handleWebsiteChange = (index: number, field: string, value: string) => {
//     const newWebsites = [...websites]
//     newWebsites[index] = { ...newWebsites[index], [field]: value }
//     setWebsites(newWebsites)
//   }

//   const addWebsite = () => {
//     setWebsites([...websites, { url: '', userName: '', password: '' }])
//   }

//   const removeWebsite = (index: number) => {
//     const newWebsites = websites.filter((_, i) => i !== index)
//     setWebsites(newWebsites)
//   }

//   const handleSubmit = (e: React.FormEvent) => {
//     e.preventDefault()
//     const formData = {
//       business,
//       hasBetaSite,
//       websites: hasBetaSite ? websites : [],
//       affiliateDetails: business.affiliatePrograms ? affiliateDetails : null,
//       softwareDetails: business.needSoftwareAsAService ? softwareDetails : null,
//       originPercentages,
//       acceptancePercentages,
//       deliveryPercentages,
//       paymentTime,
//       cardTypes,
//     }
//     console.log('Form submitted:', formData)
//     alert('Form submitted successfully! Check console for data.')
//   }

//   // Merchant categories
//   const merchantCategories = [
//     'Restaurants',
//     'Retail',
//     'E-commerce',
//     'Professional Services',
//     'Healthcare',
//     'Education',
//     'Travel & Tourism',
//     'Entertainment',
//     'Manufacturing',
//     'Wholesale',
//     'Other'
//   ]

//   return (
//     <Box sx={{ bgcolor: 'background.default', minHeight: '100vh' }}>
//       <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' }}>
//                 Detailed Description of Products/services sold
//               </Typography>
//               <Divider sx={{ mb: 4 }} />
//             </Box>

//             <Grid container spacing={3}>
//               {/* Length of time in business */}
//               <Grid item xs={12}>
//                 <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
//                   Length of time in business
//                 </Typography>
//                 <Stack direction="row" spacing={2}>
//                   <TextField
//                     fullWidth
//                     name="lengthOfTimeYears"
//                     label="Years"
//                     type="number"
//                     value={business.lengthOfTimeYears}
//                     onChange={handleBusinessChange}
//                     placeholder="Years"
//                   />
//                   <TextField
//                     fullWidth
//                     name="lengthOfTimeMonths"
//                     label="Months"
//                     type="number"
//                     value={business.lengthOfTimeMonths}
//                     onChange={handleBusinessChange}
//                     placeholder="Months"
//                   />
//                   <TextField
//                     fullWidth
//                     name="lengthOfTimeDays"
//                     label="Days"
//                     type="number"
//                     value={business.lengthOfTimeDays}
//                     onChange={handleBusinessChange}
//                     placeholder="Days"
//                   />
//                 </Stack>
//               </Grid>

//               {/* Merchant Category */}
//               <Grid item xs={12} sm={6}>
//                 <TextField
//                   fullWidth
//                   select
//                   name="merchantCategory"
//                   label="Merchant Category (MCC)"
//                   value={business.merchantCategory}
//                   onChange={handleBusinessChange}
//                 >
//                   <MenuItem value="" disabled>Select</MenuItem>
//                   {merchantCategories.map(category => (
//                     <MenuItem key={category} value={category}>{category}</MenuItem>
//                   ))}
//                 </TextField>
//               </Grid>

//               {/* Website(s) with Beta Site Toggle */}
//               <Grid item xs={12}>
//                 <FormControlLabel
//                   control={
//                     <Switch
//                       checked={hasBetaSite}
//                       onChange={(e) => setHasBetaSite(e.target.checked)}
//                     />
//                   }
//                   label="Beta Site(s)"
//                 />
//                 <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2, mb: 2 }}>
//                   Toggle on to add website details
//                 </Typography>

//                 {hasBetaSite && (
//                   <Box sx={{ bgcolor: 'action.hover', borderRadius: 2, p: 3, mt: 2 }}>
//                     <Typography variant="h6" sx={{ fontWeight: 600, mb: 3 }}>
//                       Provide Website Details
//                     </Typography>
//                     {websites.map((website, index) => (
//                       <Box key={index} sx={{ mb: 3, p: 2, border: '1px solid', borderColor: 'divider', borderRadius: 2 }}>
//                         <Stack direction="row" justifyContent="flex-end" spacing={1} sx={{ mb: 2 }}>
//                           {websites.length > 1 && (
//                             <Button size="small" color="error" onClick={() => removeWebsite(index)}>
//                               Remove
//                             </Button>
//                           )}
//                           {index === websites.length - 1 && (
//                             <Button size="small" variant="outlined" onClick={addWebsite}>
//                               Add Website
//                             </Button>
//                           )}
//                         </Stack>
//                         <Grid container spacing={2}>
//                           <Grid item xs={12}>
//                             <TextField
//                               fullWidth
//                               label="URL"
//                               value={website.url}
//                               onChange={(e) => handleWebsiteChange(index, 'url', e.target.value)}
//                               placeholder="https://"
//                             />
//                           </Grid>
//                           <Grid item xs={12} sm={6}>
//                             <TextField
//                               fullWidth
//                               label="User Name"
//                               value={website.userName}
//                               onChange={(e) => handleWebsiteChange(index, 'userName', e.target.value)}
//                             />
//                           </Grid>
//                           <Grid item xs={12} sm={6}>
//                             <TextField
//                               fullWidth
//                               label="Password"
//                               type="password"
//                               value={website.password}
//                               onChange={(e) => handleWebsiteChange(index, 'password', e.target.value)}
//                             />
//                           </Grid>
//                         </Grid>
//                       </Box>
//                     ))}
//                   </Box>
//                 )}
//               </Grid>

//               {/* Credit Card Descriptor */}
//               <Grid item xs={12} sm={6}>
//                 <TextField
//                   fullWidth
//                   name="creditCardDescriptor"
//                   label="Credit Card Descriptor (Max 22 Char.)"
//                   value={business.creditCardDescriptor}
//                   onChange={handleBusinessChange}
//                   inputProps={{ maxLength: 22 }}
//                   helperText={`${business.creditCardDescriptor.length}/22 characters`}
//                 />
//               </Grid>

//               {/* DBA/City */}
//               <Grid item xs={12} sm={6}>
//                 <TextField
//                   fullWidth
//                   name="dbaCity"
//                   label="DBA/City (Max 12 Char.)"
//                   value={business.dbaCity}
//                   onChange={handleBusinessChange}
//                   inputProps={{ maxLength: 12 }}
//                   helperText={`${business.dbaCity.length}/12 characters`}
//                 />
//               </Grid>

//               {/* Dynamic Descriptor */}
//               <Grid item xs={12}>
//                 <FormControlLabel
//                   control={
//                     <Checkbox
//                       checked={business.useDynamicDescriptor}
//                       onChange={handleBusinessChange}
//                       name="useDynamicDescriptor"
//                     />
//                   }
//                   label="Will You use 'Dynamic Descriptor'"
//                 />
//               </Grid>

//               {/* Bankruptcy */}
//               <Grid item xs={12}>
//                 <FormControlLabel
//                   control={
//                     <Checkbox
//                       checked={business.filedBankruptcy}
//                       onChange={handleBusinessChange}
//                       name="filedBankruptcy"
//                     />
//                   }
//                   label="Have you filed for bankruptcy before?"
//                 />
//               </Grid>

//               {/* Previous Credit Card acceptance */}
//               <Grid item xs={12}>
//                 <FormControlLabel
//                   control={
//                     <Checkbox
//                       checked={business.previouslyAcceptedCreditCard}
//                       onChange={handleBusinessChange}
//                       name="previouslyAcceptedCreditCard"
//                     />
//                   }
//                   label="Have you previously Credit Card acceptance?"
//                 />
//               </Grid>

//               {/* Violated card schema */}
//               <Grid item xs={12}>
//                 <FormControlLabel
//                   control={
//                     <Checkbox
//                       checked={business.violatedCardSchema}
//                       onChange={handleBusinessChange}
//                       name="violatedCardSchema"
//                     />
//                   }
//                   label="Have you ever flagged or been in violation of any card schema program(e.g. Excessive Chargebacks,BRAM violation,Account Data Compromise)?"
//                 />
//               </Grid>

//               {/* Estimated monthly sales */}
//               <Grid item xs={12} sm={6}>
//                 <TextField
//                   fullWidth
//                   name="estimatedMonthlySales"
//                   label="Estimated monthly sales volume"
//                   type="number"
//                   value={business.estimatedMonthlySales}
//                   onChange={handleBusinessChange}
//                   InputProps={{ startAdornment: 'USD ' }}
//                 />
//               </Grid>

//               {/* Average transaction value */}
//               <Grid item xs={12} sm={6}>
//                 <TextField
//                   fullWidth
//                   name="averageTransactionValue"
//                   label="Average transaction value"
//                   type="number"
//                   value={business.averageTransactionValue}
//                   onChange={handleBusinessChange}
//                   InputProps={{ startAdornment: 'USD ' }}
//                 />
//               </Grid>

//               {/* Highest transaction value */}
//               <Grid item xs={12} sm={6}>
//                 <TextField
//                   fullWidth
//                   name="highestTransactionValue"
//                   label="Highest transaction value"
//                   type="number"
//                   value={business.highestTransactionValue}
//                   onChange={handleBusinessChange}
//                   InputProps={{ startAdornment: 'USD ' }}
//                 />
//               </Grid>

//               {/* Payment frequency */}
//               <Grid item xs={12}>
//                 <FormControl component="fieldset">
//                   <FormLabel component="legend">Payment frequency</FormLabel>
//                   <RadioGroup
//                     row
//                     name="paymentFrequency"
//                     value={business.paymentFrequency}
//                     onChange={handleBusinessChange}
//                   >
//                     <FormControlLabel value="one-time" control={<Radio />} label="One-time payment" />
//                     <FormControlLabel value="recurring" control={<Radio />} label="Recurring payment" />
//                   </RadioGroup>
//                 </FormControl>
//               </Grid>

//               {/* Origin of Transactions */}
//               <Grid item xs={12}>
//                 <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
//                   ORIGIN OF TRANSACTIONS
//                 </Typography>
//                 <Grid container spacing={3}>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="Domestic (merchant own country)"
//                       type="number"
//                       value={originPercentages.domestic}
//                       onChange={(e) => handleOriginChange('domestic', e.target.value)}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="Europe"
//                       type="number"
//                       value={originPercentages.europe}
//                       onChange={(e) => handleOriginChange('europe', e.target.value)}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="USA (Oceania)"
//                       type="number"
//                       value={originPercentages.usa}
//                       onChange={(e) => handleOriginChange('usa', e.target.value)}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="Asia"
//                       type="number"
//                       value={originPercentages.asia}
//                       onChange={(e) => handleOriginChange('asia', e.target.value)}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="Rest of world"
//                       type="number"
//                       value={originPercentages.restOfWorld}
//                       onChange={(e) => handleOriginChange('restOfWorld', e.target.value)}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                 </Grid>
//               </Grid>

//               {/* Method of Acceptance */}
//               <Grid item xs={12}>
//                 <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
//                   METHOD OF ACCEPTANCE
//                 </Typography>
//                 <Grid container spacing={3}>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="E-commerce / M-Commerce"
//                       type="number"
//                       value={acceptancePercentages.ecommerce}
//                       onChange={(e) => handleAcceptanceChange('ecommerce', e.target.value)}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="Card Present (Point-Of-Sale)"
//                       type="number"
//                       value={acceptancePercentages.cardPresent}
//                       onChange={(e) => handleAcceptanceChange('cardPresent', e.target.value)}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="M-Pos (Mobile POS)"
//                       type="number"
//                       value={acceptancePercentages.mpos}
//                       onChange={(e) => handleAcceptanceChange('mpos', e.target.value)}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="MOTO (Mail-order/Telephone-order)"
//                       type="number"
//                       value={acceptancePercentages.moto}
//                       onChange={(e) => handleAcceptanceChange('moto', e.target.value)}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                 </Grid>
//               </Grid>

//               {/* Delivery Time */}
//               <Grid item xs={12}>
//                 <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
//                   DELIVERY TIME FOR GOODS/SERVICES
//                 </Typography>
//                 <Grid container spacing={3}>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="Immediately"
//                       type="number"
//                       value={deliveryPercentages.immediately}
//                       onChange={(e) => handleDeliveryChange('immediately', e.target.value)}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="Within 4 weeks"
//                       type="number"
//                       value={deliveryPercentages.within4Weeks}
//                       onChange={(e) => handleDeliveryChange('within4Weeks', e.target.value)}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="Within 5-14 weeks"
//                       type="number"
//                       value={deliveryPercentages.within5To14Weeks}
//                       onChange={(e) => handleDeliveryChange('within5To14Weeks', e.target.value)}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="More than 14 weeks"
//                       type="number"
//                       value={deliveryPercentages.moreThan14Weeks}
//                       onChange={(e) => handleDeliveryChange('moreThan14Weeks', e.target.value)}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                 </Grid>
//               </Grid>

//               {/* When does payment take place? */}
//               <Grid item xs={12}>
//                 <FormControl component="fieldset">
//                   <FormLabel component="legend">When does payment take place?</FormLabel>
//                   <RadioGroup
//                     row
//                     name="paymentTime"
//                     value={paymentTime}
//                     onChange={(e) => setPaymentTime(e.target.value)}
//                   >
//                     <FormControlLabel value="upon-purchase" control={<Radio />} label="Upon purchase" />
//                     <FormControlLabel value="with-download" control={<Radio />} label="With download" />
//                     <FormControlLabel value="on-delivery" control={<Radio />} label="On delivery" />
//                     <FormControlLabel value="other" control={<Radio />} label="Other" />
//                   </RadioGroup>
//                 </FormControl>
//               </Grid>

//               {/* Card types */}
//               <Grid item xs={12}>
//                 <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
//                   Card types applying for
//                 </Typography>
//                 <Grid container spacing={2}>
//                   <Grid item xs={6} sm={4} md={3}>
//                     <FormControlLabel
//                       control={<Checkbox checked={cardTypes.maestro} onChange={(e) => setCardTypes({ ...cardTypes, maestro: e.target.checked })} />}
//                       label="Maestro"
//                     />
//                   </Grid>
//                   <Grid item xs={6} sm={4} md={3}>
//                     <FormControlLabel
//                       control={<Checkbox checked={cardTypes.mastercard} onChange={(e) => setCardTypes({ ...cardTypes, mastercard: e.target.checked })} />}
//                       label="MasterCard"
//                     />
//                   </Grid>
//                   <Grid item xs={6} sm={4} md={3}>
//                     <FormControlLabel
//                       control={<Checkbox checked={cardTypes.vpay} onChange={(e) => setCardTypes({ ...cardTypes, vpay: e.target.checked })} />}
//                       label="VPay"
//                     />
//                   </Grid>
//                   <Grid item xs={6} sm={4} md={3}>
//                     <FormControlLabel
//                       control={<Checkbox checked={cardTypes.jcb} onChange={(e) => setCardTypes({ ...cardTypes, jcb: e.target.checked })} />}
//                       label="JCB"
//                     />
//                   </Grid>
//                   <Grid item xs={6} sm={4} md={3}>
//                     <FormControlLabel
//                       control={<Checkbox checked={cardTypes.diners} onChange={(e) => setCardTypes({ ...cardTypes, diners: e.target.checked })} />}
//                       label="Diners"
//                     />
//                   </Grid>
//                   <Grid item xs={6} sm={4} md={3}>
//                     <FormControlLabel
//                       control={<Checkbox checked={cardTypes.cartesBancaires} onChange={(e) => setCardTypes({ ...cardTypes, cartesBancaires: e.target.checked })} />}
//                       label="Cartes Bancaires"
//                     />
//                   </Grid>
//                   <Grid item xs={6} sm={4} md={3}>
//                     <FormControlLabel
//                       control={<Checkbox checked={cardTypes.rupay} onChange={(e) => setCardTypes({ ...cardTypes, rupay: e.target.checked })} />}
//                       label="Rupay"
//                     />
//                   </Grid>
//                   <Grid item xs={6} sm={4} md={3}>
//                     <FormControlLabel
//                       control={<Checkbox checked={cardTypes.chinaUnionPay} onChange={(e) => setCardTypes({ ...cardTypes, chinaUnionPay: e.target.checked })} />}
//                       label="China Union Pay"
//                     />
//                   </Grid>
//                   <Grid item xs={6} sm={4} md={3}>
//                     <FormControlLabel
//                       control={<Checkbox checked={cardTypes.americanExpress} onChange={(e) => setCardTypes({ ...cardTypes, americanExpress: e.target.checked })} />}
//                       label="American Express"
//                     />
//                   </Grid>
//                   <Grid item xs={6} sm={4} md={3}>
//                     <FormControlLabel
//                       control={<Checkbox checked={cardTypes.visa} onChange={(e) => setCardTypes({ ...cardTypes, visa: e.target.checked })} />}
//                       label="Visa"
//                     />
//                   </Grid>
//                   <Grid item xs={6} sm={4} md={3}>
//                     <FormControlLabel
//                       control={<Checkbox checked={cardTypes.other} onChange={(e) => setCardTypes({ ...cardTypes, other: e.target.checked })} />}
//                       label="Other"
//                     />
//                   </Grid>
//                 </Grid>
//               </Grid>

//               {/* Affiliate Programs */}
//               <Grid item xs={12}>
//                 <FormControlLabel
//                   control={
//                     <Switch
//                       checked={business.affiliatePrograms}
//                       onChange={handleBusinessChange}
//                       name="affiliatePrograms"
//                     />
//                   }
//                   label="Do you offer / make use of affiliate programs?"
//                 />

//                 {business.affiliatePrograms && (
//                   <Box sx={{ mt: 2 }}>
//                     <TextField
//                       fullWidth
//                       multiline
//                       rows={3}
//                       label="Please provide details"
//                       value={affiliateDetails}
//                       onChange={(e) => setAffiliateDetails(e.target.value)}
//                       placeholder="Please provide details about your affiliate programs..."
//                     />
//                   </Box>
//                 )}
//               </Grid>

//               {/* Software As A Service */}
//               <Grid item xs={12}>
//                 <FormControlLabel
//                   control={
//                     <Switch
//                       checked={business.needSoftwareAsAService}
//                       onChange={handleBusinessChange}
//                       name="needSoftwareAsAService"
//                     />
//                   }
//                   label="Need Software As A Service"
//                 />

//                 {business.needSoftwareAsAService && (
//                   <Box sx={{ mt: 2 }}>
//                     <TextField
//                       fullWidth
//                       multiline
//                       rows={3}
//                       label="Please provide details"
//                       value={softwareDetails}
//                       onChange={(e) => setSoftwareDetails(e.target.value)}
//                       placeholder="Please provide details about your software requirements..."
//                     />
//                   </Box>
//                 )}
//               </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 BusinessProfile


// enpoint integration
  // 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 MenuItem from '@mui/material/MenuItem'
  // import FormControlLabel from '@mui/material/FormControlLabel'
  // import Checkbox from '@mui/material/Checkbox'
  // import Switch from '@mui/material/Switch'
  // import Button from '@mui/material/Button'
  // import Radio from '@mui/material/Radio'
  // import RadioGroup from '@mui/material/RadioGroup'
  // import FormControl from '@mui/material/FormControl'
  // import FormLabel from '@mui/material/FormLabel'
  // 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 BusinessProfileProps {
  //   onNext?: () => void
  //   onPrevious?: () => void
  // }

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

  // interface CreditHistory {
  //   months_ago: string
  //   number_of_transaction: string
  //   transaction_volume: string
  //   number_of_chargeback: string
  //   chargeback_volume: string
  //   number_of_refunds: string
  //   refund_volume: string
  // }

  // const BusinessProfile = ({ onNext, onPrevious }: BusinessProfileProps) => {
  //   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

  //   // Main business state
  //   const [business, setBusiness] = useState({
  //     description_of_products: '',
  //     length_of_time_business: '',
  //     merchant_cat_code: '',
  //     website: '',
  //     descriptor: '',
  //     city_field: '',
  //     dynamic_descriptors: false,
  //     field_for_bankruptcy: false,
  //     field_for_bankruptcy_date: '',
  //     accepted_credit_cards: false,
  //     accepted_credit_cards_months: '',
  //     card_scheme_program: false,
  //     card_scheme_program_provide_details: '',
  //     previous_payment_service_provider: '',
  //     previous_acquirer: '',
  //     leaving_current_acquirer: '',
  //     monthly_sales_volume: '',
  //     currency: '$',
  //     avg_transaction_value: '',
  //     highest_transaction_value: '',
  //     one_time_payment: false,
  //     recurring_payment: false,
  //     domestic: '',
  //     europe: '',
  //     usa: '',
  //     asia: '',
  //     rest_of_world: '',
  //     e_commerce: '',
  //     card_present: '',
  //     m_pos: '',
  //     moto: '',
  //     immediately: '',
  //     within_four_weeks: '',
  //     within_5_14_weeks: '',
  //     more_than_14_weeks: '',
  //     is_upon_purchase: false,
  //     is_with_download: false,
  //     is_on_delivery: false,
  //     is_other_payment_option: false,
  //     other_payment_details: '',
  //     is_offer_affiliate_prog: false,
  //     offer_affiliate_prog_details: '',
  //     is_need_soft_service: false,
  //     software_service_details: '',
  //   })

  //   // Beta website state
  //   const [hasBetaSite, setHasBetaSite] = useState(false)
  //   const [betaWebsite, setBetaWebsite] = useState('')
  //   const [betaUsername, setBetaUsername] = useState('')
  //   const [betaPassword, setBetaPassword] = useState('')

  //   // Credit card history - dynamic based on months entered (max 6)
  //   const [creditCardHistory, setCreditCardHistory] = useState<CreditHistory[]>([])

  //   // Show credit card history table
  //   const [showCreditHistory, setShowCreditHistory] = useState<boolean>(false)
  //   const [numberOfMonths, setNumberOfMonths] = useState<number>(0)

  //   // Card types
  //   const [selectedCardTypes, setSelectedCardTypes] = useState<number[]>([])
  //   const [otherCardDetails, setOtherCardDetails] = useState('')

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

  //   // Initialize credit card history based on months
  //   const initializeCreditHistory = (months: number) => {
  //     const maxMonths = Math.min(months, 6)
  //     const newHistory: CreditHistory[] = []
  //     for (let i = 1; i <= maxMonths; i++) {
  //       newHistory.push({
  //         months_ago: String(i),
  //         number_of_transaction: '',
  //         transaction_volume: '',
  //         number_of_chargeback: '',
  //         chargeback_volume: '',
  //         number_of_refunds: '',
  //         refund_volume: '',
  //       })
  //     }
  //     setCreditCardHistory(newHistory)
  //     setNumberOfMonths(maxMonths)
  //   }

  //   // Fetch existing business data
  //   useEffect(() => {
  //     fetchBusinessData()
  //   }, [])

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

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

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

  //       if (response.data && response.data.businessProfile) {
  //         const formData = response.data.businessProfile
  //         console.log('Existing business data found:', formData)
  //         setIsEditMode(true)
  //         prefillFormData(formData)
  //         toast.success('Business data loaded!')
  //       } else {
  //         console.log('No existing business data found')
  //         setIsEditMode(false)
  //       }
  //     } catch (err: any) {
  //       console.error('Error fetching business data:', err)
  //       if (err.response?.status === 404) {
  //         console.log('No business record found, will create new on submit')
  //         setIsEditMode(false)
  //       } else {
  //         toast.error('Failed to load business data')
  //       }
  //     } finally {
  //       setFetchingData(false)
  //     }
  //   }

  //   const prefillFormData = (data: any) => {
  //     console.log('Prefilling business data:', data)

  //     if (data.descriptionOfProducts) {
  //       setBusiness(prev => ({ ...prev, description_of_products: data.descriptionOfProducts }))
  //     }
  //     if (data.lengthOfBusiness) {
  //       setBusiness(prev => ({ ...prev, length_of_time_business: data.lengthOfBusiness }))
  //     }
  //     if (data.merchantCategoryCode) {
  //       setBusiness(prev => ({ ...prev, merchant_cat_code: data.merchantCategoryCode }))
  //     }
  //     if (data.website) {
  //       setBusiness(prev => ({ ...prev, website: data.website }))
  //     }
  //     if (data.betaWebsite) {
  //       setHasBetaSite(true)
  //       setBetaWebsite(data.betaWebsite)
  //     }
  //     if (data.username) {
  //       setBetaUsername(data.username)
  //     }
  //     if (data.password) {
  //       setBetaPassword(data.password)
  //     }
  //     if (data.descriptor !== undefined && data.descriptor !== null) {
  //       setBusiness(prev => ({ ...prev, descriptor: data.descriptor || '' }))
  //     }
  //     if (data.cityField) {
  //       setBusiness(prev => ({ ...prev, city_field: data.cityField }))
  //     }
  //     if (data.isDynamicDescriptor !== undefined) {
  //       setBusiness(prev => ({ ...prev, dynamic_descriptors: data.isDynamicDescriptor }))
  //     }
  //     if (data.isBankruptcy !== undefined) {
  //       setBusiness(prev => ({ ...prev, field_for_bankruptcy: data.isBankruptcy }))
  //     }
  //     if (data.fieldForBankruptcyDate) {
  //       setBusiness(prev => ({ ...prev, field_for_bankruptcy_date: data.fieldForBankruptcyDate }))
  //     }
  //     if (data.isAcceptedCreditCards !== undefined) {
  //       setBusiness(prev => ({ ...prev, accepted_credit_cards: data.isAcceptedCreditCards }))
  //     }
  //     if (data.acceptedCreditCardMonths) {
  //       const months = parseInt(data.acceptedCreditCardMonths)
  //       setBusiness(prev => ({ ...prev, accepted_credit_cards_months: String(months) }))
  //       if (months > 0) {
  //         setShowCreditHistory(true)
  //         initializeCreditHistory(months)
  //       }
  //     }
      
  //     // Credit card history - map backend data
  //     if (data.creditCardHistory && Array.isArray(data.creditCardHistory) && data.creditCardHistory.length > 0) {
  //       const history = data.creditCardHistory
  //       const monthsCount = Math.min(history.length, 6)
  //       const newHistory: CreditHistory[] = []
  //       for (let i = 0; i < monthsCount; i++) {
  //         const backendData = history[i] || {}
  //         newHistory.push({
  //           months_ago: backendData.months_ago || String(i + 1),
  //           number_of_transaction: backendData.number_of_transaction || backendData.numberOfTransaction || '',
  //           transaction_volume: backendData.transaction_volume || backendData.transactionVolume || '',
  //           number_of_chargeback: backendData.number_of_chargeback || backendData.numberOfChargeback || '',
  //           chargeback_volume: backendData.chargeback_volume || backendData.chargebackVolume || '',
  //           number_of_refunds: backendData.number_of_refunds || backendData.numberOfRefunds || '',
  //           refund_volume: backendData.refund_volume || backendData.refundVolume || '',
  //         })
  //       }
  //       setCreditCardHistory(newHistory)
  //       setNumberOfMonths(monthsCount)
  //       setShowCreditHistory(true)
  //     }

  //     if (data.hasCardSchemeProgram !== undefined) {
  //       setBusiness(prev => ({ ...prev, card_scheme_program: data.hasCardSchemeProgram }))
  //     }
  //     if (data.cardSchemeProgramDetails && data.cardSchemeProgramDetails !== 'NA') {
  //       setBusiness(prev => ({ ...prev, card_scheme_program_provide_details: data.cardSchemeProgramDetails }))
  //     }
  //     if (data.previousPaymentServiceProvider) {
  //       setBusiness(prev => ({ ...prev, previous_payment_service_provider: data.previousPaymentServiceProvider }))
  //     }
  //     if (data.previousAcquirer) {
  //       setBusiness(prev => ({ ...prev, previous_acquirer: data.previousAcquirer }))
  //     }
  //     if (data.reasonForLeavingAcquirer) {
  //       setBusiness(prev => ({ ...prev, leaving_current_acquirer: data.reasonForLeavingAcquirer }))
  //     }
  //     if (data.monthlySalesVolume !== undefined && data.monthlySalesVolume !== null) {
  //       setBusiness(prev => ({ ...prev, monthly_sales_volume: String(data.monthlySalesVolume) }))
  //     }
  //     if (data.salesCurrency) {
  //       setBusiness(prev => ({ ...prev, currency: data.salesCurrency }))
  //     }
  //     if (data.avgTransValue !== undefined && data.avgTransValue !== null) {
  //       setBusiness(prev => ({ ...prev, avg_transaction_value: String(data.avgTransValue) }))
  //     }
  //     if (data.highestTransValue !== undefined && data.highestTransValue !== null) {
  //       setBusiness(prev => ({ ...prev, highest_transaction_value: String(data.highestTransValue) }))
  //     }
  //     if (data.oneTimePayment !== undefined) {
  //       setBusiness(prev => ({ ...prev, one_time_payment: data.oneTimePayment }))
  //     }
  //     if (data.recurringPayment !== undefined) {
  //       setBusiness(prev => ({ ...prev, recurring_payment: data.recurringPayment }))
  //     }
  //     if (data.domestic !== undefined && data.domestic !== null) {
  //       setBusiness(prev => ({ ...prev, domestic: String(data.domestic) }))
  //     }
  //     if (data.europe !== undefined && data.europe !== null) {
  //       setBusiness(prev => ({ ...prev, europe: String(data.europe) }))
  //     }
  //     if (data.usa !== undefined && data.usa !== null) {
  //       setBusiness(prev => ({ ...prev, usa: String(data.usa) }))
  //     }
  //     if (data.asia !== undefined && data.asia !== null) {
  //       setBusiness(prev => ({ ...prev, asia: String(data.asia) }))
  //     }
  //     if (data.restOfWorld !== undefined && data.restOfWorld !== null) {
  //       setBusiness(prev => ({ ...prev, rest_of_world: String(data.restOfWorld) }))
  //     }
  //     if (data.ecommerce !== undefined && data.ecommerce !== null) {
  //       setBusiness(prev => ({ ...prev, e_commerce: String(data.ecommerce) }))
  //     }
  //     if (data.cardPresent !== undefined && data.cardPresent !== null) {
  //       setBusiness(prev => ({ ...prev, card_present: String(data.cardPresent) }))
  //     }
  //     if (data.mpos !== undefined && data.mpos !== null) {
  //       setBusiness(prev => ({ ...prev, m_pos: String(data.mpos) }))
  //     }
  //     if (data.moto !== undefined && data.moto !== null) {
  //       setBusiness(prev => ({ ...prev, moto: String(data.moto) }))
  //     }
  //     if (data.immediately !== undefined && data.immediately !== null) {
  //       setBusiness(prev => ({ ...prev, immediately: String(data.immediately) }))
  //     }
  //     if (data.withinFourWeeks !== undefined && data.withinFourWeeks !== null) {
  //       setBusiness(prev => ({ ...prev, within_four_weeks: String(data.withinFourWeeks) }))
  //     }
  //     if (data.within5To14Weeks !== undefined && data.within5To14Weeks !== null) {
  //       setBusiness(prev => ({ ...prev, within_5_14_weeks: String(data.within5To14Weeks) }))
  //     }
  //     if (data.moreThan14Weeks !== undefined && data.moreThan14Weeks !== null) {
  //       setBusiness(prev => ({ ...prev, more_than_14_weeks: String(data.moreThan14Weeks) }))
  //     }
  //     if (data.isUponPurchase !== undefined) {
  //       setBusiness(prev => ({ ...prev, is_upon_purchase: data.isUponPurchase }))
  //     }
  //     if (data.isWithDownload !== undefined) {
  //       setBusiness(prev => ({ ...prev, is_with_download: data.isWithDownload }))
  //     }
  //     if (data.isonDelivery !== undefined) {
  //       setBusiness(prev => ({ ...prev, is_on_delivery: data.isonDelivery }))
  //     }
  //     if (data.isOtherPaymentOption !== undefined) {
  //       setBusiness(prev => ({ ...prev, is_other_payment_option: data.isOtherPaymentOption }))
  //     }
  //     if (data.otherPaymentDetails && data.otherPaymentDetails !== 'NA') {
  //       setBusiness(prev => ({ ...prev, other_payment_details: data.otherPaymentDetails }))
  //     }
  //     if (data.isOfferAffiliateProg !== undefined) {
  //       setBusiness(prev => ({ ...prev, is_offer_affiliate_prog: data.isOfferAffiliateProg }))
  //     }
  //     if (data.offerAffiliateProgDetails && data.offerAffiliateProgDetails !== 'NA') {
  //       setBusiness(prev => ({ ...prev, offer_affiliate_prog_details: data.offerAffiliateProgDetails }))
  //     }
  //     if (data.isNeedSoftwService !== undefined) {
  //       setBusiness(prev => ({ ...prev, is_need_soft_service: data.isNeedSoftwService }))
  //     }
  //     if (data.softwareServDetails && data.softwareServDetails !== 'NA') {
  //       setBusiness(prev => ({ ...prev, software_service_details: data.softwareServDetails }))
  //     }
  //     if (data.card_type && Array.isArray(data.card_type)) {
  //       setSelectedCardTypes(data.card_type)
  //     }
  //   }

  //   const handleBusinessChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  //     const { name, value, type, checked } = e.target
      
  //     if (name === 'accepted_credit_cards_months') {
  //       const numValue = parseInt(value) || 0
  //       setBusiness(prev => ({ ...prev, [name]: value }))
        
  //       // Show/hide credit history based on months entered
  //       if (numValue > 0 && business.accepted_credit_cards) {
  //         const maxMonths = Math.min(numValue, 6)
  //         setShowCreditHistory(true)
  //         initializeCreditHistory(maxMonths)
  //       } else {
  //         setShowCreditHistory(false)
  //         setCreditCardHistory([])
  //       }
        
  //       if (errors[name]) {
  //         setErrors(prev => ({ ...prev, [name]: '' }))
  //       }
  //       return
  //     }

  //     setBusiness(prev => ({
  //       ...prev,
  //       [name]: type === 'checkbox' ? checked : value
  //     }))

  //     if (name === 'accepted_credit_cards' && !checked) {
  //       setShowCreditHistory(false)
  //       setCreditCardHistory([])
  //     }

  //     if (errors[name]) {
  //       setErrors(prev => ({ ...prev, [name]: '' }))
  //     }
  //   }

  //   const handleCreditHistoryChange = (index: number, field: string, value: string) => {
  //     const newHistory = [...creditCardHistory]
  //     newHistory[index] = { ...newHistory[index], [field]: value }
  //     setCreditCardHistory(newHistory)
  //   }

  //   const handleCardTypeToggle = (cardId: number) => {
  //     setSelectedCardTypes(prev =>
  //       prev.includes(cardId)
  //         ? prev.filter(id => id !== cardId)
  //         : [...prev, cardId]
  //     )
  //   }

  //   const buildRequestBody = () => {
  //     const requestBody: any = {
  //       application_id: STATIC_APPLICATION_ID,
  //       description_of_products: business.description_of_products || '',
  //       length_of_time_business: business.length_of_time_business || '',
  //       merchant_cat_code: business.merchant_cat_code || '',
  //       website: business.website || '',
  //       descriptor: business.descriptor || '',
  //       city_field: business.city_field || '',
  //       dynamic_descriptors: business.dynamic_descriptors,
  //       field_for_bankruptcy: business.field_for_bankruptcy,
  //       field_for_bankruptcy_date: business.field_for_bankruptcy_date || '',
  //       accepted_credit_cards: business.accepted_credit_cards,
  //       accepted_credit_cards_months: business.accepted_credit_cards_months || '',
  //       card_scheme_program: business.card_scheme_program,
  //       card_scheme_program_provide_details: business.card_scheme_program_provide_details || '',
  //       previous_payment_service_provider: business.previous_payment_service_provider || '',
  //       previous_acquirer: business.previous_acquirer || '',
  //       leaving_current_acquirer: business.leaving_current_acquirer || '',
  //       monthly_sales_volume: business.monthly_sales_volume || '',
  //       currency: business.currency || '$',
  //       avg_transaction_value: business.avg_transaction_value || '',
  //       highest_transaction_value: business.highest_transaction_value || '',
  //       one_time_payment: business.one_time_payment,
  //       recurring_payment: business.recurring_payment,
  //       domestic: business.domestic || '',
  //       europe: business.europe || '',
  //       usa: business.usa || '',
  //       asia: business.asia || '',
  //       rest_of_world: business.rest_of_world || '',
  //       e_commerce: business.e_commerce || '',
  //       card_present: business.card_present || '',
  //       m_pos: business.m_pos || '',
  //       moto: business.moto || '',
  //       immediately: business.immediately || '',
  //       within_four_weeks: business.within_four_weeks || '',
  //       within_5_14_weeks: business.within_5_14_weeks || '',
  //       more_than_14_weeks: business.more_than_14_weeks || '',
  //       is_upon_purchase: business.is_upon_purchase,
  //       is_with_download: business.is_with_download,
  //       is_on_delivery: business.is_on_delivery,
  //       is_other_payment_option: business.is_other_payment_option,
  //       other_payment_details: business.other_payment_details || '',
  //       is_offer_affiliate_prog: business.is_offer_affiliate_prog,
  //       offer_affiliate_prog_details: business.offer_affiliate_prog_details || '',
  //       is_need_soft_service: business.is_need_soft_service,
  //       software_service_details: business.software_service_details || '',
  //     }

  //     if (hasBetaSite) {
  //       requestBody.beta_website = betaWebsite || ''
  //       requestBody.username = betaUsername || ''
  //       requestBody.password = betaPassword || ''
  //     }

  //     // Only include credit card history if accepted_credit_cards is true and months > 0
  //     if (business.accepted_credit_cards && parseInt(business.accepted_credit_cards_months) > 0 && creditCardHistory.length > 0) {
  //       const historyWithMonths = creditCardHistory.map(({ months_ago, number_of_transaction, transaction_volume, number_of_chargeback, chargeback_volume, number_of_refunds, refund_volume }) => ({
  //         months_ago: parseInt(months_ago),
  //         number_of_transaction: number_of_transaction || '0',
  //         transaction_volume: transaction_volume || '0',
  //         number_of_chargeback: number_of_chargeback || '0',
  //         chargeback_volume: chargeback_volume || '0',
  //         number_of_refunds: number_of_refunds || '0',
  //         refund_volume: refund_volume || '0',
  //       }))
  //       requestBody.credit_card_history = historyWithMonths
  //     }

  //     if (selectedCardTypes && selectedCardTypes.length > 0) {
  //       requestBody.card_type = selectedCardTypes
  //     }

  //     if (selectedCardTypes.includes(11) && otherCardDetails) {
  //       requestBody.other_card_details = otherCardDetails
  //     }

  //     return requestBody
  //   }

  //   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) {
  //         response = await axiosInstance.put(
  //           `${endpoints.merchantApplication.businessProfile}${STATIC_APPLICATION_ID}`,
  //           requestBody
  //         )
  //         console.log('PUT Response:', response.data)
  //         toast.success('Business profile updated successfully!')
  //       } else {
  //         response = await axiosInstance.post(
  //           endpoints.merchantApplication.businessProfile,
  //           requestBody
  //         )
  //         console.log('POST Response:', response.data)
  //         toast.success('Business profile created successfully!')
  //         setIsEditMode(true)
  //       }

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

  //       let errorMessage = isEditMode
  //         ? 'Failed to update business profile. Please try again.'
  //         : 'Failed to create business profile. 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)
  //     }
  //   }

  //   const merchantCategories = [
  //     'Restaurants',
  //     'Retail',
  //     'E-commerce',
  //     'Professional Services',
  //     'Healthcare',
  //     'Education',
  //     'Travel & Tourism',
  //     'Entertainment',
  //     'Manufacturing',
  //     'Wholesale',
  //     'Other'
  //   ]

  //   const cardTypesList = [
  //     { id: 1, name: 'Maestro' },
  //     { id: 2, name: 'MasterCard' },
  //     { id: 3, name: 'VPay' },
  //     { id: 4, name: 'JCB' },
  //     { id: 5, name: 'Diners' },
  //     { id: 6, name: 'Cartes Bancaires' },
  //     { id: 7, name: 'Rupay' },
  //     { id: 8, name: 'China Union Pay' },
  //     { id: 9, name: 'American Express' },
  //     { id: 10, name: 'Visa' },
  //     { id: 11, name: 'Other' },
  //   ]

  //   // Generate month suffix
  //   const getMonthSuffix = (num: number) => {
  //     if (num === 1) return '1st'
  //     if (num === 2) return '2nd'
  //     if (num === 3) return '3rd'
  //     return `${num}th`
  //   }

  //   if (fetchingData) {
  //     return (
  //       <Box sx={{ p: 6 }}>
  //         <Skeleton variant="text" height={60} />
  //         <Skeleton variant="rectangular" height={400} />
  //         <Skeleton variant="text" height={60} />
  //         <Skeleton variant="rectangular" height={200} />
  //       </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: 0 }}>
  //             <Box sx={{ mb: 5 }}>
  //               <Typography variant="h5" sx={{ fontWeight: 600, mb: 0.5, color: 'text.primary' }}>
  //                 Business Profile Details
  //               </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={{ mb: 4 }} />
  //             </Box>

  //             <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 severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
  //                 {error}
  //               </Alert>
  //             )}

  //             <Grid container spacing={3}>
  //               <Grid item xs={12}>
  //                 <TextField
  //                   fullWidth
  //                   multiline
  //                   rows={3}
  //                   name="description_of_products"
  //                   label="Detailed Description of Products/Services Sold"
  //                   value={business.description_of_products}
  //                   onChange={handleBusinessChange}
  //                   error={!!errors.description_of_products}
  //                   helperText={errors.description_of_products}
  //                   placeholder="Please provide a detailed description of the products or services your business sells..."
  //                 />
  //               </Grid>

  //               <Grid item xs={12} sm={6}>
  //                 <TextField
  //                   fullWidth
  //                   name="length_of_time_business"
  //                   label="Length of time in business"
  //                   value={business.length_of_time_business}
  //                   onChange={handleBusinessChange}
  //                   error={!!errors.length_of_time_business}
  //                   helperText={errors.length_of_time_business}
  //                   placeholder="e.g., 5 years"
  //                 />
  //               </Grid>

  //               <Grid item xs={12} sm={6}>
  //                 <TextField
  //                   fullWidth
  //                   select
  //                   name="merchant_cat_code"
  //                   label="Merchant Category (MCC)"
  //                   value={business.merchant_cat_code}
  //                   onChange={handleBusinessChange}
  //                   error={!!errors.merchant_cat_code}
  //                   helperText={errors.merchant_cat_code}
  //                 >
  //                   <MenuItem value="" disabled>Select</MenuItem>
  //                   {merchantCategories.map(category => (
  //                     <MenuItem key={category} value={category}>{category}</MenuItem>
  //                   ))}
  //                 </TextField>
  //               </Grid>

  //               <Grid item xs={12}>
  //                 <Grid container spacing={3} alignItems="flex-start">
  //                   <Grid item xs={12} sm={6}>
  //                     <TextField
  //                       fullWidth
  //                       name="website"
  //                       label="Website(s) (Comma-Separated)"
  //                       value={business.website}
  //                       onChange={handleBusinessChange}
  //                       error={!!errors.website}
  //                       helperText={errors.website}
  //                       placeholder="https://example.com, https://store.example.com"
  //                     />
  //                   </Grid>

  //                   <Grid item xs={12} sm={6}>
  //                     <FormControlLabel
  //                       control={
  //                         <Switch
  //                           checked={hasBetaSite}
  //                           onChange={(e) => setHasBetaSite(e.target.checked)}
  //                         />
  //                       }
  //                       label="Beta Site(s)"
  //                     />
  //                     <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2 }}>
  //                       Toggle on to add website details
  //                     </Typography>
  //                   </Grid>

  //                   {hasBetaSite && (
  //                     <Grid item xs={12}>
  //                       <Box sx={{ bgcolor: 'action.hover', borderRadius: 2, p: 3, mt: 1 }}>
  //                         <Typography variant="h6" sx={{ fontWeight: 600, mb: 3 }}>
  //                           Beta Website Details
  //                         </Typography>
  //                         <Grid container spacing={2}>
  //                           <Grid item xs={12}>
  //                             <TextField
  //                               fullWidth
  //                               label="Beta Website URL"
  //                               value={betaWebsite}
  //                               onChange={(e) => setBetaWebsite(e.target.value)}
  //                               placeholder="https://beta.example.com"
  //                             />
  //                           </Grid>
  //                           <Grid item xs={12} sm={6}>
  //                             <TextField
  //                               fullWidth
  //                               label="Username"
  //                               value={betaUsername}
  //                               onChange={(e) => setBetaUsername(e.target.value)}
  //                             />
  //                           </Grid>
  //                           <Grid item xs={12} sm={6}>
  //                             <TextField
  //                               fullWidth
  //                               label="Password"
  //                               type="password"
  //                               value={betaPassword}
  //                               onChange={(e) => setBetaPassword(e.target.value)}
  //                             />
  //                           </Grid>
  //                         </Grid>
  //                       </Box>
  //                     </Grid>
  //                   )}
  //                 </Grid>
  //               </Grid>

  //               <Grid item xs={12} sm={6}>
  //                 <TextField
  //                   fullWidth
  //                   name="descriptor"
  //                   label="Credit Card Descriptor (Max 22 Char.)"
  //                   value={business.descriptor}
  //                   onChange={handleBusinessChange}
  //                   error={!!errors.descriptor}
  //                   helperText={errors.descriptor}
  //                   inputProps={{ maxLength: 22 }}
  //                 />
  //               </Grid>

  //               <Grid item xs={12} sm={6}>
  //                 <TextField
  //                   fullWidth
  //                   name="city_field"
  //                   label="DBA/City (Max 12 Char.)"
  //                   value={business.city_field}
  //                   onChange={handleBusinessChange}
  //                   error={!!errors.city_field}
  //                   helperText={errors.city_field}
  //                   inputProps={{ maxLength: 12 }}
  //                 />
  //               </Grid>

  //               <Grid item xs={12}>
  //                 <FormControlLabel
  //                   control={
  //                     <Checkbox
  //                       checked={business.dynamic_descriptors}
  //                       onChange={handleBusinessChange}
  //                       name="dynamic_descriptors"
  //                     />
  //                   }
  //                   label="Will You use 'Dynamic Descriptor'"
  //                 />
  //               </Grid>

  //               <Grid item xs={12}>
  //                 <FormControlLabel
  //                   control={
  //                     <Checkbox
  //                       checked={business.field_for_bankruptcy}
  //                       onChange={handleBusinessChange}
  //                       name="field_for_bankruptcy"
  //                     />
  //                   }
  //                   label="Have you filed for bankruptcy before?"
  //                 />
  //                 {business.field_for_bankruptcy && (
  //                   <Box sx={{ mt: 2, ml: 4 }}>
  //                     <TextField
  //                       fullWidth
  //                       type="date"
  //                       label="Date of Bankruptcy"
  //                       name="field_for_bankruptcy_date"
  //                       value={business.field_for_bankruptcy_date}
  //                       onChange={handleBusinessChange}
  //                       InputLabelProps={{ shrink: true }}
  //                     />
  //                   </Box>
  //                 )}
  //               </Grid>

  //               <Grid item xs={12}>
  //                 <FormControlLabel
  //                   control={
  //                     <Checkbox
  //                       checked={business.accepted_credit_cards}
  //                       onChange={handleBusinessChange}
  //                       name="accepted_credit_cards"
  //                     />
  //                   }
  //                   label="Have you previously accepted Credit Card payments?"
  //                 />
  //                 {business.accepted_credit_cards && (
  //                   <Box sx={{ mt: 2, ml: 4 }}>
  //                     <Grid container spacing={2}>
  //                       <Grid item xs={12} sm={6}>
  //                         <TextField
  //                           fullWidth
  //                           type="number"
  //                           label="How Many Months (Max 6)"
  //                           name="accepted_credit_cards_months"
  //                           value={business.accepted_credit_cards_months}
  //                           onChange={handleBusinessChange}
  //                           placeholder="Enter number of months (max 6)"
  //                           helperText="Enter 1-6 months to show credit history"
  //                           inputProps={{ min: 0, max: 6 }}
  //                         />
  //                       </Grid>
  //                       <Grid item xs={12} sm={6}>
  //                         <TextField
  //                           fullWidth
  //                           label="Previous Payment Service Provider"
  //                           name="previous_payment_service_provider"
  //                           value={business.previous_payment_service_provider}
  //                           onChange={handleBusinessChange}
  //                           placeholder="Enter provider name"
  //                         />
  //                       </Grid>
  //                       <Grid item xs={12} sm={6}>
  //                         <TextField
  //                           fullWidth
  //                           label="Previous Acquirer"
  //                           name="previous_acquirer"
  //                           value={business.previous_acquirer}
  //                           onChange={handleBusinessChange}
  //                           placeholder="Enter acquirer name"
  //                         />
  //                       </Grid>
  //                       <Grid item xs={12} sm={6}>
  //                         <TextField
  //                           fullWidth
  //                           label="Reason for leaving current acquirer"
  //                           name="leaving_current_acquirer"
  //                           value={business.leaving_current_acquirer}
  //                           onChange={handleBusinessChange}
  //                           placeholder="Enter reason"
  //                         />
  //                       </Grid>
  //                     </Grid>

  //                     {/* Credit Card History Table - Shows only when months > 0 and <= 6 */}
  //                     {showCreditHistory && creditCardHistory.length > 0 && (
  //                       <Box sx={{ mt: 4 }}>
  //                         <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, color: 'primary.main' }}>
  //                           PLEASE PROVIDE {creditCardHistory.length} MONTH{creditCardHistory.length > 1 ? 'S' : ''} OF MOST RECENT PROCESSING HISTORY BELOW
  //                         </Typography>
  //                         <Box sx={{ overflowX: 'auto' }}>
  //                           <table style={{ width: '100%', borderCollapse: 'collapse' }}>
  //                             <thead>
  //                               <tr style={{ backgroundColor: '#f5f5f5' }}>
  //                                 <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '80px' }}>
  //                                   MONTH
  //                                 </th>
  //                                 <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
  //                                   Number of transactions
  //                                 </th>
  //                                 <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
  //                                   Transaction volume
  //                                 </th>
  //                                 <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
  //                                   Number of chargebacks
  //                                 </th>
  //                                 <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
  //                                   Chargeback volume
  //                                 </th>
  //                                 <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
  //                                   Number of refunds
  //                                 </th>
  //                                 <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
  //                                   Refund volume
  //                                 </th>
  //                               </tr>
  //                             </thead>
  //                             <tbody>
  //                               {creditCardHistory.map((history, index) => (
  //                                 <tr key={index}>
  //                                   <td style={{ padding: '12px', border: '1px solid #ddd', fontWeight: 500, textAlign: 'center' }}>
  //                                     {getMonthSuffix(index + 1)}
  //                                   </td>
  //                                   <td style={{ padding: '8px', border: '1px solid #ddd' }}>
  //                                     <TextField
  //                                       fullWidth
  //                                       type="number"
  //                                       size="small"
  //                                       value={history.number_of_transaction}
  //                                       onChange={(e) => handleCreditHistoryChange(index, 'number_of_transaction', e.target.value)}
  //                                       placeholder="0"
  //                                     />
  //                                   </td>
  //                                   <td style={{ padding: '8px', border: '1px solid #ddd' }}>
  //                                     <TextField
  //                                       fullWidth
  //                                       type="number"
  //                                       size="small"
  //                                       value={history.transaction_volume}
  //                                       onChange={(e) => handleCreditHistoryChange(index, 'transaction_volume', e.target.value)}
  //                                       placeholder="0"
  //                                     />
  //                                   </td>
  //                                   <td style={{ padding: '8px', border: '1px solid #ddd' }}>
  //                                     <TextField
  //                                       fullWidth
  //                                       type="number"
  //                                       size="small"
  //                                       value={history.number_of_chargeback}
  //                                       onChange={(e) => handleCreditHistoryChange(index, 'number_of_chargeback', e.target.value)}
  //                                       placeholder="0"
  //                                     />
  //                                   </td>
  //                                   <td style={{ padding: '8px', border: '1px solid #ddd' }}>
  //                                     <TextField
  //                                       fullWidth
  //                                       type="number"
  //                                       size="small"
  //                                       value={history.chargeback_volume}
  //                                       onChange={(e) => handleCreditHistoryChange(index, 'chargeback_volume', e.target.value)}
  //                                       placeholder="0"
  //                                     />
  //                                   </td>
  //                                   <td style={{ padding: '8px', border: '1px solid #ddd' }}>
  //                                     <TextField
  //                                       fullWidth
  //                                       type="number"
  //                                       size="small"
  //                                       value={history.number_of_refunds}
  //                                       onChange={(e) => handleCreditHistoryChange(index, 'number_of_refunds', e.target.value)}
  //                                       placeholder="0"
  //                                     />
  //                                   </td>
  //                                   <td style={{ padding: '8px', border: '1px solid #ddd' }}>
  //                                     <TextField
  //                                       fullWidth
  //                                       type="number"
  //                                       size="small"
  //                                       value={history.refund_volume}
  //                                       onChange={(e) => handleCreditHistoryChange(index, 'refund_volume', e.target.value)}
  //                                       placeholder="0"
  //                                     />
  //                                   </td>
  //                                 </tr>
  //                               ))}
  //                             </tbody>
  //                           </table>
  //                         </Box>
  //                       </Box>
  //                     )}
  //                   </Box>
  //                 )}
  //               </Grid>

  //               <Grid item xs={12}>
  //                 <FormControlLabel
  //                   control={
  //                     <Checkbox
  //                       checked={business.card_scheme_program}
  //                       onChange={handleBusinessChange}
  //                       name="card_scheme_program"
  //                     />
  //                   }
  //                   label="Have you ever flagged or been in violation of any card schema program?"
  //                 />
  //                 {business.card_scheme_program && (
  //                   <Box sx={{ mt: 2, ml: 4 }}>
  //                     <TextField
  //                       fullWidth
  //                       multiline
  //                       rows={3}
  //                       label="Please Provide Details"
  //                       name="card_scheme_program_provide_details"
  //                       value={business.card_scheme_program_provide_details}
  //                       onChange={handleBusinessChange}
  //                       placeholder="Please provide details about the violation..."
  //                     />
  //                   </Box>
  //                 )}
  //               </Grid>

  //               <Grid item xs={12} sm={4}>
  //                 <TextField
  //                   fullWidth
  //                   name="monthly_sales_volume"
  //                   label="Estimated monthly sales volume"
  //                   type="number"
  //                   value={business.monthly_sales_volume}
  //                   onChange={handleBusinessChange}
  //                   placeholder="Enter amount"
  //                   InputProps={{ startAdornment: <span>$ </span> }}
  //                 />
  //               </Grid>

  //               {/* <Grid item xs={12} sm={4}>
  //                 <TextField
  //                   fullWidth
  //                   name="currency"
  //                   label="Currency"
  //                   value={business.currency}
  //                   onChange={handleBusinessChange}
  //                   placeholder="e.g., USD, EUR"
  //                 />
  //               </Grid> */}
  //               <Grid item xs={12} sm={4}>
  //                 <TextField
  //                   fullWidth
  //                   name="highest_transaction_value"
  //                   label="Highest transaction value"
  //                   type="number"
  //                   value={business.highest_transaction_value}
  //                   onChange={handleBusinessChange}
  //                   placeholder="Enter amount"
  //                   InputProps={{ startAdornment: <span>$ </span> }}
  //                 />
  //               </Grid>

  //               <Grid item xs={12} sm={4}>
  //                 <TextField
  //                   fullWidth
  //                   name="avg_transaction_value"
  //                   label="Average transaction value"
  //                   type="number"
  //                   value={business.avg_transaction_value}
  //                   onChange={handleBusinessChange}
  //                   placeholder="Enter amount"
  //                   InputProps={{ startAdornment: <span>$ </span> }}
  //                 />
  //               </Grid>

                

  //               <Grid item xs={12} sm={6}>
  //                 <FormControl component="fieldset">
  //                   <FormLabel component="legend">Payment frequency</FormLabel>
  //                   <Stack direction="row" spacing={2}>
  //                     <FormControlLabel
  //                       control={
  //                         <Checkbox
  //                           checked={business.one_time_payment}
  //                           onChange={handleBusinessChange}
  //                           name="one_time_payment"
  //                         />
  //                       }
  //                       label="One-time payment"
  //                     />
  //                     <FormControlLabel
  //                       control={
  //                         <Checkbox
  //                           checked={business.recurring_payment}
  //                           onChange={handleBusinessChange}
  //                           name="recurring_payment"
  //                         />
  //                       }
  //                       label="Recurring payment"
  //                     />
  //                   </Stack>
  //                 </FormControl>
  //               </Grid>

  //               <Grid item xs={12}>
  //                 <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
  //                   ORIGIN OF TRANSACTIONS (%)
  //                 </Typography>
  //                 <Grid container spacing={2}>
  //                   <Grid item xs={12} sm={6}>
  //                     <TextField
  //                       fullWidth
  //                       label="Domestic"
  //                       type="number"
  //                       name="domestic"
  //                       value={business.domestic}
  //                       onChange={handleBusinessChange}
  //                       InputProps={{ endAdornment: '%' }}
  //                     />
  //                   </Grid>
  //                   <Grid item xs={12} sm={6}>
  //                     <TextField
  //                       fullWidth
  //                       label="Europe"
  //                       type="number"
  //                       name="europe"
  //                       value={business.europe}
  //                       onChange={handleBusinessChange}
  //                       InputProps={{ endAdornment: '%' }}
  //                     />
  //                   </Grid>
  //                   <Grid item xs={12} sm={6}>
  //                     <TextField
  //                       fullWidth
  //                       label="USA (Oceania)"
  //                       type="number"
  //                       name="usa"
  //                       value={business.usa}
  //                       onChange={handleBusinessChange}
  //                       InputProps={{ endAdornment: '%' }}
  //                     />
  //                   </Grid>
  //                   <Grid item xs={12} sm={6}>
  //                     <TextField
  //                       fullWidth
  //                       label="Asia"
  //                       type="number"
  //                       name="asia"
  //                       value={business.asia}
  //                       onChange={handleBusinessChange}
  //                       InputProps={{ endAdornment: '%' }}
  //                     />
  //                   </Grid>
  //                   <Grid item xs={12} sm={6}>
  //                     <TextField
  //                       fullWidth
  //                       label="Rest of world"
  //                       type="number"
  //                       name="rest_of_world"
  //                       value={business.rest_of_world}
  //                       onChange={handleBusinessChange}
  //                       InputProps={{ endAdornment: '%' }}
  //                     />
  //                   </Grid>
  //                 </Grid>
  //               </Grid>

  //               <Grid item xs={12}>
  //                 <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
  //                   METHOD OF ACCEPTANCE (%)
  //                 </Typography>
  //                 <Grid container spacing={2}>
  //                   <Grid item xs={12} sm={6}>
  //                     <TextField
  //                       fullWidth
  //                       label="E-commerce / M-Commerce"
  //                       type="number"
  //                       name="e_commerce"
  //                       value={business.e_commerce}
  //                       onChange={handleBusinessChange}
  //                       InputProps={{ endAdornment: '%' }}
  //                     />
  //                   </Grid>
  //                   <Grid item xs={12} sm={6}>
  //                     <TextField
  //                       fullWidth
  //                       label="Card Present (POS)"
  //                       type="number"
  //                       name="card_present"
  //                       value={business.card_present}
  //                       onChange={handleBusinessChange}
  //                       InputProps={{ endAdornment: '%' }}
  //                     />
  //                   </Grid>
  //                   <Grid item xs={12} sm={6}>
  //                     <TextField
  //                       fullWidth
  //                       label="M-Pos (Mobile POS)"
  //                       type="number"
  //                       name="m_pos"
  //                       value={business.m_pos}
  //                       onChange={handleBusinessChange}
  //                       InputProps={{ endAdornment: '%' }}
  //                     />
  //                   </Grid>
  //                   <Grid item xs={12} sm={6}>
  //                     <TextField
  //                       fullWidth
  //                       label="MOTO"
  //                       type="number"
  //                       name="moto"
  //                       value={business.moto}
  //                       onChange={handleBusinessChange}
  //                       InputProps={{ endAdornment: '%' }}
  //                     />
  //                   </Grid>
  //                 </Grid>
  //               </Grid>

  //               <Grid item xs={12}>
  //                 <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
  //                   DELIVERY TIME FOR GOODS/SERVICES (%)
  //                 </Typography>
  //                 <Grid container spacing={2}>
  //                   <Grid item xs={12} sm={6}>
  //                     <TextField
  //                       fullWidth
  //                       label="Immediately"
  //                       type="number"
  //                       name="immediately"
  //                       value={business.immediately}
  //                       onChange={handleBusinessChange}
  //                       InputProps={{ endAdornment: '%' }}
  //                     />
  //                   </Grid>
  //                   <Grid item xs={12} sm={6}>
  //                     <TextField
  //                       fullWidth
  //                       label="Within 4 weeks"
  //                       type="number"
  //                       name="within_four_weeks"
  //                       value={business.within_four_weeks}
  //                       onChange={handleBusinessChange}
  //                       InputProps={{ endAdornment: '%' }}
  //                     />
  //                   </Grid>
  //                   <Grid item xs={12} sm={6}>
  //                     <TextField
  //                       fullWidth
  //                       label="Within 5-14 weeks"
  //                       type="number"
  //                       name="within_5_14_weeks"
  //                       value={business.within_5_14_weeks}
  //                       onChange={handleBusinessChange}
  //                       InputProps={{ endAdornment: '%' }}
  //                     />
  //                   </Grid>
  //                   <Grid item xs={12} sm={6}>
  //                     <TextField
  //                       fullWidth
  //                       label="More than 14 weeks"
  //                       type="number"
  //                       name="more_than_14_weeks"
  //                       value={business.more_than_14_weeks}
  //                       onChange={handleBusinessChange}
  //                       InputProps={{ endAdornment: '%' }}
  //                     />
  //                   </Grid>
  //                 </Grid>
  //               </Grid>

  //               <Grid item xs={12}>
  //                 <FormControl component="fieldset">
  //                   <FormLabel component="legend">When does payment take place?</FormLabel>
  //                   <Stack direction="row" spacing={2} flexWrap="wrap">
  //                     <FormControlLabel
  //                       control={
  //                         <Checkbox
  //                           checked={business.is_upon_purchase}
  //                           onChange={handleBusinessChange}
  //                           name="is_upon_purchase"
  //                         />
  //                       }
  //                       label="Upon purchase"
  //                     />
  //                     <FormControlLabel
  //                       control={
  //                         <Checkbox
  //                           checked={business.is_with_download}
  //                           onChange={handleBusinessChange}
  //                           name="is_with_download"
  //                         />
  //                       }
  //                       label="With download"
  //                     />
  //                     <FormControlLabel
  //                       control={
  //                         <Checkbox
  //                           checked={business.is_on_delivery}
  //                           onChange={handleBusinessChange}
  //                           name="is_on_delivery"
  //                         />
  //                       }
  //                       label="On delivery"
  //                     />
  //                     <FormControlLabel
  //                       control={
  //                         <Checkbox
  //                           checked={business.is_other_payment_option}
  //                           onChange={handleBusinessChange}
  //                           name="is_other_payment_option"
  //                         />
  //                       }
  //                       label="Other"
  //                     />
  //                   </Stack>
  //                 </FormControl>
  //                 {business.is_other_payment_option && (
  //                   <Box sx={{ mt: 2 }}>
  //                     <TextField
  //                       fullWidth
  //                       multiline
  //                       rows={3}
  //                       label="Please Provide Details"
  //                       name="other_payment_details"
  //                       value={business.other_payment_details}
  //                       onChange={handleBusinessChange}
  //                       placeholder="Please provide details about when payment takes place..."
  //                     />
  //                   </Box>
  //                 )}
  //               </Grid>

  //               {/* Card types applying for */}
  //               <Grid item xs={12}>
  //                 <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
  //                   Card types applying for
  //                 </Typography>
  //                 <Grid container spacing={2}>
  //                   {cardTypesList.map((card) => (
  //                     <Grid item xs={6} sm={4} md={3} key={card.id}>
  //                       <FormControlLabel
  //                         control={
  //                           <Checkbox
  //                             checked={selectedCardTypes.includes(card.id)}
  //                             onChange={() => handleCardTypeToggle(card.id)}
  //                           />
  //                         }
  //                         label={card.name}
  //                       />
  //                     </Grid>
  //                   ))}
  //                 </Grid>
  //                 {selectedCardTypes.includes(11) && (
  //                   <Box sx={{ mt: 2 }}>
  //                     <TextField
  //                       fullWidth
  //                       multiline
  //                       rows={2}
  //                       label="Other Card Details"
  //                       value={otherCardDetails}
  //                       onChange={(e) => setOtherCardDetails(e.target.value)}
  //                       placeholder="Please specify other card types..."
  //                     />
  //                   </Box>
  //                 )}
  //               </Grid>

  //               <Grid item xs={12}>
  //                 <FormControlLabel
  //                   control={
  //                     <Switch
  //                       checked={business.is_offer_affiliate_prog}
  //                       onChange={handleBusinessChange}
  //                       name="is_offer_affiliate_prog"
  //                     />
  //                   }
  //                   label="Do you offer / make use of affiliate programs?"
  //                 />
  //                 {business.is_offer_affiliate_prog && (
  //                   <Box sx={{ mt: 2, ml: 4 }}>
  //                     <TextField
  //                       fullWidth
  //                       multiline
  //                       rows={3}
  //                       label="Please provide details"
  //                       name="offer_affiliate_prog_details"
  //                       value={business.offer_affiliate_prog_details}
  //                       onChange={handleBusinessChange}
  //                       placeholder="Please provide details about your affiliate programs..."
  //                     />
  //                   </Box>
  //                 )}
  //               </Grid>

  //               <Grid item xs={12}>
  //                 <FormControlLabel
  //                   control={
  //                     <Switch
  //                       checked={business.is_need_soft_service}
  //                       onChange={handleBusinessChange}
  //                       name="is_need_soft_service"
  //                     />
  //                   }
  //                   label="Need Software As A Service"
  //                 />
  //                 {business.is_need_soft_service && (
  //                   <Box sx={{ mt: 2, ml: 4 }}>
  //                     <TextField
  //                       fullWidth
  //                       multiline
  //                       rows={3}
  //                       label="Please provide details"
  //                       name="software_service_details"
  //                       value={business.software_service_details}
  //                       onChange={handleBusinessChange}
  //                       placeholder="Please provide details about your software requirements..."
  //                     />
  //                   </Box>
  //                 )}
  //               </Grid>
  //             </Grid>

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

  //             <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 BusinessProfile




// date calculate with incorpration and pass data through props ////////////////////////////////////////////
// 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 MenuItem from '@mui/material/MenuItem'
// import FormControlLabel from '@mui/material/FormControlLabel'
// import Checkbox from '@mui/material/Checkbox'
// 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 FormControl from '@mui/material/FormControl'
// import FormLabel from '@mui/material/FormLabel'
// import Chip from '@mui/material/Chip'

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

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

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

// interface CreditHistory {
//   months_ago: string
//   number_of_transaction: string
//   transaction_volume: string
//   number_of_chargeback: string
//   chargeback_volume: string
//   number_of_refunds: string
//   refund_volume: string
// }

// interface MerchantCategory {
//   id: number
//   uid: string
//   createdAt: string
//   updatedAt: string
//   name: string
//   code: string
//   isActive: boolean
// }

// interface CardType {
//   uid: string
//   cardType: string
//   cardName: string
// }

// interface CardTypeMapping {
//   id: number
//   uid: string
//   createdAt: string
//   updatedAt: string
//   cardtypeId: string
// }

// // Helper function to calculate length of time in business
// const calculateLengthOfTime = (incorporationDate: string): string => {
//   if (!incorporationDate) return 'Not available'
  
//   const start = new Date(incorporationDate)
//   const now = new Date()
  
//   let years = now.getFullYear() - start.getFullYear()
//   let months = now.getMonth() - start.getMonth()
//   let days = now.getDate() - start.getDate()
  
//   if (days < 0) {
//     months -= 1
//     const prevMonth = new Date(now.getFullYear(), now.getMonth(), 0)
//     days += prevMonth.getDate()
//   }
  
//   if (months < 0) {
//     years -= 1
//     months += 12
//   }
  
//   if (years < 0) {
//     const absYears = Math.abs(years)
//     const absMonths = Math.abs(months)
//     const absDays = Math.abs(days)
    
//     const parts: string[] = []
//     if (absYears > 0) parts.push(`${absYears} year${absYears > 1 ? 's' : ''}`)
//     if (absMonths > 0) parts.push(`${absMonths} month${absMonths > 1 ? 's' : ''}`)
//     if (absDays > 0) parts.push(`${absDays} day${absDays > 1 ? 's' : ''}`)
    
//     if (parts.length === 0) return 'Today'
//     return parts.join(', ')
//   }
  
//   const parts: string[] = []
//   if (years > 0) parts.push(`${years} year${years > 1 ? 's' : ''}`)
//   if (months > 0) parts.push(`${months} month${months > 1 ? 's' : ''}`)
//   if (days > 0) parts.push(`${days} day${days > 1 ? 's' : ''}`)
  
//   if (parts.length === 0) return 'Today'
//   return parts.join(', ')
// }

// const BusinessProfile = ({ onNext, onPrevious, applicationId }: BusinessProfileProps) => {
//   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)

//   // Dropdown data states
//   const [merchantCategories, setMerchantCategories] = useState<MerchantCategory[]>([])
//   const [cardTypesList, setCardTypesList] = useState<CardType[]>([])
//   const [loadingDropdowns, setLoadingDropdowns] = useState<boolean>(true)

//   // Main business state
//   const [business, setBusiness] = useState({
//     description_of_products: '',
//     length_of_time_business: '',
//     merchant_cat_code: '',
//     website: '',
//     descriptor: '',
//     city_field: '',
//     dynamic_descriptors: false,
//     field_for_bankruptcy: false,
//     field_for_bankruptcy_date: '',
//     accepted_credit_cards: false,
//     accepted_credit_cards_months: '',
//     card_scheme_program: false,
//     card_scheme_program_provide_details: '',
//     previous_payment_service_provider: '',
//     previous_acquirer: '',
//     leaving_current_acquirer: '',
//     monthly_sales_volume: '',
//     currency: '$',
//     avg_transaction_value: '',
//     highest_transaction_value: '',
//     one_time_payment: false,
//     recurring_payment: false,
//     domestic: '',
//     europe: '',
//     usa: '',
//     asia: '',
//     rest_of_world: '',
//     e_commerce: '',
//     card_present: '',
//     m_pos: '',
//     moto: '',
//     immediately: '',
//     within_four_weeks: '',
//     within_5_14_weeks: '',
//     more_than_14_weeks: '',
//     is_upon_purchase: false,
//     is_with_download: false,
//     is_on_delivery: false,
//     is_other_payment_option: false,
//     other_payment_details: '',
//     is_offer_affiliate_prog: false,
//     offer_affiliate_prog_details: '',
//     is_need_soft_service: false,
//     software_service_details: '',
//   })

//   // Beta website state
//   const [hasBetaSite, setHasBetaSite] = useState(false)
//   const [betaWebsite, setBetaWebsite] = useState('')
//   const [betaUsername, setBetaUsername] = useState('')
//   const [betaPassword, setBetaPassword] = useState('')
//   const [hasExistingPassword, setHasExistingPassword] = useState(false)
//   const [isEditingPassword, setIsEditingPassword] = useState(false)

//   // Credit card history - dynamic based on months entered (max 6)
//   const [creditCardHistory, setCreditCardHistory] = useState<CreditHistory[]>([])
//   const [savedCreditHistory, setSavedCreditHistory] = useState<CreditHistory[]>([])

//   // Show credit card history table
//   const [showCreditHistory, setShowCreditHistory] = useState<boolean>(false)
//   const [numberOfMonths, setNumberOfMonths] = useState<number>(0)

//   // Card types
//   const [selectedCardTypes, setSelectedCardTypes] = useState<string[]>([])
//   const [otherCardDetails, setOtherCardDetails] = useState('')

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

//   // Fetch dropdown data
//   useEffect(() => {
//     const fetchDropdownData = async () => {
//       try {
//         setLoadingDropdowns(true)
        
//         // Fetch merchant categories
//         const mccResponse = await axiosInstance.get(endpoints.merchantApplication.merchantcategory)
//         console.log('Merchant Categories Response:', mccResponse.data)
        
//         if (mccResponse.data && Array.isArray(mccResponse.data)) {
//           setMerchantCategories(mccResponse.data)
//         }

//         // Fetch card types
//         const cardResponse = await axiosInstance.get(endpoints.merchantApplication.cardtype)
//         console.log('Card Types Response:', cardResponse.data)
        
//         if (cardResponse.data && Array.isArray(cardResponse.data)) {
//           setCardTypesList(cardResponse.data)
//         }
//       } catch (err: any) {
//         console.error('Error fetching dropdown data:', err)
//         toast.error('Failed to load dropdown data')
//       } finally {
//         setLoadingDropdowns(false)
//       }
//     }

//     fetchDropdownData()
//   }, [])

//   // Initialize credit card history based on months
//   const initializeCreditHistory = (months: number, existingData?: CreditHistory[]) => {
//     const maxMonths = Math.min(months, 6)
//     const newHistory: CreditHistory[] = []
    
//     for (let i = 1; i <= maxMonths; i++) {
//       // If we have existing data and it's for this month index, use it
//       const existingEntry = existingData && i <= existingData.length 
//         ? existingData[i - 1] 
//         : null
      
//       newHistory.push({
//         months_ago: String(i),
//         number_of_transaction: existingEntry?.number_of_transaction || '',
//         transaction_volume: existingEntry?.transaction_volume || '',
//         number_of_chargeback: existingEntry?.number_of_chargeback || '',
//         chargeback_volume: existingEntry?.chargeback_volume || '',
//         number_of_refunds: existingEntry?.number_of_refunds || '',
//         refund_volume: existingEntry?.refund_volume || '',
//       })
//     }
    
//     setCreditCardHistory(newHistory)
//     setNumberOfMonths(maxMonths)
//   }

//   // Fetch existing business data
//   useEffect(() => {
//     if (applicationId) {
//       fetchBusinessData()
//     }
//   }, [applicationId])

//   const fetchBusinessData = 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 Business Response:', response.data)

//       // First, check if there's business profile data
//       if (response.data && response.data.businessProfile) {
//         const formData = response.data.businessProfile
//         console.log('Existing business data found:', formData)
//         setIsEditMode(true)
//         prefillFormData(formData)
//       } else {
//         console.log('No existing business data found')
//         setIsEditMode(false)
//       }

//       // Handle card types from the response
//       if (response.data && response.data.cardTypes && Array.isArray(response.data.cardTypes)) {
//         console.log('Card types from API:', response.data.cardTypes)
//         // Extract the cardtypeId from each card type mapping
//         const cardTypeIds = response.data.cardTypes.map((card: CardTypeMapping) => card.cardtypeId)
//         console.log('Card type IDs to select:', cardTypeIds)
//         setSelectedCardTypes(cardTypeIds)
//       }

//       // Handle other card details
//       if (response.data && response.data.businessProfile && response.data.businessProfile.otherCardDetails) {
//         setOtherCardDetails(response.data.businessProfile.otherCardDetails)
//         console.log('Other card details found:', response.data.businessProfile.otherCardDetails)
//       }

//       // Now check for incorporation date from company profile to calculate length of time
//       if (response.data && response.data.companyProfile && Array.isArray(response.data.companyProfile)) {
//         const mainCompany = response.data.companyProfile.find((item: any) => item.isparent === false || item.isparent === null)
//         if (mainCompany && mainCompany.incorporationDate) {
//           const calculatedLength = calculateLengthOfTime(mainCompany.incorporationDate)
//           if (calculatedLength) {
//             setBusiness(prev => ({
//               ...prev,
//               length_of_time_business: calculatedLength
//             }))
//             console.log('Calculated length of time from incorporation date:', calculatedLength)
//           }
//         }
//       }
//     } catch (err: any) {
//       console.error('Error fetching business data:', err)
//       if (err.response?.status === 404) {
//         console.log('No business record found, will create new on submit')
//         setIsEditMode(false)
//       } else {
//         toast.error('Failed to load business data')
//       }
//     } finally {
//       setFetchingData(false)
//     }
//   }

//   const prefillFormData = (data: any) => {
//     console.log('Prefilling business data:', data)

//     if (data.descriptionOfProducts) {
//       setBusiness(prev => ({ ...prev, description_of_products: data.descriptionOfProducts }))
//     }
//     if (data.lengthOfBusiness) {
//       setBusiness(prev => ({ ...prev, length_of_time_business: data.lengthOfBusiness }))
//     }
//     if (data.merchantCategoryCode) {
//       setBusiness(prev => ({ ...prev, merchant_cat_code: data.merchantCategoryCode }))
//     }
//     if (data.website) {
//       setBusiness(prev => ({ ...prev, website: data.website }))
//     }
//     if (data.betaWebsite) {
//       setHasBetaSite(true)
//       setBetaWebsite(data.betaWebsite)
//     }
//     if (data.username) {
//       setBetaUsername(data.username)
//     }
//     if (data.password) {
//       setHasExistingPassword(true)
//       setIsEditingPassword(false)
//       setBetaPassword('')
//     } else {
//       setHasExistingPassword(false)
//       setBetaPassword('')
//     }
//     if (data.descriptor !== undefined && data.descriptor !== null) {
//       setBusiness(prev => ({ ...prev, descriptor: data.descriptor || '' }))
//     }
//     if (data.cityField) {
//       setBusiness(prev => ({ ...prev, city_field: data.cityField }))
//     }
//     if (data.isDynamicDescriptor !== undefined) {
//       setBusiness(prev => ({ ...prev, dynamic_descriptors: data.isDynamicDescriptor }))
//     }
//     if (data.isBankruptcy !== undefined) {
//       setBusiness(prev => ({ ...prev, field_for_bankruptcy: data.isBankruptcy }))
//     }
//     if (data.fieldForBankruptcyDate) {
//       setBusiness(prev => ({ ...prev, field_for_bankruptcy_date: data.fieldForBankruptcyDate }))
//     }
//     if (data.isAcceptedCreditCards !== undefined) {
//       setBusiness(prev => ({ ...prev, accepted_credit_cards: data.isAcceptedCreditCards }))
//     }
    
//     // Handle credit card history first to save the data
//     let savedHistory: CreditHistory[] = []
//     if (data.creditCardHistory && Array.isArray(data.creditCardHistory) && data.creditCardHistory.length > 0) {
//       savedHistory = data.creditCardHistory.map((item: any) => ({
//         months_ago: item.months_ago || '',
//         number_of_transaction: item.number_of_transaction || item.numberOfTransaction || '',
//         transaction_volume: item.transaction_volume || item.transactionVolume || '',
//         number_of_chargeback: item.number_of_chargeback || item.numberOfChargeback || '',
//         chargeback_volume: item.chargeback_volume || item.chargebackVolume || '',
//         number_of_refunds: item.number_of_refunds || item.numberOfRefunds || '',
//         refund_volume: item.refund_volume || item.refundVolume || '',
//       }))
//     }
    
//     // Save the credit history data
//     if (savedHistory.length > 0) {
//       setSavedCreditHistory(savedHistory)
//     }
    
//     // Now set the months and initialize history
//     if (data.acceptedCreditCardMonths) {
//       const months = parseInt(data.acceptedCreditCardMonths)
//       setBusiness(prev => ({ ...prev, accepted_credit_cards_months: String(months) }))
//       if (months > 0) {
//         setShowCreditHistory(true)
//         // Use saved history to initialize
//         initializeCreditHistory(months, savedHistory.length > 0 ? savedHistory : undefined)
//       }
//     } else if (savedHistory.length > 0) {
//       // If no months set but we have history, set months to history length
//       const months = Math.min(savedHistory.length, 6)
//       setBusiness(prev => ({ ...prev, accepted_credit_cards_months: String(months) }))
//       setShowCreditHistory(true)
//       initializeCreditHistory(months, savedHistory)
//     }

//     if (data.hasCardSchemeProgram !== undefined) {
//       setBusiness(prev => ({ ...prev, card_scheme_program: data.hasCardSchemeProgram }))
//     }
//     if (data.cardSchemeProgramDetails && data.cardSchemeProgramDetails !== 'NA') {
//       setBusiness(prev => ({ ...prev, card_scheme_program_provide_details: data.cardSchemeProgramDetails }))
//     }
//     if (data.previousPaymentServiceProvider) {
//       setBusiness(prev => ({ ...prev, previous_payment_service_provider: data.previousPaymentServiceProvider }))
//     }
//     if (data.previousAcquirer) {
//       setBusiness(prev => ({ ...prev, previous_acquirer: data.previousAcquirer }))
//     }
//     if (data.reasonForLeavingAcquirer) {
//       setBusiness(prev => ({ ...prev, leaving_current_acquirer: data.reasonForLeavingAcquirer }))
//     }
//     if (data.monthlySalesVolume !== undefined && data.monthlySalesVolume !== null) {
//       setBusiness(prev => ({ ...prev, monthly_sales_volume: String(data.monthlySalesVolume) }))
//     }
//     if (data.salesCurrency) {
//       setBusiness(prev => ({ ...prev, currency: data.salesCurrency }))
//     }
//     if (data.avgTransValue !== undefined && data.avgTransValue !== null) {
//       setBusiness(prev => ({ ...prev, avg_transaction_value: String(data.avgTransValue) }))
//     }
//     if (data.highestTransValue !== undefined && data.highestTransValue !== null) {
//       setBusiness(prev => ({ ...prev, highest_transaction_value: String(data.highestTransValue) }))
//     }
//     if (data.oneTimePayment !== undefined) {
//       setBusiness(prev => ({ ...prev, one_time_payment: data.oneTimePayment }))
//     }
//     if (data.recurringPayment !== undefined) {
//       setBusiness(prev => ({ ...prev, recurring_payment: data.recurringPayment }))
//     }
//     if (data.domestic !== undefined && data.domestic !== null) {
//       setBusiness(prev => ({ ...prev, domestic: String(data.domestic) }))
//     }
//     if (data.europe !== undefined && data.europe !== null) {
//       setBusiness(prev => ({ ...prev, europe: String(data.europe) }))
//     }
//     if (data.usa !== undefined && data.usa !== null) {
//       setBusiness(prev => ({ ...prev, usa: String(data.usa) }))
//     }
//     if (data.asia !== undefined && data.asia !== null) {
//       setBusiness(prev => ({ ...prev, asia: String(data.asia) }))
//     }
//     if (data.restOfWorld !== undefined && data.restOfWorld !== null) {
//       setBusiness(prev => ({ ...prev, rest_of_world: String(data.restOfWorld) }))
//     }
//     if (data.ecommerce !== undefined && data.ecommerce !== null) {
//       setBusiness(prev => ({ ...prev, e_commerce: String(data.ecommerce) }))
//     }
//     if (data.cardPresent !== undefined && data.cardPresent !== null) {
//       setBusiness(prev => ({ ...prev, card_present: String(data.cardPresent) }))
//     }
//     if (data.mpos !== undefined && data.mpos !== null) {
//       setBusiness(prev => ({ ...prev, m_pos: String(data.mpos) }))
//     }
//     if (data.moto !== undefined && data.moto !== null) {
//       setBusiness(prev => ({ ...prev, moto: String(data.moto) }))
//     }
//     if (data.immediately !== undefined && data.immediately !== null) {
//       setBusiness(prev => ({ ...prev, immediately: String(data.immediately) }))
//     }
//     if (data.withinFourWeeks !== undefined && data.withinFourWeeks !== null) {
//       setBusiness(prev => ({ ...prev, within_four_weeks: String(data.withinFourWeeks) }))
//     }
//     if (data.within5To14Weeks !== undefined && data.within5To14Weeks !== null) {
//       setBusiness(prev => ({ ...prev, within_5_14_weeks: String(data.within5To14Weeks) }))
//     }
//     if (data.moreThan14Weeks !== undefined && data.moreThan14Weeks !== null) {
//       setBusiness(prev => ({ ...prev, more_than_14_weeks: String(data.moreThan14Weeks) }))
//     }
//     if (data.isUponPurchase !== undefined) {
//       setBusiness(prev => ({ ...prev, is_upon_purchase: data.isUponPurchase }))
//     }
//     if (data.isWithDownload !== undefined) {
//       setBusiness(prev => ({ ...prev, is_with_download: data.isWithDownload }))
//     }
//     if (data.isonDelivery !== undefined) {
//       setBusiness(prev => ({ ...prev, is_on_delivery: data.isonDelivery }))
//     }
//     if (data.isOtherPaymentOption !== undefined) {
//       setBusiness(prev => ({ ...prev, is_other_payment_option: data.isOtherPaymentOption }))
//     }
//     if (data.otherPaymentDetails && data.otherPaymentDetails !== 'NA') {
//       setBusiness(prev => ({ ...prev, other_payment_details: data.otherPaymentDetails }))
//     }
//     if (data.isOfferAffiliateProg !== undefined) {
//       setBusiness(prev => ({ ...prev, is_offer_affiliate_prog: data.isOfferAffiliateProg }))
//     }
//     if (data.offerAffiliateProgDetails && data.offerAffiliateProgDetails !== 'NA') {
//       setBusiness(prev => ({ ...prev, offer_affiliate_prog_details: data.offerAffiliateProgDetails }))
//     }
//     if (data.isNeedSoftwService !== undefined) {
//       setBusiness(prev => ({ ...prev, is_need_soft_service: data.isNeedSoftwService }))
//     }
//     if (data.softwareServDetails && data.softwareServDetails !== 'NA') {
//       setBusiness(prev => ({ ...prev, software_service_details: data.softwareServDetails }))
//     }
//   }

//   const handleBusinessChange = (e: React.ChangeEvent<HTMLInputElement>) => {
//     const { name, value, type, checked } = e.target
    
//     if (name === 'accepted_credit_cards_months') {
//       const numValue = parseInt(value) || 0
//       setBusiness(prev => ({ ...prev, [name]: value }))
      
//       if (numValue > 0 && business.accepted_credit_cards) {
//         const maxMonths = Math.min(numValue, 6)
//         setShowCreditHistory(true)
        
//         // Use saved credit history to preserve data
//         const existingData = savedCreditHistory.length > 0 ? savedCreditHistory : creditCardHistory
        
//         // Create new history with preserved data
//         const newHistory: CreditHistory[] = []
//         for (let i = 1; i <= maxMonths; i++) {
//           const existingEntry = existingData && i <= existingData.length 
//             ? existingData[i - 1] 
//             : null
          
//           newHistory.push({
//             months_ago: String(i),
//             number_of_transaction: existingEntry?.number_of_transaction || '',
//             transaction_volume: existingEntry?.transaction_volume || '',
//             number_of_chargeback: existingEntry?.number_of_chargeback || '',
//             chargeback_volume: existingEntry?.chargeback_volume || '',
//             number_of_refunds: existingEntry?.number_of_refunds || '',
//             refund_volume: existingEntry?.refund_volume || '',
//           })
//         }
        
//         setCreditCardHistory(newHistory)
//         setNumberOfMonths(maxMonths)
        
//         // Update saved history if we're increasing months
//         if (numValue > creditCardHistory.length) {
//           setSavedCreditHistory(newHistory)
//         }
//       } else {
//         setShowCreditHistory(false)
//         setCreditCardHistory([])
//         setNumberOfMonths(0)
//       }
      
//       if (errors[name]) {
//         setErrors(prev => ({ ...prev, [name]: '' }))
//       }
//       return
//     }

//     if (name === 'length_of_time_business') {
//       return
//     }

//     setBusiness(prev => ({
//       ...prev,
//       [name]: type === 'checkbox' ? checked : value
//     }))

//     if (name === 'accepted_credit_cards' && !checked) {
//       setShowCreditHistory(false)
//       setCreditCardHistory([])
//       setSavedCreditHistory([])
//       setNumberOfMonths(0)
//     }

//     if (errors[name]) {
//       setErrors(prev => ({ ...prev, [name]: '' }))
//     }
//   }

//   const handleCreditHistoryChange = (index: number, field: string, value: string) => {
//     const newHistory = [...creditCardHistory]
//     newHistory[index] = { ...newHistory[index], [field]: value }
//     setCreditCardHistory(newHistory)
//     // Also update saved history to preserve changes
//     setSavedCreditHistory(newHistory)
//   }

//   const handleCardTypeToggle = (cardUid: string) => {
//     setSelectedCardTypes(prev =>
//       prev.includes(cardUid)
//         ? prev.filter(id => id !== cardUid)
//         : [...prev, cardUid]
//     )
//   }

//   const handleEditPassword = () => {
//     setIsEditingPassword(true)
//     setBetaPassword('')
//   }

//   const handleCancelEditPassword = () => {
//     setIsEditingPassword(false)
//     setBetaPassword('')
//   }

//   const buildRequestBody = () => {
//     const requestBody: any = {
//       application_id: parseInt(applicationId),
//       description_of_products: business.description_of_products || '',
//       length_of_time_business: business.length_of_time_business || '',
//       merchant_cat_code: business.merchant_cat_code || '',
//       website: business.website || '',
//       descriptor: business.descriptor || '',
//       city_field: business.city_field || '',
//       dynamic_descriptors: business.dynamic_descriptors,
//       field_for_bankruptcy: business.field_for_bankruptcy,
//       field_for_bankruptcy_date: business.field_for_bankruptcy_date || '',
//       accepted_credit_cards: business.accepted_credit_cards,
//       accepted_credit_cards_months: business.accepted_credit_cards_months || '',
//       card_scheme_program: business.card_scheme_program,
//       card_scheme_program_provide_details: business.card_scheme_program_provide_details || '',
//       previous_payment_service_provider: business.previous_payment_service_provider || '',
//       previous_acquirer: business.previous_acquirer || '',
//       leaving_current_acquirer: business.leaving_current_acquirer || '',
//       monthly_sales_volume: business.monthly_sales_volume || '',
//       currency: business.currency || '$',
//       avg_transaction_value: business.avg_transaction_value || '',
//       highest_transaction_value: business.highest_transaction_value || '',
//       one_time_payment: business.one_time_payment,
//       recurring_payment: business.recurring_payment,
//       domestic: business.domestic || '',
//       europe: business.europe || '',
//       usa: business.usa || '',
//       asia: business.asia || '',
//       rest_of_world: business.rest_of_world || '',
//       e_commerce: business.e_commerce || '',
//       card_present: business.card_present || '',
//       m_pos: business.m_pos || '',
//       moto: business.moto || '',
//       immediately: business.immediately || '',
//       within_four_weeks: business.within_four_weeks || '',
//       within_5_14_weeks: business.within_5_14_weeks || '',
//       more_than_14_weeks: business.more_than_14_weeks || '',
//       is_upon_purchase: business.is_upon_purchase,
//       is_with_download: business.is_with_download,
//       is_on_delivery: business.is_on_delivery,
//       is_other_payment_option: business.is_other_payment_option,
//       other_payment_details: business.other_payment_details || '',
//       is_offer_affiliate_prog: business.is_offer_affiliate_prog,
//       offer_affiliate_prog_details: business.offer_affiliate_prog_details || '',
//       is_need_soft_service: business.is_need_soft_service,
//       software_service_details: business.software_service_details || '',
//     }

//     if (hasBetaSite) {
//       requestBody.beta_website = betaWebsite || ''
//       requestBody.username = betaUsername || ''
      
//       // Only send password if it's being edited or it's a new entry
//       if (isEditingPassword && betaPassword) {
//         requestBody.password = betaPassword
//       } else if (!hasExistingPassword && betaPassword) {
//         requestBody.password = betaPassword
//       } else if (!isEditingPassword && hasExistingPassword) {
//         // Keep existing password
//         requestBody.password = 'True'
//       }
//     }

//     if (business.accepted_credit_cards && parseInt(business.accepted_credit_cards_months) > 0 && creditCardHistory.length > 0) {
//       const historyWithMonths = creditCardHistory.map(({ months_ago, number_of_transaction, transaction_volume, number_of_chargeback, chargeback_volume, number_of_refunds, refund_volume }) => ({
//         months_ago: parseInt(months_ago),
//         number_of_transaction: number_of_transaction || '0',
//         transaction_volume: transaction_volume || '0',
//         number_of_chargeback: number_of_chargeback || '0',
//         chargeback_volume: chargeback_volume || '0',
//         number_of_refunds: number_of_refunds || '0',
//         refund_volume: refund_volume || '0',
//       }))
//       requestBody.credit_card_history = historyWithMonths
//     }

//     if (selectedCardTypes && selectedCardTypes.length > 0) {
//       requestBody.card_type = selectedCardTypes
//     }

//     // Check if "Other" card type is selected - use camelCase for backend
//     const otherCard = cardTypesList.find(card => card.cardName === 'Other' || card.cardType === 'Other')
//     if (otherCard && selectedCardTypes.includes(otherCard.uid) && otherCardDetails) {
//       requestBody.otherCardDetails = otherCardDetails
//     }

//     return requestBody
//   }

//   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('Application ID:', applicationId)
//     console.log('Request Body:', JSON.stringify(requestBody, null, 2))

//     try {
//       let response

//       if (isEditMode) {
//         response = await axiosInstance.put(
//           `${endpoints.merchantApplication.businessProfile}${applicationId}`,
//           requestBody
//         )
//         console.log('PUT Response:', response.data)
//         toast.success('Business profile updated successfully!')
//       } else {
//         response = await axiosInstance.post(
//           endpoints.merchantApplication.businessProfile,
//           requestBody
//         )
//         console.log('POST Response:', response.data)
//         toast.success('Business profile created successfully!')
//         setIsEditMode(true)
//       }

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

//       let errorMessage = isEditMode
//         ? 'Failed to update business profile. Please try again.'
//         : 'Failed to create business profile. 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)
//     }
//   }

//   const getMonthSuffix = (num: number) => {
//     if (num === 1) return '1st'
//     if (num === 2) return '2nd'
//     if (num === 3) return '3rd'
//     return `${num}th`
//   }

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

//   return (
//     <Box sx={{ bgcolor: 'background.default', minHeight: '100vh' }}>
//       <Card sx={{ borderRadius: 0, boxShadow: 'none' }}>
//         <form onSubmit={handleSubmit}>
//           <Box sx={{ p: 0 }}>
//             <Box sx={{ mb: 5 }}>
//               <Typography variant="h5" sx={{ fontWeight: 600, mb: 0.5, color: 'text.primary' }}>
//                 Business Profile Details
//               </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={{ mb: 4 }} />
//             </Box>

//             <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 severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
//                 {error}
//               </Alert>
//             )}

//             <Grid container spacing={3}>
//               <Grid item xs={12}>
//                 <TextField
//                   fullWidth
//                   multiline
//                   rows={3}
//                   name="description_of_products"
//                   label="Detailed Description of Products/Services Sold"
//                   value={business.description_of_products}
//                   onChange={handleBusinessChange}
//                   error={!!errors.description_of_products}
//                   helperText={errors.description_of_products}
//                   placeholder="Please provide a detailed description of the products or services your business sells..."
//                 />
//               </Grid>

//               <Grid item xs={12} sm={6}>
//                 <TextField
//                   fullWidth
//                   name="length_of_time_business"
//                   label="Length of time in business"
//                   value={business.length_of_time_business}
//                   onChange={handleBusinessChange}
//                   error={!!errors.length_of_time_business}
//                   helperText="Auto-calculated from incorporation date"
//                   placeholder="e.g., 5 years, 2 months, 10 days"
//                   InputProps={{
//                     readOnly: true,
//                     sx: { bgcolor: 'action.hover' }
//                   }}
//                 />
//               </Grid>

//               <Grid item xs={12} sm={6}>
//                 <TextField
//                   fullWidth
//                   select
//                   name="merchant_cat_code"
//                   label="Merchant Category (MCC)"
//                   value={business.merchant_cat_code}
//                   onChange={handleBusinessChange}
//                   error={!!errors.merchant_cat_code}
//                   helperText={errors.merchant_cat_code}
//                 >
//                   <MenuItem value="" disabled>Select</MenuItem>
//                   {merchantCategories.map((category) => (
//                     <MenuItem key={category.id} value={category.code}>
//                       {category.name} ({category.code})
//                     </MenuItem>
//                   ))}
//                 </TextField>
//               </Grid>

//               <Grid item xs={12}>
//                 <Grid container spacing={3} alignItems="flex-start">
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       name="website"
//                       label="Website(s) (Comma-Separated)"
//                       value={business.website}
//                       onChange={handleBusinessChange}
//                       error={!!errors.website}
//                       helperText={errors.website}
//                       placeholder="https://example.com, https://store.example.com"
//                     />
//                   </Grid>

//                   <Grid item xs={12} sm={6}>
//                     <FormControlLabel
//                       control={
//                         <Switch
//                           checked={hasBetaSite}
//                           onChange={(e) => setHasBetaSite(e.target.checked)}
//                         />
//                       }
//                       label="Beta Site(s)"
//                     />
//                     <Typography variant="body2" sx={{ color: 'text.secondary', ml: 2 }}>
//                       Toggle on to add website details
//                     </Typography>
//                   </Grid>

//                   {hasBetaSite && (
//                     <Grid item xs={12}>
//                       <Box sx={{ bgcolor: 'action.hover', borderRadius: 2, p: 3, mt: 1 }}>
//                         <Typography variant="h6" sx={{ fontWeight: 600, mb: 3 }}>
//                           Beta Website Details
//                         </Typography>
//                         <Grid container spacing={2}>
//                           <Grid item xs={12}>
//                             <TextField
//                               fullWidth
//                               label="Beta Website URL"
//                               value={betaWebsite}
//                               onChange={(e) => setBetaWebsite(e.target.value)}
//                               placeholder="https://beta.example.com"
//                             />
//                           </Grid>
//                           <Grid item xs={12} sm={6}>
//                             <TextField
//                               fullWidth
//                               label="Username"
//                               value={betaUsername}
//                               onChange={(e) => setBetaUsername(e.target.value)}
//                             />
//                           </Grid>
//                           <Grid item xs={12} sm={6}>
//                             <Box>
//                               <TextField
//                                 fullWidth
//                                 label="Password"
//                                 type="password"
//                                 value={betaPassword}
//                                 onChange={(e) => setBetaPassword(e.target.value)}
//                                 disabled={!isEditingPassword && hasExistingPassword}
//                                 placeholder={!isEditingPassword && hasExistingPassword ? "••••••••" : "Enter password"}
//                                 sx={{
//                                   '& .MuiInputBase-root': {
//                                     backgroundColor: !isEditingPassword && hasExistingPassword ? '#f5f5f5' : 'transparent',
//                                   }
//                                 }}
//                               />
//                               <Box sx={{ display: 'flex', gap: 1, mt: 1, alignItems: 'center', flexWrap: 'wrap' }}>
//                                 {hasExistingPassword && !isEditingPassword ? (
//                                   <>
//                                     <Chip 
//                                       label="✓ Password Set" 
//                                       color="success" 
//                                       size="small"
//                                     />
//                                     <Typography variant="caption" color="text.secondary">
//                                       Click
//                                     </Typography>
//                                     <Button
//                                       size="small"
//                                       variant="outlined"
//                                       color="primary"
//                                       onClick={handleEditPassword}
//                                       sx={{ minWidth: '80px', height: '30px' }}
//                                     >
//                                       Edit
//                                     </Button>
//                                     <Typography variant="caption" color="text.secondary">
//                                       to change password
//                                     </Typography>
//                                   </>
//                                 ) : hasExistingPassword && isEditingPassword ? (
//                                   <>
//                                     <Chip 
//                                       label="Editing Password" 
//                                       color="warning" 
//                                       size="small"
//                                     />
//                                     <Button
//                                       size="small"
//                                       variant="outlined"
//                                       color="error"
//                                       onClick={handleCancelEditPassword}
//                                       sx={{ minWidth: '80px', height: '30px' }}
//                                     >
//                                       Cancel
//                                     </Button>
//                                     <Typography variant="caption" color="warning.main">
//                                       Enter new password or cancel to keep existing
//                                     </Typography>
//                                   </>
//                                 ) : (
//                                   <Typography variant="caption" color="text.secondary">
//                                     Set a password for the beta site
//                                   </Typography>
//                                 )}
//                               </Box>
//                             </Box>
//                           </Grid>
//                         </Grid>
//                       </Box>
//                     </Grid>
//                   )}
//                 </Grid>
//               </Grid>

//               <Grid item xs={12} sm={6}>
//                 <TextField
//                   fullWidth
//                   name="descriptor"
//                   label="Credit Card Descriptor (Max 22 Char.)"
//                   value={business.descriptor}
//                   onChange={handleBusinessChange}
//                   error={!!errors.descriptor}
//                   helperText={errors.descriptor}
//                   inputProps={{ maxLength: 22 }}
//                 />
//               </Grid>

//               <Grid item xs={12} sm={6}>
//                 <TextField
//                   fullWidth
//                   name="city_field"
//                   label="DBA/City (Max 12 Char.)"
//                   value={business.city_field}
//                   onChange={handleBusinessChange}
//                   error={!!errors.city_field}
//                   helperText={errors.city_field}
//                   inputProps={{ maxLength: 12 }}
//                 />
//               </Grid>

//               <Grid item xs={12}>
//                 <FormControlLabel
//                   control={
//                     <Checkbox
//                       checked={business.dynamic_descriptors}
//                       onChange={handleBusinessChange}
//                       name="dynamic_descriptors"
//                     />
//                   }
//                   label="Will You use 'Dynamic Descriptor'"
//                 />
//               </Grid>

//               <Grid item xs={12}>
//                 <FormControlLabel
//                   control={
//                     <Checkbox
//                       checked={business.field_for_bankruptcy}
//                       onChange={handleBusinessChange}
//                       name="field_for_bankruptcy"
//                     />
//                   }
//                   label="Have you filed for bankruptcy before?"
//                 />
//                 {business.field_for_bankruptcy && (
//                   <Box sx={{ mt: 2, ml: 4 }}>
//                     <TextField
//                       fullWidth
//                       type="date"
//                       label="Date of Bankruptcy"
//                       name="field_for_bankruptcy_date"
//                       value={business.field_for_bankruptcy_date}
//                       onChange={handleBusinessChange}
//                       InputLabelProps={{ shrink: true }}
//                     />
//                   </Box>
//                 )}
//               </Grid>

//               <Grid item xs={12}>
//                 <FormControlLabel
//                   control={
//                     <Checkbox
//                       checked={business.accepted_credit_cards}
//                       onChange={handleBusinessChange}
//                       name="accepted_credit_cards"
//                     />
//                   }
//                   label="Have you previously accepted Credit Card payments?"
//                 />
//                 {business.accepted_credit_cards && (
//                   <Box sx={{ mt: 2, ml: 4 }}>
//                     <Grid container spacing={2}>
//                       <Grid item xs={12} sm={6}>
//                         <TextField
//                           fullWidth
//                           type="number"
//                           label="How Many Months (Max 6)"
//                           name="accepted_credit_cards_months"
//                           value={business.accepted_credit_cards_months}
//                           onChange={handleBusinessChange}
//                           placeholder="Enter number of months (max 6)"
//                           helperText="Enter 1-6 months to show credit history"
//                           inputProps={{ min: 0, max: 6 }}
//                         />
//                       </Grid>
//                       <Grid item xs={12} sm={6}>
//                         <TextField
//                           fullWidth
//                           label="Previous Payment Service Provider"
//                           name="previous_payment_service_provider"
//                           value={business.previous_payment_service_provider}
//                           onChange={handleBusinessChange}
//                           placeholder="Enter provider name"
//                         />
//                       </Grid>
//                       <Grid item xs={12} sm={6}>
//                         <TextField
//                           fullWidth
//                           label="Previous Acquirer"
//                           name="previous_acquirer"
//                           value={business.previous_acquirer}
//                           onChange={handleBusinessChange}
//                           placeholder="Enter acquirer name"
//                         />
//                       </Grid>
//                       <Grid item xs={12} sm={6}>
//                         <TextField
//                           fullWidth
//                           label="Reason for leaving current acquirer"
//                           name="leaving_current_acquirer"
//                           value={business.leaving_current_acquirer}
//                           onChange={handleBusinessChange}
//                           placeholder="Enter reason"
//                         />
//                       </Grid>
//                     </Grid>

//                     {showCreditHistory && creditCardHistory.length > 0 && (
//                       <Box sx={{ mt: 4 }}>
//                         <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, color: 'primary.main' }}>
//                           PLEASE PROVIDE {creditCardHistory.length} MONTH{creditCardHistory.length > 1 ? 'S' : ''} OF MOST RECENT PROCESSING HISTORY BELOW
//                         </Typography>
//                         <Box sx={{ overflowX: 'auto' }}>
//                           <table style={{ width: '100%', borderCollapse: 'collapse' }}>
//                             <thead>
//                               <tr style={{ backgroundColor: '#f5f5f5' }}>
//                                 <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '80px' }}>
//                                   MONTH
//                                 </th>
//                                 <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
//                                   Number of transactions
//                                 </th>
//                                 <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
//                                   Transaction volume
//                                 </th>
//                                 <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
//                                   Number of chargebacks
//                                 </th>
//                                 <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
//                                   Chargeback volume
//                                 </th>
//                                 <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
//                                   Number of refunds
//                                 </th>
//                                 <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
//                                   Refund volume
//                                 </th>
//                               </tr>
//                             </thead>
//                             <tbody>
//                               {creditCardHistory.map((history, index) => (
//                                 <tr key={index}>
//                                   <td style={{ padding: '12px', border: '1px solid #ddd', fontWeight: 500, textAlign: 'center' }}>
//                                     {getMonthSuffix(index + 1)}
//                                   </td>
//                                   <td style={{ padding: '8px', border: '1px solid #ddd' }}>
//                                     <TextField
//                                       fullWidth
//                                       type="number"
//                                       size="small"
//                                       value={history.number_of_transaction}
//                                       onChange={(e) => handleCreditHistoryChange(index, 'number_of_transaction', e.target.value)}
//                                       placeholder="0"
//                                     />
//                                   </td>
//                                   <td style={{ padding: '8px', border: '1px solid #ddd' }}>
//                                     <TextField
//                                       fullWidth
//                                       type="number"
//                                       size="small"
//                                       value={history.transaction_volume}
//                                       onChange={(e) => handleCreditHistoryChange(index, 'transaction_volume', e.target.value)}
//                                       placeholder="0"
//                                     />
//                                   </td>
//                                   <td style={{ padding: '8px', border: '1px solid #ddd' }}>
//                                     <TextField
//                                       fullWidth
//                                       type="number"
//                                       size="small"
//                                       value={history.number_of_chargeback}
//                                       onChange={(e) => handleCreditHistoryChange(index, 'number_of_chargeback', e.target.value)}
//                                       placeholder="0"
//                                     />
//                                   </td>
//                                   <td style={{ padding: '8px', border: '1px solid #ddd' }}>
//                                     <TextField
//                                       fullWidth
//                                       type="number"
//                                       size="small"
//                                       value={history.chargeback_volume}
//                                       onChange={(e) => handleCreditHistoryChange(index, 'chargeback_volume', e.target.value)}
//                                       placeholder="0"
//                                     />
//                                   </td>
//                                   <td style={{ padding: '8px', border: '1px solid #ddd' }}>
//                                     <TextField
//                                       fullWidth
//                                       type="number"
//                                       size="small"
//                                       value={history.number_of_refunds}
//                                       onChange={(e) => handleCreditHistoryChange(index, 'number_of_refunds', e.target.value)}
//                                       placeholder="0"
//                                     />
//                                   </td>
//                                   <td style={{ padding: '8px', border: '1px solid #ddd' }}>
//                                     <TextField
//                                       fullWidth
//                                       type="number"
//                                       size="small"
//                                       value={history.refund_volume}
//                                       onChange={(e) => handleCreditHistoryChange(index, 'refund_volume', e.target.value)}
//                                       placeholder="0"
//                                     />
//                                   </td>
//                                 </tr>
//                               ))}
//                             </tbody>
//                           </table>
//                         </Box>
//                       </Box>
//                     )}
//                   </Box>
//                 )}
//               </Grid>

//               <Grid item xs={12}>
//                 <FormControlLabel
//                   control={
//                     <Checkbox
//                       checked={business.card_scheme_program}
//                       onChange={handleBusinessChange}
//                       name="card_scheme_program"
//                     />
//                   }
//                   label="Have you ever flagged or been in violation of any card schema program?"
//                 />
//                 {business.card_scheme_program && (
//                   <Box sx={{ mt: 2, ml: 4 }}>
//                     <TextField
//                       fullWidth
//                       multiline
//                       rows={3}
//                       label="Please Provide Details"
//                       name="card_scheme_program_provide_details"
//                       value={business.card_scheme_program_provide_details}
//                       onChange={handleBusinessChange}
//                       placeholder="Please provide details about the violation..."
//                     />
//                   </Box>
//                 )}
//               </Grid>

//               <Grid item xs={12} sm={4}>
//                 <TextField
//                   fullWidth
//                   name="monthly_sales_volume"
//                   label="Estimated monthly sales volume"
//                   type="number"
//                   value={business.monthly_sales_volume}
//                   onChange={handleBusinessChange}
//                   placeholder="Enter amount"
//                   InputProps={{ startAdornment: <span>$ </span> }}
//                 />
//               </Grid>

//               <Grid item xs={12} sm={4}>
//                 <TextField
//                   fullWidth
//                   name="highest_transaction_value"
//                   label="Highest transaction value"
//                   type="number"
//                   value={business.highest_transaction_value}
//                   onChange={handleBusinessChange}
//                   placeholder="Enter amount"
//                   InputProps={{ startAdornment: <span>$ </span> }}
//                 />
//               </Grid>

//               <Grid item xs={12} sm={4}>
//                 <TextField
//                   fullWidth
//                   name="avg_transaction_value"
//                   label="Average transaction value"
//                   type="number"
//                   value={business.avg_transaction_value}
//                   onChange={handleBusinessChange}
//                   placeholder="Enter amount"
//                   InputProps={{ startAdornment: <span>$ </span> }}
//                 />
//               </Grid>

//               <Grid item xs={12} sm={6}>
//                 <FormControl component="fieldset">
//                   <FormLabel component="legend">Payment frequency</FormLabel>
//                   <Stack direction="row" spacing={2}>
//                     <FormControlLabel
//                       control={
//                         <Checkbox
//                           checked={business.one_time_payment}
//                           onChange={handleBusinessChange}
//                           name="one_time_payment"
//                         />
//                       }
//                       label="One-time payment"
//                     />
//                     <FormControlLabel
//                       control={
//                         <Checkbox
//                           checked={business.recurring_payment}
//                           onChange={handleBusinessChange}
//                           name="recurring_payment"
//                         />
//                       }
//                       label="Recurring payment"
//                     />
//                   </Stack>
//                 </FormControl>
//               </Grid>

//               <Grid item xs={12}>
//                 <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
//                   ORIGIN OF TRANSACTIONS (%)
//                 </Typography>
//                 <Grid container spacing={2}>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="Domestic"
//                       type="number"
//                       name="domestic"
//                       value={business.domestic}
//                       onChange={handleBusinessChange}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="Europe"
//                       type="number"
//                       name="europe"
//                       value={business.europe}
//                       onChange={handleBusinessChange}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="USA (Oceania)"
//                       type="number"
//                       name="usa"
//                       value={business.usa}
//                       onChange={handleBusinessChange}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="Asia"
//                       type="number"
//                       name="asia"
//                       value={business.asia}
//                       onChange={handleBusinessChange}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="Rest of world"
//                       type="number"
//                       name="rest_of_world"
//                       value={business.rest_of_world}
//                       onChange={handleBusinessChange}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                 </Grid>
//               </Grid>

//               <Grid item xs={12}>
//                 <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
//                   METHOD OF ACCEPTANCE (%)
//                 </Typography>
//                 <Grid container spacing={2}>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="E-commerce / M-Commerce"
//                       type="number"
//                       name="e_commerce"
//                       value={business.e_commerce}
//                       onChange={handleBusinessChange}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="Card Present (POS)"
//                       type="number"
//                       name="card_present"
//                       value={business.card_present}
//                       onChange={handleBusinessChange}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="M-Pos (Mobile POS)"
//                       type="number"
//                       name="m_pos"
//                       value={business.m_pos}
//                       onChange={handleBusinessChange}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="MOTO"
//                       type="number"
//                       name="moto"
//                       value={business.moto}
//                       onChange={handleBusinessChange}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                 </Grid>
//               </Grid>

//               <Grid item xs={12}>
//                 <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
//                   DELIVERY TIME FOR GOODS/SERVICES (%)
//                 </Typography>
//                 <Grid container spacing={2}>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="Immediately"
//                       type="number"
//                       name="immediately"
//                       value={business.immediately}
//                       onChange={handleBusinessChange}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="Within 4 weeks"
//                       type="number"
//                       name="within_four_weeks"
//                       value={business.within_four_weeks}
//                       onChange={handleBusinessChange}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="Within 5-14 weeks"
//                       type="number"
//                       name="within_5_14_weeks"
//                       value={business.within_5_14_weeks}
//                       onChange={handleBusinessChange}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                   <Grid item xs={12} sm={6}>
//                     <TextField
//                       fullWidth
//                       label="More than 14 weeks"
//                       type="number"
//                       name="more_than_14_weeks"
//                       value={business.more_than_14_weeks}
//                       onChange={handleBusinessChange}
//                       InputProps={{ endAdornment: '%' }}
//                     />
//                   </Grid>
//                 </Grid>
//               </Grid>

//               <Grid item xs={12}>
//                 <FormControl component="fieldset">
//                   <FormLabel component="legend">When does payment take place?</FormLabel>
//                   <Stack direction="row" spacing={2} flexWrap="wrap">
//                     <FormControlLabel
//                       control={
//                         <Checkbox
//                           checked={business.is_upon_purchase}
//                           onChange={handleBusinessChange}
//                           name="is_upon_purchase"
//                         />
//                       }
//                       label="Upon purchase"
//                     />
//                     <FormControlLabel
//                       control={
//                         <Checkbox
//                           checked={business.is_with_download}
//                           onChange={handleBusinessChange}
//                           name="is_with_download"
//                         />
//                       }
//                       label="With download"
//                     />
//                     <FormControlLabel
//                       control={
//                         <Checkbox
//                           checked={business.is_on_delivery}
//                           onChange={handleBusinessChange}
//                           name="is_on_delivery"
//                         />
//                       }
//                       label="On delivery"
//                     />
//                     <FormControlLabel
//                       control={
//                         <Checkbox
//                           checked={business.is_other_payment_option}
//                           onChange={handleBusinessChange}
//                           name="is_other_payment_option"
//                         />
//                       }
//                       label="Other"
//                     />
//                   </Stack>
//                 </FormControl>
//                 {business.is_other_payment_option && (
//                   <Box sx={{ mt: 2 }}>
//                     <TextField
//                       fullWidth
//                       multiline
//                       rows={3}
//                       label="Please Provide Details"
//                       name="other_payment_details"
//                       value={business.other_payment_details}
//                       onChange={handleBusinessChange}
//                       placeholder="Please provide details about when payment takes place..."
//                     />
//                   </Box>
//                 )}
//               </Grid>

//               <Grid item xs={12}>
//                 <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
//                   Card types applying for
//                 </Typography>
//                 <Grid container spacing={2}>
//                   {cardTypesList.map((card) => (
//                     <Grid item xs={6} sm={4} md={3} key={card.uid}>
//                       <FormControlLabel
//                         control={
//                           <Checkbox
//                             checked={selectedCardTypes.includes(card.uid)}
//                             onChange={() => handleCardTypeToggle(card.uid)}
//                           />
//                         }
//                         label={card.cardName || card.cardType}
//                       />
//                     </Grid>
//                   ))}
//                 </Grid>
//                 {selectedCardTypes.some(uid => {
//                   const card = cardTypesList.find(c => c.uid === uid)
//                   return card && (card.cardName === 'Other' || card.cardType === 'Other')
//                 }) && (
//                   <Box sx={{ mt: 2 }}>
//                     <TextField
//                       fullWidth
//                       multiline
//                       rows={2}
//                       label="Other Card Details"
//                       value={otherCardDetails}
//                       onChange={(e) => setOtherCardDetails(e.target.value)}
//                       placeholder="Please specify other card types..."
//                     />
//                   </Box>
//                 )}
//               </Grid>

//               <Grid item xs={12}>
//                 <FormControlLabel
//                   control={
//                     <Switch
//                       checked={business.is_offer_affiliate_prog}
//                       onChange={handleBusinessChange}
//                       name="is_offer_affiliate_prog"
//                     />
//                   }
//                   label="Do you offer / make use of affiliate programs?"
//                 />
//                 {business.is_offer_affiliate_prog && (
//                   <Box sx={{ mt: 2, ml: 4 }}>
//                     <TextField
//                       fullWidth
//                       multiline
//                       rows={3}
//                       label="Please provide details"
//                       name="offer_affiliate_prog_details"
//                       value={business.offer_affiliate_prog_details}
//                       onChange={handleBusinessChange}
//                       placeholder="Please provide details about your affiliate programs..."
//                     />
//                   </Box>
//                 )}
//               </Grid>

//               <Grid item xs={12}>
//                 <FormControlLabel
//                   control={
//                     <Switch
//                       checked={business.is_need_soft_service}
//                       onChange={handleBusinessChange}
//                       name="is_need_soft_service"
//                     />
//                   }
//                   label="Need Software As A Service"
//                 />
//                 {business.is_need_soft_service && (
//                   <Box sx={{ mt: 2, ml: 4 }}>
//                     <TextField
//                       fullWidth
//                       multiline
//                       rows={3}
//                       label="Please provide details"
//                       name="software_service_details"
//                       value={business.software_service_details}
//                       onChange={handleBusinessChange}
//                       placeholder="Please provide details about your software requirements..."
//                     />
//                   </Box>
//                 )}
//               </Grid>
//             </Grid>

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

//             <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 BusinessProfile

// 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 MenuItem from '@mui/material/MenuItem'
// import FormControlLabel from '@mui/material/FormControlLabel'
// import Checkbox from '@mui/material/Checkbox'
// 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 FormControl from '@mui/material/FormControl'
// import FormLabel from '@mui/material/FormLabel'

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

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

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

// interface CreditHistory {
//   months_ago: string
//   number_of_transaction: string
//   transaction_volume: string
//   number_of_chargeback: string
//   chargeback_volume: string
//   number_of_refunds: string
//   refund_volume: string
// }

// interface MerchantCategory {
//   id: number
//   uid: string
//   createdAt: string
//   updatedAt: string
//   name: string
//   code: string
//   isActive: boolean
// }

// interface CardType {
//   uid: string
//   cardType: string
//   cardName: string
// }

// interface CardTypeMapping {
//   id: number
//   uid: string
//   createdAt: string
//   updatedAt: string
//   cardtypeId: string
// }

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

// const validateDescription = (val: string): string => {
//   if (!val) return ''
//   if (val.trim().length < 10)
//     return 'Please provide at least 10 characters of detail. e.g. We sell electronics and provide repair services.'
//   if (val.trim().length > 2000)
//     return 'Description must not exceed 2000 characters.'
//   if (/[<>@#\\]/.test(val))
//     return 'Special characters like < > @ # \\ are not allowed.'
//   return ''
// }

// const validateWebsite = (val: string): string => {
//   if (!val) return ''
//   const urls = val.split(',').map(u => u.trim())
//   for (const url of urls) {
//     if (url && !/^https?:\/\/[^\s]+$/.test(url))
//       return 'Please enter valid URLs starting with http:// or https://. e.g. https://example.com'
//   }
//   return ''
// }

// const validateDescriptor = (val: string): string => {
//   if (!val) return ''
//   if (val.trim().length > 22)
//     return 'Descriptor must not exceed 22 characters.'
//   if (/[<>@#\\]/.test(val))
//     return 'Special characters like < > @ # \\ are not allowed.'
//   return ''
// }

// const validateCityField = (val: string): string => {
//   if (!val) return ''
//   if (val.trim().length > 12)
//     return 'DBA/City must not exceed 12 characters.'
//   if (!/^[A-Za-zÀ-ÿ\s'\-]+$/.test(val.trim()))
//     return 'Only letters, spaces, hyphens and apostrophes are allowed.'
//   return ''
// }

// const validateMonthlySales = (val: string): string => {
//   if (!val) return ''
//   if (!/^\d+(\.\d{1,2})?$/.test(val.trim()))
//     return 'Please enter a valid numeric amount. e.g. 10000 or 25000.50'
//   if (parseFloat(val) <= 0)
//     return 'Amount must be greater than 0.'
//   return ''
// }

// const validatePercentage = (val: string): string => {
//   if (!val) return ''
//   if (!/^\d+(\.\d{1,2})?$/.test(val.trim()))
//     return 'Please enter a valid number. e.g. 25 or 50.5'
//   const num = parseFloat(val)
//   if (num < 0 || num > 100)
//     return 'Please enter a value between 0 and 100.'
//   return ''
// }

// const validateMonths = (val: string): string => {
//   if (!val) return ''
//   if (!/^\d+$/.test(val.trim()))
//     return 'Please enter a valid number. e.g. 3'
//   const num = parseInt(val)
//   if (num < 1 || num > 6)
//     return 'Please enter a number between 1 and 6.'
//   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,
//   required,
//   inputProps,
// }: 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}
//         required={required}
//         inputProps={inputProps}
//         sx={{
//           '& .MuiOutlinedInput-root': {
//             '& fieldset': { borderColor: isEditMode && filled ? '#A5D6A7' : undefined },
//             '&:hover fieldset': { borderColor: isEditMode && filled ? '#66BB6A' : undefined },
//           },
//         }}
//       >
//         {children}
//       </TextField>
//     </Box>
//   )
// }

// // ─── SmartCheckbox ────────────────────────────────────────────────────────────
// const SmartCheckbox = ({
//   label,
//   checked,
//   onChange,
//   name,
//   isEditMode,
// }: {
//   label: string
//   checked: boolean
//   onChange: (e: React.ChangeEvent<HTMLInputElement>) => void
//   name: string
//   isEditMode: boolean
// }) => {
//   return (
//     <FormControlLabel
//       control={
//         <Checkbox
//           checked={checked}
//           onChange={onChange}
//           name={name}
//           sx={{
//             '&.Mui-checked': {
//               color: isEditMode ? '#2e7d32' : undefined,
//             },
//           }}
//         />
//       }
//       label={label}
//     />
//   )
// }

// // ─── 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>
//   )
// }

// // Helper function to calculate length of time in business
// const calculateLengthOfTime = (incorporationDate: string): string => {
//   if (!incorporationDate) return 'Not available'
  
//   const start = new Date(incorporationDate)
//   const now = new Date()
  
//   let years = now.getFullYear() - start.getFullYear()
//   let months = now.getMonth() - start.getMonth()
//   let days = now.getDate() - start.getDate()
  
//   if (days < 0) {
//     months -= 1
//     const prevMonth = new Date(now.getFullYear(), now.getMonth(), 0)
//     days += prevMonth.getDate()
//   }
  
//   if (months < 0) {
//     years -= 1
//     months += 12
//   }
  
//   if (years < 0) {
//     const absYears = Math.abs(years)
//     const absMonths = Math.abs(months)
//     const absDays = Math.abs(days)
    
//     const parts: string[] = []
//     if (absYears > 0) parts.push(`${absYears} year${absYears > 1 ? 's' : ''}`)
//     if (absMonths > 0) parts.push(`${absMonths} month${absMonths > 1 ? 's' : ''}`)
//     if (absDays > 0) parts.push(`${absDays} day${absDays > 1 ? 's' : ''}`)
    
//     if (parts.length === 0) return 'Today'
//     return parts.join(', ')
//   }
  
//   const parts: string[] = []
//   if (years > 0) parts.push(`${years} year${years > 1 ? 's' : ''}`)
//   if (months > 0) parts.push(`${months} month${months > 1 ? 's' : ''}`)
//   if (days > 0) parts.push(`${days} day${days > 1 ? 's' : ''}`)
  
//   if (parts.length === 0) return 'Today'
//   return parts.join(', ')
// }

// const BusinessProfile = ({ onNext, onPrevious, applicationId }: BusinessProfileProps) => {
//   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)

//   // Dropdown data states
//   const [merchantCategories, setMerchantCategories] = useState<MerchantCategory[]>([])
//   const [cardTypesList, setCardTypesList] = useState<CardType[]>([])
//   const [loadingDropdowns, setLoadingDropdowns] = useState<boolean>(true)

//   // Main business state
//   const [business, setBusiness] = useState({
//     description_of_products: '',
//     length_of_time_business: '',
//     merchant_cat_code: '',
//     website: '',
//     descriptor: '',
//     city_field: '',
//     dynamic_descriptors: false,
//     field_for_bankruptcy: false,
//     field_for_bankruptcy_date: '',
//     accepted_credit_cards: false,
//     accepted_credit_cards_months: '',
//     card_scheme_program: false,
//     card_scheme_program_provide_details: '',
//     previous_payment_service_provider: '',
//     previous_acquirer: '',
//     leaving_current_acquirer: '',
//     monthly_sales_volume: '',
//     currency: '$',
//     avg_transaction_value: '',
//     highest_transaction_value: '',
//     one_time_payment: false,
//     recurring_payment: false,
//     domestic: '',
//     europe: '',
//     usa: '',
//     asia: '',
//     rest_of_world: '',
//     e_commerce: '',
//     card_present: '',
//     m_pos: '',
//     moto: '',
//     immediately: '',
//     within_four_weeks: '',
//     within_5_14_weeks: '',
//     more_than_14_weeks: '',
//     is_upon_purchase: false,
//     is_with_download: false,
//     is_on_delivery: false,
//     is_other_payment_option: false,
//     other_payment_details: '',
//     is_offer_affiliate_prog: false,
//     offer_affiliate_prog_details: '',
//     is_need_soft_service: false,
//     software_service_details: '',
//   })

//   // Beta website state
//   const [hasBetaSite, setHasBetaSite] = useState(false)
//   const [betaWebsite, setBetaWebsite] = useState('')
//   const [betaUsername, setBetaUsername] = useState('')
//   const [betaPassword, setBetaPassword] = useState('')
//   const [hasExistingPassword, setHasExistingPassword] = useState(false)
//   const [isEditingPassword, setIsEditingPassword] = useState(false)

//   // Credit card history - dynamic based on months entered (max 6)
//   const [creditCardHistory, setCreditCardHistory] = useState<CreditHistory[]>([])
//   const [savedCreditHistory, setSavedCreditHistory] = useState<CreditHistory[]>([])

//   // Show credit card history table
//   const [showCreditHistory, setShowCreditHistory] = useState<boolean>(false)
//   const [numberOfMonths, setNumberOfMonths] = useState<number>(0)

//   // Card types
//   const [selectedCardTypes, setSelectedCardTypes] = useState<string[]>([])
//   const [otherCardDetails, setOtherCardDetails] = useState('')

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

//   // ─── Live validation router ───────────────────────────────────────────────
//   const runLiveValidation = (field: string, value: string): string => {
//     switch (field) {
//       case 'description_of_products':
//         return validateDescription(value)
//       case 'website':
//         return validateWebsite(value)
//       case 'descriptor':
//         return validateDescriptor(value)
//       case 'city_field':
//         return validateCityField(value)
//       case 'monthly_sales_volume':
//         return validateMonthlySales(value)
//       case 'highest_transaction_value':
//         return validateMonthlySales(value)
//       case 'avg_transaction_value':
//         return validateMonthlySales(value)
//       case 'accepted_credit_cards_months':
//         return validateMonths(value)
//       case 'domestic':
//       case 'europe':
//       case 'usa':
//       case 'asia':
//       case 'rest_of_world':
//       case 'e_commerce':
//       case 'card_present':
//       case 'm_pos':
//       case 'moto':
//       case 'immediately':
//       case 'within_four_weeks':
//       case 'within_5_14_weeks':
//       case 'more_than_14_weeks':
//         return validatePercentage(value)
//       default:
//         return ''
//     }
//   }

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

//   // Fetch dropdown data
//   useEffect(() => {
//     const fetchDropdownData = async () => {
//       try {
//         setLoadingDropdowns(true)
        
//         // Fetch merchant categories
//         const mccResponse = await axiosInstance.get(endpoints.merchantApplication.merchantcategory)
//         console.log('Merchant Categories Response:', mccResponse.data)
        
//         if (mccResponse.data && Array.isArray(mccResponse.data)) {
//           setMerchantCategories(mccResponse.data)
//         }

//         // Fetch card types
//         const cardResponse = await axiosInstance.get(endpoints.merchantApplication.cardtype)
//         console.log('Card Types Response:', cardResponse.data)
        
//         if (cardResponse.data && Array.isArray(cardResponse.data)) {
//           setCardTypesList(cardResponse.data)
//         }
//       } catch (err: any) {
//         console.error('Error fetching dropdown data:', err)
//         toast.error('Failed to load dropdown data')
//       } finally {
//         setLoadingDropdowns(false)
//       }
//     }

//     fetchDropdownData()
//   }, [])

//   // Initialize credit card history based on months
//   const initializeCreditHistory = (months: number, existingData?: CreditHistory[]) => {
//     const maxMonths = Math.min(months, 6)
//     const newHistory: CreditHistory[] = []
    
//     for (let i = 1; i <= maxMonths; i++) {
//       const existingEntry = existingData && i <= existingData.length 
//         ? existingData[i - 1] 
//         : null
      
//       newHistory.push({
//         months_ago: String(i),
//         number_of_transaction: existingEntry?.number_of_transaction || '',
//         transaction_volume: existingEntry?.transaction_volume || '',
//         number_of_chargeback: existingEntry?.number_of_chargeback || '',
//         chargeback_volume: existingEntry?.chargeback_volume || '',
//         number_of_refunds: existingEntry?.number_of_refunds || '',
//         refund_volume: existingEntry?.refund_volume || '',
//       })
//     }
    
//     setCreditCardHistory(newHistory)
//     setNumberOfMonths(maxMonths)
//   }

//   // Fetch existing business data
//   useEffect(() => {
//     if (applicationId) {
//       fetchBusinessData()
//     }
//   }, [applicationId])

//   const fetchBusinessData = 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.businessProfile) {
//         const formData = response.data.businessProfile
//         setIsEditMode(true)
//         prefillFormData(formData)
//       } else {
//         setIsEditMode(false)
//       }

//       // Handle card types from the response
//       if (response.data && response.data.cardTypes && Array.isArray(response.data.cardTypes)) {
//         const cardTypeIds = response.data.cardTypes.map((card: CardTypeMapping) => card.cardtypeId)
//         setSelectedCardTypes(cardTypeIds)
//       }

//       // Handle other card details
//       if (response.data && response.data.businessProfile && response.data.businessProfile.otherCardDetails) {
//         setOtherCardDetails(response.data.businessProfile.otherCardDetails)
//       }

//       // Now check for incorporation date from company profile to calculate length of time
//       if (response.data && response.data.companyProfile && Array.isArray(response.data.companyProfile)) {
//         const mainCompany = response.data.companyProfile.find((item: any) => item.isparent === false || item.isparent === null)
//         if (mainCompany && mainCompany.incorporationDate) {
//           const calculatedLength = calculateLengthOfTime(mainCompany.incorporationDate)
//           if (calculatedLength) {
//             setBusiness(prev => ({
//               ...prev,
//               length_of_time_business: calculatedLength
//             }))
//           }
//         }
//       }
//     } catch (err: any) {
//       console.error('Error fetching business data:', err)
//       if (err.response?.status === 404) {
//         setIsEditMode(false)
//       } else {
//         toast.error('Failed to load business data')
//       }
//     } finally {
//       setFetchingData(false)
//     }
//   }

//   const prefillFormData = (data: any) => {
//     if (data.descriptionOfProducts) {
//       setBusiness(prev => ({ ...prev, description_of_products: data.descriptionOfProducts }))
//     }
//     if (data.lengthOfBusiness) {
//       setBusiness(prev => ({ ...prev, length_of_time_business: data.lengthOfBusiness }))
//     }
//     if (data.merchantCategoryCode) {
//       setBusiness(prev => ({ ...prev, merchant_cat_code: data.merchantCategoryCode }))
//     }
//     if (data.website) {
//       setBusiness(prev => ({ ...prev, website: data.website }))
//     }
//     if (data.betaWebsite) {
//       setHasBetaSite(true)
//       setBetaWebsite(data.betaWebsite)
//     }
//     if (data.username) {
//       setBetaUsername(data.username)
//     }
//     if (data.password) {
//       setHasExistingPassword(true)
//       setIsEditingPassword(false)
//       setBetaPassword('')
//     } else {
//       setHasExistingPassword(false)
//       setBetaPassword('')
//     }
//     if (data.descriptor !== undefined && data.descriptor !== null) {
//       setBusiness(prev => ({ ...prev, descriptor: data.descriptor || '' }))
//     }
//     if (data.cityField) {
//       setBusiness(prev => ({ ...prev, city_field: data.cityField }))
//     }
//     if (data.isDynamicDescriptor !== undefined) {
//       setBusiness(prev => ({ ...prev, dynamic_descriptors: data.isDynamicDescriptor }))
//     }
//     if (data.isBankruptcy !== undefined) {
//       setBusiness(prev => ({ ...prev, field_for_bankruptcy: data.isBankruptcy }))
//     }
//     if (data.fieldForBankruptcyDate) {
//       setBusiness(prev => ({ ...prev, field_for_bankruptcy_date: data.fieldForBankruptcyDate }))
//     }
//     if (data.isAcceptedCreditCards !== undefined) {
//       setBusiness(prev => ({ ...prev, accepted_credit_cards: data.isAcceptedCreditCards }))
//     }
    
//     let savedHistory: CreditHistory[] = []
//     if (data.creditCardHistory && Array.isArray(data.creditCardHistory) && data.creditCardHistory.length > 0) {
//       savedHistory = data.creditCardHistory.map((item: any) => ({
//         months_ago: item.months_ago || '',
//         number_of_transaction: item.number_of_transaction || item.numberOfTransaction || '',
//         transaction_volume: item.transaction_volume || item.transactionVolume || '',
//         number_of_chargeback: item.number_of_chargeback || item.numberOfChargeback || '',
//         chargeback_volume: item.chargeback_volume || item.chargebackVolume || '',
//         number_of_refunds: item.number_of_refunds || item.numberOfRefunds || '',
//         refund_volume: item.refund_volume || item.refundVolume || '',
//       }))
//     }
    
//     if (savedHistory.length > 0) {
//       setSavedCreditHistory(savedHistory)
//     }
    
//     if (data.acceptedCreditCardMonths) {
//       const months = parseInt(data.acceptedCreditCardMonths)
//       setBusiness(prev => ({ ...prev, accepted_credit_cards_months: String(months) }))
//       if (months > 0) {
//         setShowCreditHistory(true)
//         initializeCreditHistory(months, savedHistory.length > 0 ? savedHistory : undefined)
//       }
//     } else if (savedHistory.length > 0) {
//       const months = Math.min(savedHistory.length, 6)
//       setBusiness(prev => ({ ...prev, accepted_credit_cards_months: String(months) }))
//       setShowCreditHistory(true)
//       initializeCreditHistory(months, savedHistory)
//     }

//     if (data.hasCardSchemeProgram !== undefined) {
//       setBusiness(prev => ({ ...prev, card_scheme_program: data.hasCardSchemeProgram }))
//     }
//     if (data.cardSchemeProgramDetails && data.cardSchemeProgramDetails !== 'NA') {
//       setBusiness(prev => ({ ...prev, card_scheme_program_provide_details: data.cardSchemeProgramDetails }))
//     }
//     if (data.previousPaymentServiceProvider) {
//       setBusiness(prev => ({ ...prev, previous_payment_service_provider: data.previousPaymentServiceProvider }))
//     }
//     if (data.previousAcquirer) {
//       setBusiness(prev => ({ ...prev, previous_acquirer: data.previousAcquirer }))
//     }
//     if (data.reasonForLeavingAcquirer) {
//       setBusiness(prev => ({ ...prev, leaving_current_acquirer: data.reasonForLeavingAcquirer }))
//     }
//     if (data.monthlySalesVolume !== undefined && data.monthlySalesVolume !== null) {
//       setBusiness(prev => ({ ...prev, monthly_sales_volume: String(data.monthlySalesVolume) }))
//     }
//     if (data.salesCurrency) {
//       setBusiness(prev => ({ ...prev, currency: data.salesCurrency }))
//     }
//     if (data.avgTransValue !== undefined && data.avgTransValue !== null) {
//       setBusiness(prev => ({ ...prev, avg_transaction_value: String(data.avgTransValue) }))
//     }
//     if (data.highestTransValue !== undefined && data.highestTransValue !== null) {
//       setBusiness(prev => ({ ...prev, highest_transaction_value: String(data.highestTransValue) }))
//     }
//     if (data.oneTimePayment !== undefined) {
//       setBusiness(prev => ({ ...prev, one_time_payment: data.oneTimePayment }))
//     }
//     if (data.recurringPayment !== undefined) {
//       setBusiness(prev => ({ ...prev, recurring_payment: data.recurringPayment }))
//     }
//     if (data.domestic !== undefined && data.domestic !== null) {
//       setBusiness(prev => ({ ...prev, domestic: String(data.domestic) }))
//     }
//     if (data.europe !== undefined && data.europe !== null) {
//       setBusiness(prev => ({ ...prev, europe: String(data.europe) }))
//     }
//     if (data.usa !== undefined && data.usa !== null) {
//       setBusiness(prev => ({ ...prev, usa: String(data.usa) }))
//     }
//     if (data.asia !== undefined && data.asia !== null) {
//       setBusiness(prev => ({ ...prev, asia: String(data.asia) }))
//     }
//     if (data.restOfWorld !== undefined && data.restOfWorld !== null) {
//       setBusiness(prev => ({ ...prev, rest_of_world: String(data.restOfWorld) }))
//     }
//     if (data.ecommerce !== undefined && data.ecommerce !== null) {
//       setBusiness(prev => ({ ...prev, e_commerce: String(data.ecommerce) }))
//     }
//     if (data.cardPresent !== undefined && data.cardPresent !== null) {
//       setBusiness(prev => ({ ...prev, card_present: String(data.cardPresent) }))
//     }
//     if (data.mpos !== undefined && data.mpos !== null) {
//       setBusiness(prev => ({ ...prev, m_pos: String(data.mpos) }))
//     }
//     if (data.moto !== undefined && data.moto !== null) {
//       setBusiness(prev => ({ ...prev, moto: String(data.moto) }))
//     }
//     if (data.immediately !== undefined && data.immediately !== null) {
//       setBusiness(prev => ({ ...prev, immediately: String(data.immediately) }))
//     }
//     if (data.withinFourWeeks !== undefined && data.withinFourWeeks !== null) {
//       setBusiness(prev => ({ ...prev, within_four_weeks: String(data.withinFourWeeks) }))
//     }
//     if (data.within5To14Weeks !== undefined && data.within5To14Weeks !== null) {
//       setBusiness(prev => ({ ...prev, within_5_14_weeks: String(data.within5To14Weeks) }))
//     }
//     if (data.moreThan14Weeks !== undefined && data.moreThan14Weeks !== null) {
//       setBusiness(prev => ({ ...prev, more_than_14_weeks: String(data.moreThan14Weeks) }))
//     }
//     if (data.isUponPurchase !== undefined) {
//       setBusiness(prev => ({ ...prev, is_upon_purchase: data.isUponPurchase }))
//     }
//     if (data.isWithDownload !== undefined) {
//       setBusiness(prev => ({ ...prev, is_with_download: data.isWithDownload }))
//     }
//     if (data.isonDelivery !== undefined) {
//       setBusiness(prev => ({ ...prev, is_on_delivery: data.isonDelivery }))
//     }
//     if (data.isOtherPaymentOption !== undefined) {
//       setBusiness(prev => ({ ...prev, is_other_payment_option: data.isOtherPaymentOption }))
//     }
//     if (data.otherPaymentDetails && data.otherPaymentDetails !== 'NA') {
//       setBusiness(prev => ({ ...prev, other_payment_details: data.otherPaymentDetails }))
//     }
//     if (data.isOfferAffiliateProg !== undefined) {
//       setBusiness(prev => ({ ...prev, is_offer_affiliate_prog: data.isOfferAffiliateProg }))
//     }
//     if (data.offerAffiliateProgDetails && data.offerAffiliateProgDetails !== 'NA') {
//       setBusiness(prev => ({ ...prev, offer_affiliate_prog_details: data.offerAffiliateProgDetails }))
//     }
//     if (data.isNeedSoftwService !== undefined) {
//       setBusiness(prev => ({ ...prev, is_need_soft_service: data.isNeedSoftwService }))
//     }
//     if (data.softwareServDetails && data.softwareServDetails !== 'NA') {
//       setBusiness(prev => ({ ...prev, software_service_details: data.softwareServDetails }))
//     }
//   }

//   const handleBusinessChange = (e: React.ChangeEvent<HTMLInputElement>) => {
//     const { name, value, type, checked } = e.target
    
//     // Handle checkbox/switch fields
//     if (type === 'checkbox') {
//       setBusiness(prev => ({ ...prev, [name]: checked }))
//       if (errors[name]) {
//         setErrors(prev => ({ ...prev, [name]: '' }))
//       }
//       return
//     }
    
//     // Handle months field specially
//     if (name === 'accepted_credit_cards_months') {
//       const numValue = parseInt(value) || 0
//       setBusiness(prev => ({ ...prev, [name]: value }))
      
//       // Run live validation
//       const errorMsg = runLiveValidation(name, value)
//       setErrors(prev => ({ ...prev, [name]: errorMsg }))
      
//       if (numValue > 0 && business.accepted_credit_cards) {
//         const maxMonths = Math.min(numValue, 6)
//         setShowCreditHistory(true)
        
//         const existingData = savedCreditHistory.length > 0 ? savedCreditHistory : creditCardHistory
        
//         const newHistory: CreditHistory[] = []
//         for (let i = 1; i <= maxMonths; i++) {
//           const existingEntry = existingData && i <= existingData.length 
//             ? existingData[i - 1] 
//             : null
          
//           newHistory.push({
//             months_ago: String(i),
//             number_of_transaction: existingEntry?.number_of_transaction || '',
//             transaction_volume: existingEntry?.transaction_volume || '',
//             number_of_chargeback: existingEntry?.number_of_chargeback || '',
//             chargeback_volume: existingEntry?.chargeback_volume || '',
//             number_of_refunds: existingEntry?.number_of_refunds || '',
//             refund_volume: existingEntry?.refund_volume || '',
//           })
//         }
        
//         setCreditCardHistory(newHistory)
//         setNumberOfMonths(maxMonths)
        
//         if (numValue > creditCardHistory.length) {
//           setSavedCreditHistory(newHistory)
//         }
//       } else {
//         setShowCreditHistory(false)
//         setCreditCardHistory([])
//         setNumberOfMonths(0)
//       }
//       return
//     }

//     // Handle other text fields
//     if (name === 'length_of_time_business') {
//       return
//     }

//     setBusiness(prev => ({ ...prev, [name]: value }))

//     // Run live validation
//     const errorMsg = runLiveValidation(name, value)
//     setErrors(prev => ({ ...prev, [name]: errorMsg }))

//     if (name === 'accepted_credit_cards' && !checked) {
//       setShowCreditHistory(false)
//       setCreditCardHistory([])
//       setSavedCreditHistory([])
//       setNumberOfMonths(0)
//     }
//   }

//   const handleCreditHistoryChange = (index: number, field: string, value: string) => {
//     const newHistory = [...creditCardHistory]
//     newHistory[index] = { ...newHistory[index], [field]: value }
//     setCreditCardHistory(newHistory)
//     setSavedCreditHistory(newHistory)
//   }

//   const handleCardTypeToggle = (cardUid: string) => {
//     setSelectedCardTypes(prev =>
//       prev.includes(cardUid)
//         ? prev.filter(id => id !== cardUid)
//         : [...prev, cardUid]
//     )
//   }

//   const handleEditPassword = () => {
//     setIsEditingPassword(true)
//     setBetaPassword('')
//   }

//   const handleCancelEditPassword = () => {
//     setIsEditingPassword(false)
//     setBetaPassword('')
//   }

//   const buildRequestBody = () => {
//     const requestBody: any = {
//       application_id: parseInt(applicationId),
//       description_of_products: business.description_of_products || '',
//       length_of_time_business: business.length_of_time_business || '',
//       merchant_cat_code: business.merchant_cat_code || '',
//       website: business.website || '',
//       descriptor: business.descriptor || '',
//       city_field: business.city_field || '',
//       dynamic_descriptors: business.dynamic_descriptors,
//       field_for_bankruptcy: business.field_for_bankruptcy,
//       field_for_bankruptcy_date: business.field_for_bankruptcy_date || '',
//       accepted_credit_cards: business.accepted_credit_cards,
//       accepted_credit_cards_months: business.accepted_credit_cards_months || '',
//       card_scheme_program: business.card_scheme_program,
//       card_scheme_program_provide_details: business.card_scheme_program_provide_details || '',
//       previous_payment_service_provider: business.previous_payment_service_provider || '',
//       previous_acquirer: business.previous_acquirer || '',
//       leaving_current_acquirer: business.leaving_current_acquirer || '',
//       monthly_sales_volume: business.monthly_sales_volume || '',
//       currency: business.currency || '$',
//       avg_transaction_value: business.avg_transaction_value || '',
//       highest_transaction_value: business.highest_transaction_value || '',
//       one_time_payment: business.one_time_payment,
//       recurring_payment: business.recurring_payment,
//       domestic: business.domestic || '',
//       europe: business.europe || '',
//       usa: business.usa || '',
//       asia: business.asia || '',
//       rest_of_world: business.rest_of_world || '',
//       e_commerce: business.e_commerce || '',
//       card_present: business.card_present || '',
//       m_pos: business.m_pos || '',
//       moto: business.moto || '',
//       immediately: business.immediately || '',
//       within_four_weeks: business.within_four_weeks || '',
//       within_5_14_weeks: business.within_5_14_weeks || '',
//       more_than_14_weeks: business.more_than_14_weeks || '',
//       is_upon_purchase: business.is_upon_purchase,
//       is_with_download: business.is_with_download,
//       is_on_delivery: business.is_on_delivery,
//       is_other_payment_option: business.is_other_payment_option,
//       other_payment_details: business.other_payment_details || '',
//       is_offer_affiliate_prog: business.is_offer_affiliate_prog,
//       offer_affiliate_prog_details: business.offer_affiliate_prog_details || '',
//       is_need_soft_service: business.is_need_soft_service,
//       software_service_details: business.software_service_details || '',
//     }

//     if (hasBetaSite) {
//       requestBody.beta_website = betaWebsite || ''
//       requestBody.username = betaUsername || ''
      
//       if (isEditingPassword && betaPassword) {
//         requestBody.password = betaPassword
//       } else if (!hasExistingPassword && betaPassword) {
//         requestBody.password = betaPassword
//       } else if (!isEditingPassword && hasExistingPassword) {
//         requestBody.password = 'True'
//       }
//     }

//     if (business.accepted_credit_cards && parseInt(business.accepted_credit_cards_months) > 0 && creditCardHistory.length > 0) {
//       const historyWithMonths = creditCardHistory.map(({ months_ago, number_of_transaction, transaction_volume, number_of_chargeback, chargeback_volume, number_of_refunds, refund_volume }) => ({
//         months_ago: parseInt(months_ago),
//         number_of_transaction: number_of_transaction || '0',
//         transaction_volume: transaction_volume || '0',
//         number_of_chargeback: number_of_chargeback || '0',
//         chargeback_volume: chargeback_volume || '0',
//         number_of_refunds: number_of_refunds || '0',
//         refund_volume: refund_volume || '0',
//       }))
//       requestBody.credit_card_history = historyWithMonths
//     }

//     if (selectedCardTypes && selectedCardTypes.length > 0) {
//       requestBody.card_type = selectedCardTypes
//     }

//     const otherCard = cardTypesList.find(card => card.cardName === 'Other' || card.cardType === 'Other')
//     if (otherCard && selectedCardTypes.includes(otherCard.uid) && otherCardDetails) {
//       requestBody.otherCardDetails = otherCardDetails
//     }

//     return requestBody
//   }

//   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.businessProfile}${applicationId}`,
//           requestBody
//         )
//         toast.success('Business profile updated successfully!')
//       } else {
//         response = await axiosInstance.post(
//           endpoints.merchantApplication.businessProfile,
//           requestBody
//         )
//         toast.success('Business profile created successfully!')
//         setIsEditMode(true)
//       }

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

//       let errorMessage = isEditMode
//         ? 'Failed to update business profile. Please try again.'
//         : 'Failed to create business profile. 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)
//     }
//   }

//   const getMonthSuffix = (num: number) => {
//     if (num === 1) return '1st'
//     if (num === 2) return '2nd'
//     if (num === 3) return '3rd'
//     return `${num}th`
//   }

//   // ─── 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 || loadingDropdowns) {
//     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 }}>
//                 Business Profile Details
//               </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 filled fields, orange "Not Provided" indicates 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>
//             )} */}

//             {/* Main Form */}
//             <Paper elevation={0} sx={{ mb: 4, p: 3, bgcolor: 'background.paper', borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
//               <SectionHeader color="primary.main" title="Business Information" />
//               <Grid container spacing={3}>
//                 <Grid item xs={12}>
//                   <SmartTextField
//                     label="Detailed Description of Products/Services Sold"
//                     name="description_of_products"
//                     value={business.description_of_products}
//                     onChange={handleBusinessChange}
//                     error={errors.description_of_products}
//                     helperText={errors.description_of_products}
//                     placeholder="Please provide a detailed description of the products or services your business sells..."
//                     multiline
//                     rows={3}
//                     isEditMode={isEditMode}
//                   />
//                 </Grid>

//                 <Grid item xs={12} sm={6}>
//                   <SmartTextField
//                     label="Length of time in business"
//                     name="length_of_time_business"
//                     value={business.length_of_time_business}
//                     onChange={handleBusinessChange}
//                     error={errors.length_of_time_business}
//                     helperText={errors.length_of_time_business || "Auto-calculated from incorporation date"}
//                     placeholder="e.g., 5 years, 2 months, 10 days"
//                     isEditMode={isEditMode}
//                     disabled
//                     InputProps={{
//                       sx: { bgcolor: 'action.hover' }
//                     }}
//                   />
//                 </Grid>

//                 <Grid item xs={12} sm={6}>
//                   <SmartTextField
//                     label="Merchant Category (MCC)"
//                     name="merchant_cat_code"
//                     value={business.merchant_cat_code}
//                     onChange={handleBusinessChange}
//                     error={errors.merchant_cat_code}
//                     helperText={errors.merchant_cat_code}
//                     select
//                     isEditMode={isEditMode}
//                   >
//                     <MenuItem value="" disabled>Select</MenuItem>
//                     {merchantCategories.map((category) => (
//                       <MenuItem key={category.id} value={category.code}>
//                         {category.name} ({category.code})
//                       </MenuItem>
//                     ))}
//                   </SmartTextField>
//                 </Grid>

//                 <Grid item xs={12}>
//                   <Grid container spacing={3} alignItems="flex-start">
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Website(s) (Comma-Separated)"
//                         name="website"
//                         value={business.website}
//                         onChange={handleBusinessChange}
//                         error={errors.website}
//                         helperText={errors.website}
//                         placeholder="https://example.com, https://store.example.com"
//                         isEditMode={isEditMode}
//                       />
//                     </Grid>

//                     <Grid item xs={12} sm={6}>
//                       <SmartSwitch
//                         label="Beta Site(s)"
//                         checked={hasBetaSite}
//                         onChange={(e) => setHasBetaSite(e.target.checked)}
//                         name="hasBetaSite"
//                         isEditMode={isEditMode}
//                         helperText="Toggle on to add website details"
//                       />
//                     </Grid>

//                     {hasBetaSite && (
//                       <Grid item xs={12}>
//                         <Box sx={{ bgcolor: 'action.hover', borderRadius: 2, p: 3, mt: 1 }}>
//                           <Typography variant="h6" sx={{ fontWeight: 600, mb: 3 }}>
//                             Beta Website Details
//                           </Typography>
//                           <Grid container spacing={2}>
//                             <Grid item xs={12}>
//                               <SmartTextField
//                                 label="Beta Website URL"
//                                 name="betaWebsite"
//                                 value={betaWebsite}
//                                 onChange={(e) => setBetaWebsite(e.target.value)}
//                                 placeholder="https://beta.example.com"
//                                 isEditMode={isEditMode}
//                               />
//                             </Grid>
//                             <Grid item xs={12} sm={6}>
//                               <SmartTextField
//                                 label="Username"
//                                 name="betaUsername"
//                                 value={betaUsername}
//                                 onChange={(e) => setBetaUsername(e.target.value)}
//                                 isEditMode={isEditMode}
//                               />
//                             </Grid>
//                             <Grid item xs={12} sm={6}>
//                               <Box>
//                                 <SmartTextField
//                                   label="Password"
//                                   name="betaPassword"
//                                   value={betaPassword}
//                                   onChange={(e) => setBetaPassword(e.target.value)}
//                                   type="password"
//                                   disabled={!isEditingPassword && hasExistingPassword}
//                                   isEditMode={isEditMode}
//                                   placeholder={!isEditingPassword && hasExistingPassword ? "••••••••" : "Enter password"}
//                                   InputProps={{
//                                     sx: {
//                                       backgroundColor: !isEditingPassword && hasExistingPassword ? '#f5f5f5' : 'transparent',
//                                     }
//                                   }}
//                                 />
//                                 <Box sx={{ display: 'flex', gap: 1, mt: 1, alignItems: 'center', flexWrap: 'wrap' }}>
//                                   {hasExistingPassword && !isEditingPassword ? (
//                                     <>
//                                       <Chip 
//                                         label="✓ Password Set" 
//                                         color="success" 
//                                         size="small"
//                                       />
//                                       <Typography variant="caption" color="text.secondary">
//                                         Click
//                                       </Typography>
//                                       <Button
//                                         size="small"
//                                         variant="outlined"
//                                         color="primary"
//                                         onClick={handleEditPassword}
//                                         sx={{ minWidth: '80px', height: '30px' }}
//                                       >
//                                         Edit
//                                       </Button>
//                                       <Typography variant="caption" color="text.secondary">
//                                         to change password
//                                       </Typography>
//                                     </>
//                                   ) : hasExistingPassword && isEditingPassword ? (
//                                     <>
//                                       <Chip 
//                                         label="Editing Password" 
//                                         color="warning" 
//                                         size="small"
//                                       />
//                                       <Button
//                                         size="small"
//                                         variant="outlined"
//                                         color="error"
//                                         onClick={handleCancelEditPassword}
//                                         sx={{ minWidth: '80px', height: '30px' }}
//                                       >
//                                         Cancel
//                                       </Button>
//                                       <Typography variant="caption" color="warning.main">
//                                         Enter new password or cancel to keep existing
//                                       </Typography>
//                                     </>
//                                   ) : (
//                                     <Typography variant="caption" color="text.secondary">
//                                       Set a password for the beta site
//                                     </Typography>
//                                   )}
//                                 </Box>
//                               </Box>
//                             </Grid>
//                           </Grid>
//                         </Box>
//                       </Grid>
//                     )}
//                   </Grid>
//                 </Grid>

//                 <Grid item xs={12} sm={6}>
//                   <SmartTextField
//                     label="Credit Card Descriptor (Max 22 Char.)"
//                     name="descriptor"
//                     value={business.descriptor}
//                     onChange={handleBusinessChange}
//                     error={errors.descriptor}
//                     helperText={errors.descriptor}
//                     inputProps={{ maxLength: 22 }}
//                     isEditMode={isEditMode}
//                   />
//                 </Grid>

//                 <Grid item xs={12} sm={6}>
//                   <SmartTextField
//                     label="DBA/City (Max 12 Char.)"
//                     name="city_field"
//                     value={business.city_field}
//                     onChange={handleBusinessChange}
//                     error={errors.city_field}
//                     helperText={errors.city_field}
//                     inputProps={{ maxLength: 12 }}
//                     isEditMode={isEditMode}
//                   />
//                 </Grid>

//                 <Grid item xs={12}>
//                   <SmartCheckbox
//                     label="Will You use 'Dynamic Descriptor'"
//                     checked={business.dynamic_descriptors}
//                     onChange={handleBusinessChange}
//                     name="dynamic_descriptors"
//                     isEditMode={isEditMode}
//                   />
//                 </Grid>

//                 <Grid item xs={12}>
//                   <SmartCheckbox
//                     label="Have you filed for bankruptcy before?"
//                     checked={business.field_for_bankruptcy}
//                     onChange={handleBusinessChange}
//                     name="field_for_bankruptcy"
//                     isEditMode={isEditMode}
//                   />
//                   {business.field_for_bankruptcy && (
//                     <Box sx={{ mt: 2, ml: 4 }}>
//                       <SmartTextField
//                         label="Date of Bankruptcy"
//                         name="field_for_bankruptcy_date"
//                         value={business.field_for_bankruptcy_date}
//                         onChange={handleBusinessChange}
//                         type="date"
//                         InputLabelProps={{ shrink: true }}
//                         isEditMode={isEditMode}
//                       />
//                     </Box>
//                   )}
//                 </Grid>

//                 <Grid item xs={12}>
//                   <SmartCheckbox
//                     label="Have you previously accepted Credit Card payments?"
//                     checked={business.accepted_credit_cards}
//                     onChange={handleBusinessChange}
//                     name="accepted_credit_cards"
//                     isEditMode={isEditMode}
//                   />
//                   {business.accepted_credit_cards && (
//                     <Box sx={{ mt: 2, ml: 4 }}>
//                       <Grid container spacing={2}>
//                         <Grid item xs={12} sm={6}>
//                           <SmartTextField
//                             label="How Many Months (Max 6)"
//                             name="accepted_credit_cards_months"
//                             value={business.accepted_credit_cards_months}
//                             onChange={handleBusinessChange}
//                             error={errors.accepted_credit_cards_months}
//                             helperText={errors.accepted_credit_cards_months || "Enter 1-6 months to show credit history"}
//                             type="number"
//                             inputProps={{ min: 0, max: 6 }}
//                             placeholder="Enter number of months (max 6)"
//                             isEditMode={isEditMode}
//                           />
//                         </Grid>
//                         <Grid item xs={12} sm={6}>
//                           <SmartTextField
//                             label="Previous Payment Service Provider"
//                             name="previous_payment_service_provider"
//                             value={business.previous_payment_service_provider}
//                             onChange={handleBusinessChange}
//                             placeholder="Enter provider name"
//                             isEditMode={isEditMode}
//                           />
//                         </Grid>
//                         <Grid item xs={12} sm={6}>
//                           <SmartTextField
//                             label="Previous Acquirer"
//                             name="previous_acquirer"
//                             value={business.previous_acquirer}
//                             onChange={handleBusinessChange}
//                             placeholder="Enter acquirer name"
//                             isEditMode={isEditMode}
//                           />
//                         </Grid>
//                         <Grid item xs={12} sm={6}>
//                           <SmartTextField
//                             label="Reason for leaving current acquirer"
//                             name="leaving_current_acquirer"
//                             value={business.leaving_current_acquirer}
//                             onChange={handleBusinessChange}
//                             placeholder="Enter reason"
//                             isEditMode={isEditMode}
//                           />
//                         </Grid>
//                       </Grid>

//                       {showCreditHistory && creditCardHistory.length > 0 && (
//                         <Box sx={{ mt: 4 }}>
//                           <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, color: 'primary.main' }}>
//                             PLEASE PROVIDE {creditCardHistory.length} MONTH{creditCardHistory.length > 1 ? 'S' : ''} OF MOST RECENT PROCESSING HISTORY BELOW
//                           </Typography>
//                           <Box sx={{ overflowX: 'auto' }}>
//                             <table style={{ width: '100%', borderCollapse: 'collapse' }}>
//                               <thead>
//                                 <tr style={{ backgroundColor: '#f5f5f5' }}>
//                                   <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '80px' }}>
//                                     MONTH
//                                   </th>
//                                   <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
//                                     Number of transactions
//                                   </th>
//                                   <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
//                                     Transaction volume
//                                   </th>
//                                   <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
//                                     Number of chargebacks
//                                   </th>
//                                   <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
//                                     Chargeback volume
//                                   </th>
//                                   <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
//                                     Number of refunds
//                                   </th>
//                                   <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
//                                     Refund volume
//                                   </th>
//                                 </tr>
//                               </thead>
//                               <tbody>
//                                 {creditCardHistory.map((history, index) => (
//                                   <tr key={index}>
//                                     <td style={{ padding: '12px', border: '1px solid #ddd', fontWeight: 500, textAlign: 'center' }}>
//                                       {getMonthSuffix(index + 1)}
//                                     </td>
//                                     <td style={{ padding: '8px', border: '1px solid #ddd' }}>
//                                       <TextField
//                                         fullWidth
//                                         type="number"
//                                         size="small"
//                                         value={history.number_of_transaction}
//                                         onChange={(e) => handleCreditHistoryChange(index, 'number_of_transaction', e.target.value)}
//                                         placeholder="0"
//                                       />
//                                     </td>
//                                     <td style={{ padding: '8px', border: '1px solid #ddd' }}>
//                                       <TextField
//                                         fullWidth
//                                         type="number"
//                                         size="small"
//                                         value={history.transaction_volume}
//                                         onChange={(e) => handleCreditHistoryChange(index, 'transaction_volume', e.target.value)}
//                                         placeholder="0"
//                                       />
//                                     </td>
//                                     <td style={{ padding: '8px', border: '1px solid #ddd' }}>
//                                       <TextField
//                                         fullWidth
//                                         type="number"
//                                         size="small"
//                                         value={history.number_of_chargeback}
//                                         onChange={(e) => handleCreditHistoryChange(index, 'number_of_chargeback', e.target.value)}
//                                         placeholder="0"
//                                       />
//                                     </td>
//                                     <td style={{ padding: '8px', border: '1px solid #ddd' }}>
//                                       <TextField
//                                         fullWidth
//                                         type="number"
//                                         size="small"
//                                         value={history.chargeback_volume}
//                                         onChange={(e) => handleCreditHistoryChange(index, 'chargeback_volume', e.target.value)}
//                                         placeholder="0"
//                                       />
//                                     </td>
//                                     <td style={{ padding: '8px', border: '1px solid #ddd' }}>
//                                       <TextField
//                                         fullWidth
//                                         type="number"
//                                         size="small"
//                                         value={history.number_of_refunds}
//                                         onChange={(e) => handleCreditHistoryChange(index, 'number_of_refunds', e.target.value)}
//                                         placeholder="0"
//                                       />
//                                     </td>
//                                     <td style={{ padding: '8px', border: '1px solid #ddd' }}>
//                                       <TextField
//                                         fullWidth
//                                         type="number"
//                                         size="small"
//                                         value={history.refund_volume}
//                                         onChange={(e) => handleCreditHistoryChange(index, 'refund_volume', e.target.value)}
//                                         placeholder="0"
//                                       />
//                                     </td>
//                                   </tr>
//                                 ))}
//                               </tbody>
//                             </table>
//                           </Box>
//                         </Box>
//                       )}
//                     </Box>
//                   )}
//                 </Grid>

//                 <Grid item xs={12}>
//                   <SmartCheckbox
//                     label="Have you ever flagged or been in violation of any card schema program?"
//                     checked={business.card_scheme_program}
//                     onChange={handleBusinessChange}
//                     name="card_scheme_program"
//                     isEditMode={isEditMode}
//                   />
//                   {business.card_scheme_program && (
//                     <Box sx={{ mt: 2, ml: 4 }}>
//                       <SmartTextField
//                         label="Please Provide Details"
//                         name="card_scheme_program_provide_details"
//                         value={business.card_scheme_program_provide_details}
//                         onChange={handleBusinessChange}
//                         placeholder="Please provide details about the violation..."
//                         multiline
//                         rows={3}
//                         isEditMode={isEditMode}
//                       />
//                     </Box>
//                   )}
//                 </Grid>

//                 <Grid item xs={12} sm={4}>
//                   <SmartTextField
//                     label="Estimated monthly sales volume"
//                     name="monthly_sales_volume"
//                     value={business.monthly_sales_volume}
//                     onChange={handleBusinessChange}
//                     error={errors.monthly_sales_volume}
//                     helperText={errors.monthly_sales_volume}
//                     type="number"
//                     placeholder="Enter amount"
//                     isEditMode={isEditMode}
//                     InputProps={{ startAdornment: <span>$ </span> }}
//                   />
//                 </Grid>

//                 <Grid item xs={12} sm={4}>
//                   <SmartTextField
//                     label="Highest transaction value"
//                     name="highest_transaction_value"
//                     value={business.highest_transaction_value}
//                     onChange={handleBusinessChange}
//                     error={errors.highest_transaction_value}
//                     helperText={errors.highest_transaction_value}
//                     type="number"
//                     placeholder="Enter amount"
//                     isEditMode={isEditMode}
//                     InputProps={{ startAdornment: <span>$ </span> }}
//                   />
//                 </Grid>

//                 <Grid item xs={12} sm={4}>
//                   <SmartTextField
//                     label="Average transaction value"
//                     name="avg_transaction_value"
//                     value={business.avg_transaction_value}
//                     onChange={handleBusinessChange}
//                     error={errors.avg_transaction_value}
//                     helperText={errors.avg_transaction_value}
//                     type="number"
//                     placeholder="Enter amount"
//                     isEditMode={isEditMode}
//                     InputProps={{ startAdornment: <span>$ </span> }}
//                   />
//                 </Grid>

//                 <Grid item xs={12} sm={6}>
//                   <FormControl component="fieldset">
//                     <FormLabel component="legend">Payment frequency</FormLabel>
//                     <Stack direction="row" spacing={2}>
//                       <SmartCheckbox
//                         label="One-time payment"
//                         checked={business.one_time_payment}
//                         onChange={handleBusinessChange}
//                         name="one_time_payment"
//                         isEditMode={isEditMode}
//                       />
//                       <SmartCheckbox
//                         label="Recurring payment"
//                         checked={business.recurring_payment}
//                         onChange={handleBusinessChange}
//                         name="recurring_payment"
//                         isEditMode={isEditMode}
//                       />
//                     </Stack>
//                   </FormControl>
//                 </Grid>

//                 <Grid item xs={12}>
//                   <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
//                     ORIGIN OF TRANSACTIONS (%)
//                   </Typography>
//                   <Grid container spacing={2}>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Domestic"
//                         type="number"
//                         name="domestic"
//                         value={business.domestic}
//                         onChange={handleBusinessChange}
//                         error={errors.domestic}
//                         helperText={errors.domestic}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Europe"
//                         type="number"
//                         name="europe"
//                         value={business.europe}
//                         onChange={handleBusinessChange}
//                         error={errors.europe}
//                         helperText={errors.europe}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="USA (Oceania)"
//                         type="number"
//                         name="usa"
//                         value={business.usa}
//                         onChange={handleBusinessChange}
//                         error={errors.usa}
//                         helperText={errors.usa}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Asia"
//                         type="number"
//                         name="asia"
//                         value={business.asia}
//                         onChange={handleBusinessChange}
//                         error={errors.asia}
//                         helperText={errors.asia}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Rest of world"
//                         type="number"
//                         name="rest_of_world"
//                         value={business.rest_of_world}
//                         onChange={handleBusinessChange}
//                         error={errors.rest_of_world}
//                         helperText={errors.rest_of_world}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                   </Grid>
//                 </Grid>

//                 <Grid item xs={12}>
//                   <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
//                     METHOD OF ACCEPTANCE (%)
//                   </Typography>
//                   <Grid container spacing={2}>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="E-commerce / M-Commerce"
//                         type="number"
//                         name="e_commerce"
//                         value={business.e_commerce}
//                         onChange={handleBusinessChange}
//                         error={errors.e_commerce}
//                         helperText={errors.e_commerce}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Card Present (POS)"
//                         type="number"
//                         name="card_present"
//                         value={business.card_present}
//                         onChange={handleBusinessChange}
//                         error={errors.card_present}
//                         helperText={errors.card_present}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="M-Pos (Mobile POS)"
//                         type="number"
//                         name="m_pos"
//                         value={business.m_pos}
//                         onChange={handleBusinessChange}
//                         error={errors.m_pos}
//                         helperText={errors.m_pos}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="MOTO"
//                         type="number"
//                         name="moto"
//                         value={business.moto}
//                         onChange={handleBusinessChange}
//                         error={errors.moto}
//                         helperText={errors.moto}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                   </Grid>
//                 </Grid>

//                 <Grid item xs={12}>
//                   <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
//                     DELIVERY TIME FOR GOODS/SERVICES (%)
//                   </Typography>
//                   <Grid container spacing={2}>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Immediately"
//                         type="number"
//                         name="immediately"
//                         value={business.immediately}
//                         onChange={handleBusinessChange}
//                         error={errors.immediately}
//                         helperText={errors.immediately}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Within 4 weeks"
//                         type="number"
//                         name="within_four_weeks"
//                         value={business.within_four_weeks}
//                         onChange={handleBusinessChange}
//                         error={errors.within_four_weeks}
//                         helperText={errors.within_four_weeks}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Within 5-14 weeks"
//                         type="number"
//                         name="within_5_14_weeks"
//                         value={business.within_5_14_weeks}
//                         onChange={handleBusinessChange}
//                         error={errors.within_5_14_weeks}
//                         helperText={errors.within_5_14_weeks}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="More than 14 weeks"
//                         type="number"
//                         name="more_than_14_weeks"
//                         value={business.more_than_14_weeks}
//                         onChange={handleBusinessChange}
//                         error={errors.more_than_14_weeks}
//                         helperText={errors.more_than_14_weeks}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                   </Grid>
//                 </Grid>

//                 <Grid item xs={12}>
//                   <FormControl component="fieldset">
//                     <FormLabel component="legend">When does payment take place?</FormLabel>
//                     <Stack direction="row" spacing={2} flexWrap="wrap">
//                       <SmartCheckbox
//                         label="Upon purchase"
//                         checked={business.is_upon_purchase}
//                         onChange={handleBusinessChange}
//                         name="is_upon_purchase"
//                         isEditMode={isEditMode}
//                       />
//                       <SmartCheckbox
//                         label="With download"
//                         checked={business.is_with_download}
//                         onChange={handleBusinessChange}
//                         name="is_with_download"
//                         isEditMode={isEditMode}
//                       />
//                       <SmartCheckbox
//                         label="On delivery"
//                         checked={business.is_on_delivery}
//                         onChange={handleBusinessChange}
//                         name="is_on_delivery"
//                         isEditMode={isEditMode}
//                       />
//                       <SmartCheckbox
//                         label="Other"
//                         checked={business.is_other_payment_option}
//                         onChange={handleBusinessChange}
//                         name="is_other_payment_option"
//                         isEditMode={isEditMode}
//                       />
//                     </Stack>
//                   </FormControl>
//                   {business.is_other_payment_option && (
//                     <Box sx={{ mt: 2 }}>
//                       <SmartTextField
//                         label="Please Provide Details"
//                         name="other_payment_details"
//                         value={business.other_payment_details}
//                         onChange={handleBusinessChange}
//                         placeholder="Please provide details about when payment takes place..."
//                         multiline
//                         rows={3}
//                         isEditMode={isEditMode}
//                       />
//                     </Box>
//                   )}
//                 </Grid>

//                 <Grid item xs={12}>
//                   <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
//                     Card types applying for
//                   </Typography>
//                   <Grid container spacing={2}>
//                     {cardTypesList.map((card) => (
//                       <Grid item xs={6} sm={4} md={3} key={card.uid}>
//                         <FormControlLabel
//                           control={
//                             <Checkbox
//                               checked={selectedCardTypes.includes(card.uid)}
//                               onChange={() => handleCardTypeToggle(card.uid)}
//                               sx={{
//                                 '&.Mui-checked': {
//                                   color: isEditMode ? '#2e7d32' : undefined,
//                                 },
//                               }}
//                             />
//                           }
//                           label={card.cardName || card.cardType}
//                         />
//                       </Grid>
//                     ))}
//                   </Grid>
//                   {selectedCardTypes.some(uid => {
//                     const card = cardTypesList.find(c => c.uid === uid)
//                     return card && (card.cardName === 'Other' || card.cardType === 'Other')
//                   }) && (
//                     <Box sx={{ mt: 2 }}>
//                       <SmartTextField
//                         label="Other Card Details"
//                         name="otherCardDetails"
//                         value={otherCardDetails}
//                         onChange={(e) => setOtherCardDetails(e.target.value)}
//                         placeholder="Please specify other card types..."
//                         multiline
//                         rows={2}
//                         isEditMode={isEditMode}
//                       />
//                     </Box>
//                   )}
//                 </Grid>

//                 <Grid item xs={12}>
//                   <SmartSwitch
//                     label="Do you offer / make use of affiliate programs?"
//                     checked={business.is_offer_affiliate_prog}
//                     onChange={handleBusinessChange}
//                     name="is_offer_affiliate_prog"
//                     isEditMode={isEditMode}
//                   />
//                   {business.is_offer_affiliate_prog && (
//                     <Box sx={{ mt: 2, ml: 4 }}>
//                       <SmartTextField
//                         label="Please provide details"
//                         name="offer_affiliate_prog_details"
//                         value={business.offer_affiliate_prog_details}
//                         onChange={handleBusinessChange}
//                         placeholder="Please provide details about your affiliate programs..."
//                         multiline
//                         rows={3}
//                         isEditMode={isEditMode}
//                       />
//                     </Box>
//                   )}
//                 </Grid>

//                 <Grid item xs={12}>
//                   <SmartSwitch
//                     label="Need Software As A Service"
//                     checked={business.is_need_soft_service}
//                     onChange={handleBusinessChange}
//                     name="is_need_soft_service"
//                     isEditMode={isEditMode}
//                   />
//                   {business.is_need_soft_service && (
//                     <Box sx={{ mt: 2, ml: 4 }}>
//                       <SmartTextField
//                         label="Please provide details"
//                         name="software_service_details"
//                         value={business.software_service_details}
//                         onChange={handleBusinessChange}
//                         placeholder="Please provide details about your software requirements..."
//                         multiline
//                         rows={3}
//                         isEditMode={isEditMode}
//                       />
//                     </Box>
//                   )}
//                 </Grid>
//               </Grid>
//             </Paper>

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

//             {/* Navigation */}
//             <Stack direction="row" spacing={2} justifyContent="flex-end">
//               <Button
//                 type="button"
//                 variant="outlined"
//                 size="large"
//                 onClick={onPrevious}
//                 sx={{ textTransform: 'none', px: 4 }}
//                 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 BusinessProfile

// password issue solved ////////////////////
// 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 MenuItem from '@mui/material/MenuItem'
// import FormControlLabel from '@mui/material/FormControlLabel'
// import Checkbox from '@mui/material/Checkbox'
// 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 FormControl from '@mui/material/FormControl'
// import FormLabel from '@mui/material/FormLabel'

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

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

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

// interface CreditHistory {
//   months_ago: string
//   number_of_transaction: string
//   transaction_volume: string
//   number_of_chargeback: string
//   chargeback_volume: string
//   number_of_refunds: string
//   refund_volume: string
// }

// interface MerchantCategory {
//   id: number
//   uid: string
//   createdAt: string
//   updatedAt: string
//   name: string
//   code: string
//   isActive: boolean
// }

// interface CardType {
//   uid: string
//   cardType: string
//   cardName: string
// }

// interface CardTypeMapping {
//   id: number
//   uid: string
//   createdAt: string
//   updatedAt: string
//   cardtypeId: string
// }

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

// const validateDescription = (val: string): string => {
//   if (!val) return ''
//   if (val.trim().length < 10)
//     return 'Please provide at least 10 characters of detail. e.g. We sell electronics and provide repair services.'
//   if (val.trim().length > 2000)
//     return 'Description must not exceed 2000 characters.'
//   if (/[<>@#\\]/.test(val))
//     return 'Special characters like < > @ # \\ are not allowed.'
//   return ''
// }

// const validateWebsite = (val: string): string => {
//   if (!val) return ''
//   const urls = val.split(',').map(u => u.trim())
//   for (const url of urls) {
//     if (url && !/^https?:\/\/[^\s]+$/.test(url))
//       return 'Please enter valid URLs starting with http:// or https://. e.g. https://example.com'
//   }
//   return ''
// }

// const validateDescriptor = (val: string): string => {
//   if (!val) return ''
//   if (val.trim().length > 22)
//     return 'Descriptor must not exceed 22 characters.'
//   if (/[<>@#\\]/.test(val))
//     return 'Special characters like < > @ # \\ are not allowed.'
//   return ''
// }

// const validateCityField = (val: string): string => {
//   if (!val) return ''
//   if (val.trim().length > 12)
//     return 'DBA/City must not exceed 12 characters.'
//   if (!/^[A-Za-zÀ-ÿ\s'\-]+$/.test(val.trim()))
//     return 'Only letters, spaces, hyphens and apostrophes are allowed.'
//   return ''
// }

// const validateMonthlySales = (val: string): string => {
//   if (!val) return ''
//   if (!/^\d+(\.\d{1,2})?$/.test(val.trim()))
//     return 'Please enter a valid numeric amount. e.g. 10000 or 25000.50'
//   if (parseFloat(val) <= 0)
//     return 'Amount must be greater than 0.'
//   return ''
// }

// const validatePercentage = (val: string): string => {
//   if (!val) return ''
//   if (!/^\d+(\.\d{1,2})?$/.test(val.trim()))
//     return 'Please enter a valid number. e.g. 25 or 50.5'
//   const num = parseFloat(val)
//   if (num < 0 || num > 100)
//     return 'Please enter a value between 0 and 100.'
//   return ''
// }

// const validateMonths = (val: string): string => {
//   if (!val) return ''
//   if (!/^\d+$/.test(val.trim()))
//     return 'Please enter a valid number. e.g. 3'
//   const num = parseInt(val)
//   if (num < 1 || num > 6)
//     return 'Please enter a number between 1 and 6.'
//   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,
//   required,
//   inputProps,
//   hideStatus, // New prop to hide status indicators
// }: any) => {
//   const filled = value !== null && value !== undefined && String(value).trim() !== ''
//   return (
//     <Box>
//       {!hideStatus && (
//         <FieldLabel label={label} value={value} isEditMode={isEditMode} />
//       )}
//       {hideStatus && (
//         <Typography variant="body2" sx={{ fontWeight: 500, color: 'text.secondary', mb: 0.5 }}>
//           {label}
//         </Typography>
//       )}
//       <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}
//         required={required}
//         inputProps={inputProps}
//         sx={{
//           '& .MuiOutlinedInput-root': {
//             '& fieldset': { borderColor: isEditMode && filled && !hideStatus ? '#A5D6A7' : undefined },
//             '&:hover fieldset': { borderColor: isEditMode && filled && !hideStatus ? '#66BB6A' : undefined },
//           },
//         }}
//       >
//         {children}
//       </TextField>
//     </Box>
//   )
// }

// // ─── SmartCheckbox ────────────────────────────────────────────────────────────
// const SmartCheckbox = ({
//   label,
//   checked,
//   onChange,
//   name,
//   isEditMode,
// }: {
//   label: string
//   checked: boolean
//   onChange: (e: React.ChangeEvent<HTMLInputElement>) => void
//   name: string
//   isEditMode: boolean
// }) => {
//   return (
//     <FormControlLabel
//       control={
//         <Checkbox
//           checked={checked}
//           onChange={onChange}
//           name={name}
//           sx={{
//             '&.Mui-checked': {
//               color: isEditMode ? '#2e7d32' : undefined,
//             },
//           }}
//         />
//       }
//       label={label}
//     />
//   )
// }

// // ─── 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>
//   )
// }

// // Helper function to calculate length of time in business
// const calculateLengthOfTime = (incorporationDate: string): string => {
//   if (!incorporationDate) return 'Not available'
  
//   const start = new Date(incorporationDate)
//   const now = new Date()
  
//   let years = now.getFullYear() - start.getFullYear()
//   let months = now.getMonth() - start.getMonth()
//   let days = now.getDate() - start.getDate()
  
//   if (days < 0) {
//     months -= 1
//     const prevMonth = new Date(now.getFullYear(), now.getMonth(), 0)
//     days += prevMonth.getDate()
//   }
  
//   if (months < 0) {
//     years -= 1
//     months += 12
//   }
  
//   if (years < 0) {
//     const absYears = Math.abs(years)
//     const absMonths = Math.abs(months)
//     const absDays = Math.abs(days)
    
//     const parts: string[] = []
//     if (absYears > 0) parts.push(`${absYears} year${absYears > 1 ? 's' : ''}`)
//     if (absMonths > 0) parts.push(`${absMonths} month${absMonths > 1 ? 's' : ''}`)
//     if (absDays > 0) parts.push(`${absDays} day${absDays > 1 ? 's' : ''}`)
    
//     if (parts.length === 0) return 'Today'
//     return parts.join(', ')
//   }
  
//   const parts: string[] = []
//   if (years > 0) parts.push(`${years} year${years > 1 ? 's' : ''}`)
//   if (months > 0) parts.push(`${months} month${months > 1 ? 's' : ''}`)
//   if (days > 0) parts.push(`${days} day${days > 1 ? 's' : ''}`)
  
//   if (parts.length === 0) return 'Today'
//   return parts.join(', ')
// }

// const BusinessProfile = ({ onNext, onPrevious, applicationId }: BusinessProfileProps) => {
//   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)

//   // Dropdown data states
//   const [merchantCategories, setMerchantCategories] = useState<MerchantCategory[]>([])
//   const [cardTypesList, setCardTypesList] = useState<CardType[]>([])
//   const [loadingDropdowns, setLoadingDropdowns] = useState<boolean>(true)

//   // Main business state
//   const [business, setBusiness] = useState({
//     description_of_products: '',
//     length_of_time_business: '',
//     merchant_cat_code: '',
//     website: '',
//     descriptor: '',
//     city_field: '',
//     dynamic_descriptors: false,
//     field_for_bankruptcy: false,
//     field_for_bankruptcy_date: '',
//     accepted_credit_cards: false,
//     accepted_credit_cards_months: '',
//     card_scheme_program: false,
//     card_scheme_program_provide_details: '',
//     previous_payment_service_provider: '',
//     previous_acquirer: '',
//     leaving_current_acquirer: '',
//     monthly_sales_volume: '',
//     currency: '$',
//     avg_transaction_value: '',
//     highest_transaction_value: '',
//     one_time_payment: false,
//     recurring_payment: false,
//     domestic: '',
//     europe: '',
//     usa: '',
//     asia: '',
//     rest_of_world: '',
//     e_commerce: '',
//     card_present: '',
//     m_pos: '',
//     moto: '',
//     immediately: '',
//     within_four_weeks: '',
//     within_5_14_weeks: '',
//     more_than_14_weeks: '',
//     is_upon_purchase: false,
//     is_with_download: false,
//     is_on_delivery: false,
//     is_other_payment_option: false,
//     other_payment_details: '',
//     is_offer_affiliate_prog: false,
//     offer_affiliate_prog_details: '',
//     is_need_soft_service: false,
//     software_service_details: '',
//   })

//   // Beta website state
//   const [hasBetaSite, setHasBetaSite] = useState(false)
//   const [betaWebsite, setBetaWebsite] = useState('')
//   const [betaUsername, setBetaUsername] = useState('')
//   const [betaPassword, setBetaPassword] = useState('')
//   const [hasExistingPassword, setHasExistingPassword] = useState(false)
//   const [isEditingPassword, setIsEditingPassword] = useState(false)

//   // Credit card history - dynamic based on months entered (max 6)
//   const [creditCardHistory, setCreditCardHistory] = useState<CreditHistory[]>([])
//   const [savedCreditHistory, setSavedCreditHistory] = useState<CreditHistory[]>([])

//   // Show credit card history table
//   const [showCreditHistory, setShowCreditHistory] = useState<boolean>(false)
//   const [numberOfMonths, setNumberOfMonths] = useState<number>(0)

//   // Card types
//   const [selectedCardTypes, setSelectedCardTypes] = useState<string[]>([])
//   const [otherCardDetails, setOtherCardDetails] = useState('')

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

//   // ─── Live validation router ───────────────────────────────────────────────
//   const runLiveValidation = (field: string, value: string): string => {
//     switch (field) {
//       case 'description_of_products':
//         return validateDescription(value)
//       case 'website':
//         return validateWebsite(value)
//       case 'descriptor':
//         return validateDescriptor(value)
//       case 'city_field':
//         return validateCityField(value)
//       case 'monthly_sales_volume':
//         return validateMonthlySales(value)
//       case 'highest_transaction_value':
//         return validateMonthlySales(value)
//       case 'avg_transaction_value':
//         return validateMonthlySales(value)
//       case 'accepted_credit_cards_months':
//         return validateMonths(value)
//       case 'domestic':
//       case 'europe':
//       case 'usa':
//       case 'asia':
//       case 'rest_of_world':
//       case 'e_commerce':
//       case 'card_present':
//       case 'm_pos':
//       case 'moto':
//       case 'immediately':
//       case 'within_four_weeks':
//       case 'within_5_14_weeks':
//       case 'more_than_14_weeks':
//         return validatePercentage(value)
//       default:
//         return ''
//     }
//   }

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

//   // Fetch dropdown data
//   useEffect(() => {
//     const fetchDropdownData = async () => {
//       try {
//         setLoadingDropdowns(true)
        
//         // Fetch merchant categories
//         const mccResponse = await axiosInstance.get(endpoints.merchantApplication.merchantcategory)
//         console.log('Merchant Categories Response:', mccResponse.data)
        
//         if (mccResponse.data && Array.isArray(mccResponse.data)) {
//           setMerchantCategories(mccResponse.data)
//         }

//         // Fetch card types
//         const cardResponse = await axiosInstance.get(endpoints.merchantApplication.cardtype)
//         console.log('Card Types Response:', cardResponse.data)
        
//         if (cardResponse.data && Array.isArray(cardResponse.data)) {
//           setCardTypesList(cardResponse.data)
//         }
//       } catch (err: any) {
//         console.error('Error fetching dropdown data:', err)
//         toast.error('Failed to load dropdown data')
//       } finally {
//         setLoadingDropdowns(false)
//       }
//     }

//     fetchDropdownData()
//   }, [])

//   // Initialize credit card history based on months
//   const initializeCreditHistory = (months: number, existingData?: CreditHistory[]) => {
//     const maxMonths = Math.min(months, 6)
//     const newHistory: CreditHistory[] = []
    
//     for (let i = 1; i <= maxMonths; i++) {
//       const existingEntry = existingData && i <= existingData.length 
//         ? existingData[i - 1] 
//         : null
      
//       newHistory.push({
//         months_ago: String(i),
//         number_of_transaction: existingEntry?.number_of_transaction || '',
//         transaction_volume: existingEntry?.transaction_volume || '',
//         number_of_chargeback: existingEntry?.number_of_chargeback || '',
//         chargeback_volume: existingEntry?.chargeback_volume || '',
//         number_of_refunds: existingEntry?.number_of_refunds || '',
//         refund_volume: existingEntry?.refund_volume || '',
//       })
//     }
    
//     setCreditCardHistory(newHistory)
//     setNumberOfMonths(maxMonths)
//   }

//   // Fetch existing business data
//   useEffect(() => {
//     if (applicationId) {
//       fetchBusinessData()
//     }
//   }, [applicationId])

//   const fetchBusinessData = 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.businessProfile) {
//         const formData = response.data.businessProfile
//         setIsEditMode(true)
//         prefillFormData(formData)
//       } else {
//         setIsEditMode(false)
//       }

//       // Handle card types from the response
//       if (response.data && response.data.cardTypes && Array.isArray(response.data.cardTypes)) {
//         const cardTypeIds = response.data.cardTypes.map((card: CardTypeMapping) => card.cardtypeId)
//         setSelectedCardTypes(cardTypeIds)
//       }

//       // Handle other card details
//       if (response.data && response.data.businessProfile && response.data.businessProfile.otherCardDetails) {
//         setOtherCardDetails(response.data.businessProfile.otherCardDetails)
//       }

//       // Now check for incorporation date from company profile to calculate length of time
//       if (response.data && response.data.companyProfile && Array.isArray(response.data.companyProfile)) {
//         const mainCompany = response.data.companyProfile.find((item: any) => item.isparent === false || item.isparent === null)
//         if (mainCompany && mainCompany.incorporationDate) {
//           const calculatedLength = calculateLengthOfTime(mainCompany.incorporationDate)
//           if (calculatedLength) {
//             setBusiness(prev => ({
//               ...prev,
//               length_of_time_business: calculatedLength
//             }))
//           }
//         }
//       }
//     } catch (err: any) {
//       console.error('Error fetching business data:', err)
//       if (err.response?.status === 404) {
//         setIsEditMode(false)
//       } else {
//         toast.error('Failed to load business data')
//       }
//     } finally {
//       setFetchingData(false)
//     }
//   }

//   const prefillFormData = (data: any) => {
//     if (data.descriptionOfProducts) {
//       setBusiness(prev => ({ ...prev, description_of_products: data.descriptionOfProducts }))
//     }
//     if (data.lengthOfBusiness) {
//       setBusiness(prev => ({ ...prev, length_of_time_business: data.lengthOfBusiness }))
//     }
//     if (data.merchantCategoryCode) {
//       setBusiness(prev => ({ ...prev, merchant_cat_code: data.merchantCategoryCode }))
//     }
//     if (data.website) {
//       setBusiness(prev => ({ ...prev, website: data.website }))
//     }
//     if (data.betaWebsite) {
//       setHasBetaSite(true)
//       setBetaWebsite(data.betaWebsite)
//     }
//     if (data.username) {
//       setBetaUsername(data.username)
//     }
//     if (data.password) {
//       setHasExistingPassword(true)
//       setIsEditingPassword(false)
//       setBetaPassword('')
//     } else {
//       setHasExistingPassword(false)
//       setBetaPassword('')
//     }
//     if (data.descriptor !== undefined && data.descriptor !== null) {
//       setBusiness(prev => ({ ...prev, descriptor: data.descriptor || '' }))
//     }
//     if (data.cityField) {
//       setBusiness(prev => ({ ...prev, city_field: data.cityField }))
//     }
//     if (data.isDynamicDescriptor !== undefined) {
//       setBusiness(prev => ({ ...prev, dynamic_descriptors: data.isDynamicDescriptor }))
//     }
//     if (data.isBankruptcy !== undefined) {
//       setBusiness(prev => ({ ...prev, field_for_bankruptcy: data.isBankruptcy }))
//     }
//     if (data.fieldForBankruptcyDate) {
//       setBusiness(prev => ({ ...prev, field_for_bankruptcy_date: data.fieldForBankruptcyDate }))
//     }
//     if (data.isAcceptedCreditCards !== undefined) {
//       setBusiness(prev => ({ ...prev, accepted_credit_cards: data.isAcceptedCreditCards }))
//     }
    
//     let savedHistory: CreditHistory[] = []
//     if (data.creditCardHistory && Array.isArray(data.creditCardHistory) && data.creditCardHistory.length > 0) {
//       savedHistory = data.creditCardHistory.map((item: any) => ({
//         months_ago: item.months_ago || '',
//         number_of_transaction: item.number_of_transaction || item.numberOfTransaction || '',
//         transaction_volume: item.transaction_volume || item.transactionVolume || '',
//         number_of_chargeback: item.number_of_chargeback || item.numberOfChargeback || '',
//         chargeback_volume: item.chargeback_volume || item.chargebackVolume || '',
//         number_of_refunds: item.number_of_refunds || item.numberOfRefunds || '',
//         refund_volume: item.refund_volume || item.refundVolume || '',
//       }))
//     }
    
//     if (savedHistory.length > 0) {
//       setSavedCreditHistory(savedHistory)
//     }
    
//     if (data.acceptedCreditCardMonths) {
//       const months = parseInt(data.acceptedCreditCardMonths)
//       setBusiness(prev => ({ ...prev, accepted_credit_cards_months: String(months) }))
//       if (months > 0) {
//         setShowCreditHistory(true)
//         initializeCreditHistory(months, savedHistory.length > 0 ? savedHistory : undefined)
//       }
//     } else if (savedHistory.length > 0) {
//       const months = Math.min(savedHistory.length, 6)
//       setBusiness(prev => ({ ...prev, accepted_credit_cards_months: String(months) }))
//       setShowCreditHistory(true)
//       initializeCreditHistory(months, savedHistory)
//     }

//     if (data.hasCardSchemeProgram !== undefined) {
//       setBusiness(prev => ({ ...prev, card_scheme_program: data.hasCardSchemeProgram }))
//     }
//     if (data.cardSchemeProgramDetails && data.cardSchemeProgramDetails !== 'NA') {
//       setBusiness(prev => ({ ...prev, card_scheme_program_provide_details: data.cardSchemeProgramDetails }))
//     }
//     if (data.previousPaymentServiceProvider) {
//       setBusiness(prev => ({ ...prev, previous_payment_service_provider: data.previousPaymentServiceProvider }))
//     }
//     if (data.previousAcquirer) {
//       setBusiness(prev => ({ ...prev, previous_acquirer: data.previousAcquirer }))
//     }
//     if (data.reasonForLeavingAcquirer) {
//       setBusiness(prev => ({ ...prev, leaving_current_acquirer: data.reasonForLeavingAcquirer }))
//     }
//     if (data.monthlySalesVolume !== undefined && data.monthlySalesVolume !== null) {
//       setBusiness(prev => ({ ...prev, monthly_sales_volume: String(data.monthlySalesVolume) }))
//     }
//     if (data.salesCurrency) {
//       setBusiness(prev => ({ ...prev, currency: data.salesCurrency }))
//     }
//     if (data.avgTransValue !== undefined && data.avgTransValue !== null) {
//       setBusiness(prev => ({ ...prev, avg_transaction_value: String(data.avgTransValue) }))
//     }
//     if (data.highestTransValue !== undefined && data.highestTransValue !== null) {
//       setBusiness(prev => ({ ...prev, highest_transaction_value: String(data.highestTransValue) }))
//     }
//     if (data.oneTimePayment !== undefined) {
//       setBusiness(prev => ({ ...prev, one_time_payment: data.oneTimePayment }))
//     }
//     if (data.recurringPayment !== undefined) {
//       setBusiness(prev => ({ ...prev, recurring_payment: data.recurringPayment }))
//     }
//     if (data.domestic !== undefined && data.domestic !== null) {
//       setBusiness(prev => ({ ...prev, domestic: String(data.domestic) }))
//     }
//     if (data.europe !== undefined && data.europe !== null) {
//       setBusiness(prev => ({ ...prev, europe: String(data.europe) }))
//     }
//     if (data.usa !== undefined && data.usa !== null) {
//       setBusiness(prev => ({ ...prev, usa: String(data.usa) }))
//     }
//     if (data.asia !== undefined && data.asia !== null) {
//       setBusiness(prev => ({ ...prev, asia: String(data.asia) }))
//     }
//     if (data.restOfWorld !== undefined && data.restOfWorld !== null) {
//       setBusiness(prev => ({ ...prev, rest_of_world: String(data.restOfWorld) }))
//     }
//     if (data.ecommerce !== undefined && data.ecommerce !== null) {
//       setBusiness(prev => ({ ...prev, e_commerce: String(data.ecommerce) }))
//     }
//     if (data.cardPresent !== undefined && data.cardPresent !== null) {
//       setBusiness(prev => ({ ...prev, card_present: String(data.cardPresent) }))
//     }
//     if (data.mpos !== undefined && data.mpos !== null) {
//       setBusiness(prev => ({ ...prev, m_pos: String(data.mpos) }))
//     }
//     if (data.moto !== undefined && data.moto !== null) {
//       setBusiness(prev => ({ ...prev, moto: String(data.moto) }))
//     }
//     if (data.immediately !== undefined && data.immediately !== null) {
//       setBusiness(prev => ({ ...prev, immediately: String(data.immediately) }))
//     }
//     if (data.withinFourWeeks !== undefined && data.withinFourWeeks !== null) {
//       setBusiness(prev => ({ ...prev, within_four_weeks: String(data.withinFourWeeks) }))
//     }
//     if (data.within5To14Weeks !== undefined && data.within5To14Weeks !== null) {
//       setBusiness(prev => ({ ...prev, within_5_14_weeks: String(data.within5To14Weeks) }))
//     }
//     if (data.moreThan14Weeks !== undefined && data.moreThan14Weeks !== null) {
//       setBusiness(prev => ({ ...prev, more_than_14_weeks: String(data.moreThan14Weeks) }))
//     }
//     if (data.isUponPurchase !== undefined) {
//       setBusiness(prev => ({ ...prev, is_upon_purchase: data.isUponPurchase }))
//     }
//     if (data.isWithDownload !== undefined) {
//       setBusiness(prev => ({ ...prev, is_with_download: data.isWithDownload }))
//     }
//     if (data.isonDelivery !== undefined) {
//       setBusiness(prev => ({ ...prev, is_on_delivery: data.isonDelivery }))
//     }
//     if (data.isOtherPaymentOption !== undefined) {
//       setBusiness(prev => ({ ...prev, is_other_payment_option: data.isOtherPaymentOption }))
//     }
//     if (data.otherPaymentDetails && data.otherPaymentDetails !== 'NA') {
//       setBusiness(prev => ({ ...prev, other_payment_details: data.otherPaymentDetails }))
//     }
//     if (data.isOfferAffiliateProg !== undefined) {
//       setBusiness(prev => ({ ...prev, is_offer_affiliate_prog: data.isOfferAffiliateProg }))
//     }
//     if (data.offerAffiliateProgDetails && data.offerAffiliateProgDetails !== 'NA') {
//       setBusiness(prev => ({ ...prev, offer_affiliate_prog_details: data.offerAffiliateProgDetails }))
//     }
//     if (data.isNeedSoftwService !== undefined) {
//       setBusiness(prev => ({ ...prev, is_need_soft_service: data.isNeedSoftwService }))
//     }
//     if (data.softwareServDetails && data.softwareServDetails !== 'NA') {
//       setBusiness(prev => ({ ...prev, software_service_details: data.softwareServDetails }))
//     }
//   }

//   const handleBusinessChange = (e: React.ChangeEvent<HTMLInputElement>) => {
//     const { name, value, type, checked } = e.target
    
//     // Handle checkbox/switch fields
//     if (type === 'checkbox') {
//       setBusiness(prev => ({ ...prev, [name]: checked }))
//       if (errors[name]) {
//         setErrors(prev => ({ ...prev, [name]: '' }))
//       }
//       return
//     }
    
//     // Handle months field specially
//     if (name === 'accepted_credit_cards_months') {
//       const numValue = parseInt(value) || 0
//       setBusiness(prev => ({ ...prev, [name]: value }))
      
//       // Run live validation
//       const errorMsg = runLiveValidation(name, value)
//       setErrors(prev => ({ ...prev, [name]: errorMsg }))
      
//       if (numValue > 0 && business.accepted_credit_cards) {
//         const maxMonths = Math.min(numValue, 6)
//         setShowCreditHistory(true)
        
//         const existingData = savedCreditHistory.length > 0 ? savedCreditHistory : creditCardHistory
        
//         const newHistory: CreditHistory[] = []
//         for (let i = 1; i <= maxMonths; i++) {
//           const existingEntry = existingData && i <= existingData.length 
//             ? existingData[i - 1] 
//             : null
          
//           newHistory.push({
//             months_ago: String(i),
//             number_of_transaction: existingEntry?.number_of_transaction || '',
//             transaction_volume: existingEntry?.transaction_volume || '',
//             number_of_chargeback: existingEntry?.number_of_chargeback || '',
//             chargeback_volume: existingEntry?.chargeback_volume || '',
//             number_of_refunds: existingEntry?.number_of_refunds || '',
//             refund_volume: existingEntry?.refund_volume || '',
//           })
//         }
        
//         setCreditCardHistory(newHistory)
//         setNumberOfMonths(maxMonths)
        
//         if (numValue > creditCardHistory.length) {
//           setSavedCreditHistory(newHistory)
//         }
//       } else {
//         setShowCreditHistory(false)
//         setCreditCardHistory([])
//         setNumberOfMonths(0)
//       }
//       return
//     }

//     // Handle other text fields
//     if (name === 'length_of_time_business') {
//       return
//     }

//     setBusiness(prev => ({ ...prev, [name]: value }))

//     // Run live validation
//     const errorMsg = runLiveValidation(name, value)
//     setErrors(prev => ({ ...prev, [name]: errorMsg }))

//     if (name === 'accepted_credit_cards' && !checked) {
//       setShowCreditHistory(false)
//       setCreditCardHistory([])
//       setSavedCreditHistory([])
//       setNumberOfMonths(0)
//     }
//   }

//   const handleCreditHistoryChange = (index: number, field: string, value: string) => {
//     const newHistory = [...creditCardHistory]
//     newHistory[index] = { ...newHistory[index], [field]: value }
//     setCreditCardHistory(newHistory)
//     setSavedCreditHistory(newHistory)
//   }

//   const handleCardTypeToggle = (cardUid: string) => {
//     setSelectedCardTypes(prev =>
//       prev.includes(cardUid)
//         ? prev.filter(id => id !== cardUid)
//         : [...prev, cardUid]
//     )
//   }

//   const handleEditPassword = () => {
//     setIsEditingPassword(true)
//     setBetaPassword('')
//   }

//   const handleCancelEditPassword = () => {
//     setIsEditingPassword(false)
//     setBetaPassword('')
//   }

//   const buildRequestBody = () => {
//     const requestBody: any = {
//       application_id: parseInt(applicationId),
//       description_of_products: business.description_of_products || '',
//       length_of_time_business: business.length_of_time_business || '',
//       merchant_cat_code: business.merchant_cat_code || '',
//       website: business.website || '',
//       descriptor: business.descriptor || '',
//       city_field: business.city_field || '',
//       dynamic_descriptors: business.dynamic_descriptors,
//       field_for_bankruptcy: business.field_for_bankruptcy,
//       field_for_bankruptcy_date: business.field_for_bankruptcy_date || '',
//       accepted_credit_cards: business.accepted_credit_cards,
//       accepted_credit_cards_months: business.accepted_credit_cards_months || '',
//       card_scheme_program: business.card_scheme_program,
//       card_scheme_program_provide_details: business.card_scheme_program_provide_details || '',
//       previous_payment_service_provider: business.previous_payment_service_provider || '',
//       previous_acquirer: business.previous_acquirer || '',
//       leaving_current_acquirer: business.leaving_current_acquirer || '',
//       monthly_sales_volume: business.monthly_sales_volume || '',
//       currency: business.currency || '$',
//       avg_transaction_value: business.avg_transaction_value || '',
//       highest_transaction_value: business.highest_transaction_value || '',
//       one_time_payment: business.one_time_payment,
//       recurring_payment: business.recurring_payment,
//       domestic: business.domestic || '',
//       europe: business.europe || '',
//       usa: business.usa || '',
//       asia: business.asia || '',
//       rest_of_world: business.rest_of_world || '',
//       e_commerce: business.e_commerce || '',
//       card_present: business.card_present || '',
//       m_pos: business.m_pos || '',
//       moto: business.moto || '',
//       immediately: business.immediately || '',
//       within_four_weeks: business.within_four_weeks || '',
//       within_5_14_weeks: business.within_5_14_weeks || '',
//       more_than_14_weeks: business.more_than_14_weeks || '',
//       is_upon_purchase: business.is_upon_purchase,
//       is_with_download: business.is_with_download,
//       is_on_delivery: business.is_on_delivery,
//       is_other_payment_option: business.is_other_payment_option,
//       other_payment_details: business.other_payment_details || '',
//       is_offer_affiliate_prog: business.is_offer_affiliate_prog,
//       offer_affiliate_prog_details: business.offer_affiliate_prog_details || '',
//       is_need_soft_service: business.is_need_soft_service,
//       software_service_details: business.software_service_details || '',
//     }

//     if (hasBetaSite) {
//       requestBody.beta_website = betaWebsite || ''
//       requestBody.username = betaUsername || ''
      
//       if (isEditingPassword && betaPassword) {
//         requestBody.password = betaPassword
//       } else if (!hasExistingPassword && betaPassword) {
//         requestBody.password = betaPassword
//       } else if (!isEditingPassword && hasExistingPassword) {
//         requestBody.password = 'True'
//       }
//     }

//     if (business.accepted_credit_cards && parseInt(business.accepted_credit_cards_months) > 0 && creditCardHistory.length > 0) {
//       const historyWithMonths = creditCardHistory.map(({ months_ago, number_of_transaction, transaction_volume, number_of_chargeback, chargeback_volume, number_of_refunds, refund_volume }) => ({
//         months_ago: parseInt(months_ago),
//         number_of_transaction: number_of_transaction || '0',
//         transaction_volume: transaction_volume || '0',
//         number_of_chargeback: number_of_chargeback || '0',
//         chargeback_volume: chargeback_volume || '0',
//         number_of_refunds: number_of_refunds || '0',
//         refund_volume: refund_volume || '0',
//       }))
//       requestBody.credit_card_history = historyWithMonths
//     }

//     if (selectedCardTypes && selectedCardTypes.length > 0) {
//       requestBody.card_type = selectedCardTypes
//     }

//     const otherCard = cardTypesList.find(card => card.cardName === 'Other' || card.cardType === 'Other')
//     if (otherCard && selectedCardTypes.includes(otherCard.uid) && otherCardDetails) {
//       requestBody.otherCardDetails = otherCardDetails
//     }

//     return requestBody
//   }

//   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.businessProfile}${applicationId}`,
//           requestBody
//         )
//         toast.success('Business profile updated successfully!')
//       } else {
//         response = await axiosInstance.post(
//           endpoints.merchantApplication.businessProfile,
//           requestBody
//         )
//         toast.success('Business profile created successfully!')
//         setIsEditMode(true)
//       }

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

//       let errorMessage = isEditMode
//         ? 'Failed to update business profile. Please try again.'
//         : 'Failed to create business profile. 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)
//     }
//   }

//   const getMonthSuffix = (num: number) => {
//     if (num === 1) return '1st'
//     if (num === 2) return '2nd'
//     if (num === 3) return '3rd'
//     return `${num}th`
//   }

//   // ─── 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 || loadingDropdowns) {
//     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 }}>
//                 Business Profile Details
//               </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 filled fields, orange "Not Provided" indicates missing information.'
//                   : 'Fill the form to create a new record.'}
//               </Typography>
//             </Alert>

//             {/* Main Form */}
//             <Paper elevation={0} sx={{ mb: 4, p: 3, bgcolor: 'background.paper', borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
//               <SectionHeader color="primary.main" title="Business Information" />
//               <Grid container spacing={3}>
//                 <Grid item xs={12}>
//                   <SmartTextField
//                     label="Detailed Description of Products/Services Sold"
//                     name="description_of_products"
//                     value={business.description_of_products}
//                     onChange={handleBusinessChange}
//                     error={errors.description_of_products}
//                     helperText={errors.description_of_products}
//                     placeholder="Please provide a detailed description of the products or services your business sells..."
//                     multiline
//                     rows={3}
//                     isEditMode={isEditMode}
//                   />
//                 </Grid>

//                 <Grid item xs={12} sm={6}>
//                   <SmartTextField
//                     label="Length of time in business"
//                     name="length_of_time_business"
//                     value={business.length_of_time_business}
//                     onChange={handleBusinessChange}
//                     error={errors.length_of_time_business}
//                     helperText={errors.length_of_time_business || "Auto-calculated from incorporation date"}
//                     placeholder="e.g., 5 years, 2 months, 10 days"
//                     isEditMode={isEditMode}
//                     disabled
//                     InputProps={{
//                       sx: { bgcolor: 'action.hover' }
//                     }}
//                   />
//                 </Grid>

//                 <Grid item xs={12} sm={6}>
//                   <SmartTextField
//                     label="Merchant Category (MCC)"
//                     name="merchant_cat_code"
//                     value={business.merchant_cat_code}
//                     onChange={handleBusinessChange}
//                     error={errors.merchant_cat_code}
//                     helperText={errors.merchant_cat_code}
//                     select
//                     isEditMode={isEditMode}
//                   >
//                     <MenuItem value="" disabled>Select</MenuItem>
//                     {merchantCategories.map((category) => (
//                       <MenuItem key={category.id} value={category.code}>
//                         {category.name} ({category.code})
//                       </MenuItem>
//                     ))}
//                   </SmartTextField>
//                 </Grid>

//                 <Grid item xs={12}>
//                   <Grid container spacing={3} alignItems="flex-start">
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Website(s) (Comma-Separated)"
//                         name="website"
//                         value={business.website}
//                         onChange={handleBusinessChange}
//                         error={errors.website}
//                         helperText={errors.website}
//                         placeholder="https://example.com, https://store.example.com"
//                         isEditMode={isEditMode}
//                       />
//                     </Grid>

//                     <Grid item xs={12} sm={6}>
//                       <SmartSwitch
//                         label="Beta Site(s)"
//                         checked={hasBetaSite}
//                         onChange={(e) => setHasBetaSite(e.target.checked)}
//                         name="hasBetaSite"
//                         isEditMode={isEditMode}
//                         helperText="Toggle on to add website details"
//                       />
//                     </Grid>

//                     {hasBetaSite && (
//                       <Grid item xs={12}>
//                         <Box sx={{ bgcolor: 'action.hover', borderRadius: 2, p: 3, mt: 1 }}>
//                           <Typography variant="h6" sx={{ fontWeight: 600, mb: 3 }}>
//                             Beta Website Details
//                           </Typography>
//                           <Grid container spacing={2}>
//                             <Grid item xs={12}>
//                               <SmartTextField
//                                 label="Beta Website URL"
//                                 name="betaWebsite"
//                                 value={betaWebsite}
//                                 onChange={(e) => setBetaWebsite(e.target.value)}
//                                 placeholder="https://beta.example.com"
//                                 isEditMode={isEditMode}
//                               />
//                             </Grid>
//                             <Grid item xs={12} sm={6}>
//                               <SmartTextField
//                                 label="Username"
//                                 name="betaUsername"
//                                 value={betaUsername}
//                                 onChange={(e) => setBetaUsername(e.target.value)}
//                                 isEditMode={isEditMode}
//                               />
//                             </Grid>
//                             <Grid item xs={12} sm={6}>
//                               <Box>
//                                 <SmartTextField
//                                   label="Password"
//                                   name="betaPassword"
//                                   value={betaPassword}
//                                   onChange={(e) => setBetaPassword(e.target.value)}
//                                   type="password"
//                                   disabled={!isEditingPassword && hasExistingPassword}
//                                   isEditMode={isEditMode}
//                                   placeholder={!isEditingPassword && hasExistingPassword ? "••••••••" : "Enter password"}
//                                   hideStatus={true} // This hides the green tick and "Not Provided" for password field
//                                   InputProps={{
//                                     sx: {
//                                       backgroundColor: !isEditingPassword && hasExistingPassword ? '#f5f5f5' : 'transparent',
//                                     }
//                                   }}
//                                 />
//                                 <Box sx={{ display: 'flex', gap: 1, mt: 1, alignItems: 'center', flexWrap: 'wrap' }}>
//                                   {hasExistingPassword && !isEditingPassword ? (
//                                     <>
//                                       <Chip 
//                                         label="✓ Password Already Set" 
//                                         color="success" 
//                                         size="small"
//                                       />
//                                       <Typography variant="caption" color="text.secondary">
//                                         Click
//                                       </Typography>
//                                       <Button
//                                         size="small"
//                                         variant="outlined"
//                                         color="primary"
//                                         onClick={handleEditPassword}
//                                         sx={{ minWidth: '80px', height: '30px' }}
//                                       >
//                                         Edit
//                                       </Button>
//                                       <Typography variant="caption" color="text.secondary">
//                                         to change password
//                                       </Typography>
//                                     </>
//                                   ) : hasExistingPassword && isEditingPassword ? (
//                                     <>
//                                       <Chip 
//                                         label="Editing Password" 
//                                         color="warning" 
//                                         size="small"
//                                       />
//                                       <Button
//                                         size="small"
//                                         variant="outlined"
//                                         color="error"
//                                         onClick={handleCancelEditPassword}
//                                         sx={{ minWidth: '80px', height: '30px' }}
//                                       >
//                                         Cancel
//                                       </Button>
//                                       <Typography variant="caption" color="warning.main">
//                                         Enter new password or cancel to keep existing
//                                       </Typography>
//                                     </>
//                                   ) : (
//                                     <Typography variant="caption" color="text.secondary">
//                                       Set a password for the beta site
//                                     </Typography>
//                                   )}
//                                 </Box>
//                               </Box>
//                             </Grid>
//                           </Grid>
//                         </Box>
//                       </Grid>
//                     )}
//                   </Grid>
//                 </Grid>

//                 <Grid item xs={12} sm={6}>
//                   <SmartTextField
//                     label="Credit Card Descriptor (Max 22 Char.)"
//                     name="descriptor"
//                     value={business.descriptor}
//                     onChange={handleBusinessChange}
//                     error={errors.descriptor}
//                     helperText={errors.descriptor}
//                     inputProps={{ maxLength: 22 }}
//                     isEditMode={isEditMode}
//                   />
//                 </Grid>

//                 <Grid item xs={12} sm={6}>
//                   <SmartTextField
//                     label="DBA/City (Max 12 Char.)"
//                     name="city_field"
//                     value={business.city_field}
//                     onChange={handleBusinessChange}
//                     error={errors.city_field}
//                     helperText={errors.city_field}
//                     inputProps={{ maxLength: 12 }}
//                     isEditMode={isEditMode}
//                   />
//                 </Grid>

//                 <Grid item xs={12}>
//                   <SmartCheckbox
//                     label="Will You use 'Dynamic Descriptor'"
//                     checked={business.dynamic_descriptors}
//                     onChange={handleBusinessChange}
//                     name="dynamic_descriptors"
//                     isEditMode={isEditMode}
//                   />
//                 </Grid>

//                 <Grid item xs={12}>
//                   <SmartCheckbox
//                     label="Have you filed for bankruptcy before?"
//                     checked={business.field_for_bankruptcy}
//                     onChange={handleBusinessChange}
//                     name="field_for_bankruptcy"
//                     isEditMode={isEditMode}
//                   />
//                   {business.field_for_bankruptcy && (
//                     <Box sx={{ mt: 2, ml: 4 }}>
//                       <SmartTextField
//                         label="Date of Bankruptcy"
//                         name="field_for_bankruptcy_date"
//                         value={business.field_for_bankruptcy_date}
//                         onChange={handleBusinessChange}
//                         type="date"
//                         InputLabelProps={{ shrink: true }}
//                         isEditMode={isEditMode}
//                       />
//                     </Box>
//                   )}
//                 </Grid>

//                 <Grid item xs={12}>
//                   <SmartCheckbox
//                     label="Have you previously accepted Credit Card payments?"
//                     checked={business.accepted_credit_cards}
//                     onChange={handleBusinessChange}
//                     name="accepted_credit_cards"
//                     isEditMode={isEditMode}
//                   />
//                   {business.accepted_credit_cards && (
//                     <Box sx={{ mt: 2, ml: 4 }}>
//                       <Grid container spacing={2}>
//                         <Grid item xs={12} sm={6}>
//                           <SmartTextField
//                             label="How Many Months (Max 6)"
//                             name="accepted_credit_cards_months"
//                             value={business.accepted_credit_cards_months}
//                             onChange={handleBusinessChange}
//                             error={errors.accepted_credit_cards_months}
//                             helperText={errors.accepted_credit_cards_months || "Enter 1-6 months to show credit history"}
//                             type="number"
//                             inputProps={{ min: 0, max: 6 }}
//                             placeholder="Enter number of months (max 6)"
//                             isEditMode={isEditMode}
//                           />
//                         </Grid>
//                         <Grid item xs={12} sm={6}>
//                           <SmartTextField
//                             label="Previous Payment Service Provider"
//                             name="previous_payment_service_provider"
//                             value={business.previous_payment_service_provider}
//                             onChange={handleBusinessChange}
//                             placeholder="Enter provider name"
//                             isEditMode={isEditMode}
//                           />
//                         </Grid>
//                         <Grid item xs={12} sm={6}>
//                           <SmartTextField
//                             label="Previous Acquirer"
//                             name="previous_acquirer"
//                             value={business.previous_acquirer}
//                             onChange={handleBusinessChange}
//                             placeholder="Enter acquirer name"
//                             isEditMode={isEditMode}
//                           />
//                         </Grid>
//                         <Grid item xs={12} sm={6}>
//                           <SmartTextField
//                             label="Reason for leaving current acquirer"
//                             name="leaving_current_acquirer"
//                             value={business.leaving_current_acquirer}
//                             onChange={handleBusinessChange}
//                             placeholder="Enter reason"
//                             isEditMode={isEditMode}
//                           />
//                         </Grid>
//                       </Grid>

//                       {showCreditHistory && creditCardHistory.length > 0 && (
//                         <Box sx={{ mt: 4 }}>
//                           <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, color: 'primary.main' }}>
//                             PLEASE PROVIDE {creditCardHistory.length} MONTH{creditCardHistory.length > 1 ? 'S' : ''} OF MOST RECENT PROCESSING HISTORY BELOW
//                           </Typography>
//                           <Box sx={{ overflowX: 'auto' }}>
//                             <table style={{ width: '100%', borderCollapse: 'collapse' }}>
//                               <thead>
//                                 <tr style={{ backgroundColor: '#f5f5f5' }}>
//                                   <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '80px' }}>
//                                     MONTH
//                                   </th>
//                                   <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
//                                     Number of transactions
//                                   </th>
//                                   <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
//                                     Transaction volume
//                                   </th>
//                                   <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
//                                     Number of chargebacks
//                                   </th>
//                                   <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
//                                     Chargeback volume
//                                   </th>
//                                   <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
//                                     Number of refunds
//                                   </th>
//                                   <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
//                                     Refund volume
//                                   </th>
//                                 </tr>
//                               </thead>
//                               <tbody>
//                                 {creditCardHistory.map((history, index) => (
//                                   <tr key={index}>
//                                     <td style={{ padding: '12px', border: '1px solid #ddd', fontWeight: 500, textAlign: 'center' }}>
//                                       {getMonthSuffix(index + 1)}
//                                     </td>
//                                     <td style={{ padding: '8px', border: '1px solid #ddd' }}>
//                                       <TextField
//                                         fullWidth
//                                         type="number"
//                                         size="small"
//                                         value={history.number_of_transaction}
//                                         onChange={(e) => handleCreditHistoryChange(index, 'number_of_transaction', e.target.value)}
//                                         placeholder="0"
//                                       />
//                                     </td>
//                                     <td style={{ padding: '8px', border: '1px solid #ddd' }}>
//                                       <TextField
//                                         fullWidth
//                                         type="number"
//                                         size="small"
//                                         value={history.transaction_volume}
//                                         onChange={(e) => handleCreditHistoryChange(index, 'transaction_volume', e.target.value)}
//                                         placeholder="0"
//                                       />
//                                     </td>
//                                     <td style={{ padding: '8px', border: '1px solid #ddd' }}>
//                                       <TextField
//                                         fullWidth
//                                         type="number"
//                                         size="small"
//                                         value={history.number_of_chargeback}
//                                         onChange={(e) => handleCreditHistoryChange(index, 'number_of_chargeback', e.target.value)}
//                                         placeholder="0"
//                                       />
//                                     </td>
//                                     <td style={{ padding: '8px', border: '1px solid #ddd' }}>
//                                       <TextField
//                                         fullWidth
//                                         type="number"
//                                         size="small"
//                                         value={history.chargeback_volume}
//                                         onChange={(e) => handleCreditHistoryChange(index, 'chargeback_volume', e.target.value)}
//                                         placeholder="0"
//                                       />
//                                     </td>
//                                     <td style={{ padding: '8px', border: '1px solid #ddd' }}>
//                                       <TextField
//                                         fullWidth
//                                         type="number"
//                                         size="small"
//                                         value={history.number_of_refunds}
//                                         onChange={(e) => handleCreditHistoryChange(index, 'number_of_refunds', e.target.value)}
//                                         placeholder="0"
//                                       />
//                                     </td>
//                                     <td style={{ padding: '8px', border: '1px solid #ddd' }}>
//                                       <TextField
//                                         fullWidth
//                                         type="number"
//                                         size="small"
//                                         value={history.refund_volume}
//                                         onChange={(e) => handleCreditHistoryChange(index, 'refund_volume', e.target.value)}
//                                         placeholder="0"
//                                       />
//                                     </td>
//                                   </tr>
//                                 ))}
//                               </tbody>
//                             </table>
//                           </Box>
//                         </Box>
//                       )}
//                     </Box>
//                   )}
//                 </Grid>

//                 <Grid item xs={12}>
//                   <SmartCheckbox
//                     label="Have you ever flagged or been in violation of any card schema program?"
//                     checked={business.card_scheme_program}
//                     onChange={handleBusinessChange}
//                     name="card_scheme_program"
//                     isEditMode={isEditMode}
//                   />
//                   {business.card_scheme_program && (
//                     <Box sx={{ mt: 2, ml: 4 }}>
//                       <SmartTextField
//                         label="Please Provide Details"
//                         name="card_scheme_program_provide_details"
//                         value={business.card_scheme_program_provide_details}
//                         onChange={handleBusinessChange}
//                         placeholder="Please provide details about the violation..."
//                         multiline
//                         rows={3}
//                         isEditMode={isEditMode}
//                       />
//                     </Box>
//                   )}
//                 </Grid>

//                 <Grid item xs={12} sm={4}>
//                   <SmartTextField
//                     label="Estimated monthly sales volume"
//                     name="monthly_sales_volume"
//                     value={business.monthly_sales_volume}
//                     onChange={handleBusinessChange}
//                     error={errors.monthly_sales_volume}
//                     helperText={errors.monthly_sales_volume}
//                     type="number"
//                     placeholder="Enter amount"
//                     isEditMode={isEditMode}
//                     InputProps={{ startAdornment: <span>$ </span> }}
//                   />
//                 </Grid>

//                 <Grid item xs={12} sm={4}>
//                   <SmartTextField
//                     label="Highest transaction value"
//                     name="highest_transaction_value"
//                     value={business.highest_transaction_value}
//                     onChange={handleBusinessChange}
//                     error={errors.highest_transaction_value}
//                     helperText={errors.highest_transaction_value}
//                     type="number"
//                     placeholder="Enter amount"
//                     isEditMode={isEditMode}
//                     InputProps={{ startAdornment: <span>$ </span> }}
//                   />
//                 </Grid>

//                 <Grid item xs={12} sm={4}>
//                   <SmartTextField
//                     label="Average transaction value"
//                     name="avg_transaction_value"
//                     value={business.avg_transaction_value}
//                     onChange={handleBusinessChange}
//                     error={errors.avg_transaction_value}
//                     helperText={errors.avg_transaction_value}
//                     type="number"
//                     placeholder="Enter amount"
//                     isEditMode={isEditMode}
//                     InputProps={{ startAdornment: <span>$ </span> }}
//                   />
//                 </Grid>

//                 <Grid item xs={12} sm={6}>
//                   <FormControl component="fieldset">
//                     <FormLabel component="legend">Payment frequency</FormLabel>
//                     <Stack direction="row" spacing={2}>
//                       <SmartCheckbox
//                         label="One-time payment"
//                         checked={business.one_time_payment}
//                         onChange={handleBusinessChange}
//                         name="one_time_payment"
//                         isEditMode={isEditMode}
//                       />
//                       <SmartCheckbox
//                         label="Recurring payment"
//                         checked={business.recurring_payment}
//                         onChange={handleBusinessChange}
//                         name="recurring_payment"
//                         isEditMode={isEditMode}
//                       />
//                     </Stack>
//                   </FormControl>
//                 </Grid>

//                 <Grid item xs={12}>
//                   <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
//                     ORIGIN OF TRANSACTIONS (%)
//                   </Typography>
//                   <Grid container spacing={2}>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Domestic"
//                         type="number"
//                         name="domestic"
//                         value={business.domestic}
//                         onChange={handleBusinessChange}
//                         error={errors.domestic}
//                         helperText={errors.domestic}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Europe"
//                         type="number"
//                         name="europe"
//                         value={business.europe}
//                         onChange={handleBusinessChange}
//                         error={errors.europe}
//                         helperText={errors.europe}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="USA (Oceania)"
//                         type="number"
//                         name="usa"
//                         value={business.usa}
//                         onChange={handleBusinessChange}
//                         error={errors.usa}
//                         helperText={errors.usa}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Asia"
//                         type="number"
//                         name="asia"
//                         value={business.asia}
//                         onChange={handleBusinessChange}
//                         error={errors.asia}
//                         helperText={errors.asia}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Rest of world"
//                         type="number"
//                         name="rest_of_world"
//                         value={business.rest_of_world}
//                         onChange={handleBusinessChange}
//                         error={errors.rest_of_world}
//                         helperText={errors.rest_of_world}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                   </Grid>
//                 </Grid>

//                 <Grid item xs={12}>
//                   <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
//                     METHOD OF ACCEPTANCE (%)
//                   </Typography>
//                   <Grid container spacing={2}>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="E-commerce / M-Commerce"
//                         type="number"
//                         name="e_commerce"
//                         value={business.e_commerce}
//                         onChange={handleBusinessChange}
//                         error={errors.e_commerce}
//                         helperText={errors.e_commerce}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Card Present (POS)"
//                         type="number"
//                         name="card_present"
//                         value={business.card_present}
//                         onChange={handleBusinessChange}
//                         error={errors.card_present}
//                         helperText={errors.card_present}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="M-Pos (Mobile POS)"
//                         type="number"
//                         name="m_pos"
//                         value={business.m_pos}
//                         onChange={handleBusinessChange}
//                         error={errors.m_pos}
//                         helperText={errors.m_pos}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="MOTO"
//                         type="number"
//                         name="moto"
//                         value={business.moto}
//                         onChange={handleBusinessChange}
//                         error={errors.moto}
//                         helperText={errors.moto}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                   </Grid>
//                 </Grid>

//                 <Grid item xs={12}>
//                   <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
//                     DELIVERY TIME FOR GOODS/SERVICES (%)
//                   </Typography>
//                   <Grid container spacing={2}>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Immediately"
//                         type="number"
//                         name="immediately"
//                         value={business.immediately}
//                         onChange={handleBusinessChange}
//                         error={errors.immediately}
//                         helperText={errors.immediately}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Within 4 weeks"
//                         type="number"
//                         name="within_four_weeks"
//                         value={business.within_four_weeks}
//                         onChange={handleBusinessChange}
//                         error={errors.within_four_weeks}
//                         helperText={errors.within_four_weeks}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="Within 5-14 weeks"
//                         type="number"
//                         name="within_5_14_weeks"
//                         value={business.within_5_14_weeks}
//                         onChange={handleBusinessChange}
//                         error={errors.within_5_14_weeks}
//                         helperText={errors.within_5_14_weeks}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                     <Grid item xs={12} sm={6}>
//                       <SmartTextField
//                         label="More than 14 weeks"
//                         type="number"
//                         name="more_than_14_weeks"
//                         value={business.more_than_14_weeks}
//                         onChange={handleBusinessChange}
//                         error={errors.more_than_14_weeks}
//                         helperText={errors.more_than_14_weeks}
//                         isEditMode={isEditMode}
//                         InputProps={{ endAdornment: '%' }}
//                       />
//                     </Grid>
//                   </Grid>
//                 </Grid>

//                 <Grid item xs={12}>
//                   <FormControl component="fieldset">
//                     <FormLabel component="legend">When does payment take place?</FormLabel>
//                     <Stack direction="row" spacing={2} flexWrap="wrap">
//                       <SmartCheckbox
//                         label="Upon purchase"
//                         checked={business.is_upon_purchase}
//                         onChange={handleBusinessChange}
//                         name="is_upon_purchase"
//                         isEditMode={isEditMode}
//                       />
//                       <SmartCheckbox
//                         label="With download"
//                         checked={business.is_with_download}
//                         onChange={handleBusinessChange}
//                         name="is_with_download"
//                         isEditMode={isEditMode}
//                       />
//                       <SmartCheckbox
//                         label="On delivery"
//                         checked={business.is_on_delivery}
//                         onChange={handleBusinessChange}
//                         name="is_on_delivery"
//                         isEditMode={isEditMode}
//                       />
//                       <SmartCheckbox
//                         label="Other"
//                         checked={business.is_other_payment_option}
//                         onChange={handleBusinessChange}
//                         name="is_other_payment_option"
//                         isEditMode={isEditMode}
//                       />
//                     </Stack>
//                   </FormControl>
//                   {business.is_other_payment_option && (
//                     <Box sx={{ mt: 2 }}>
//                       <SmartTextField
//                         label="Please Provide Details"
//                         name="other_payment_details"
//                         value={business.other_payment_details}
//                         onChange={handleBusinessChange}
//                         placeholder="Please provide details about when payment takes place..."
//                         multiline
//                         rows={3}
//                         isEditMode={isEditMode}
//                       />
//                     </Box>
//                   )}
//                 </Grid>

//                 <Grid item xs={12}>
//                   <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
//                     Card types applying for
//                   </Typography>
//                   <Grid container spacing={2}>
//                     {cardTypesList.map((card) => (
//                       <Grid item xs={6} sm={4} md={3} key={card.uid}>
//                         <FormControlLabel
//                           control={
//                             <Checkbox
//                               checked={selectedCardTypes.includes(card.uid)}
//                               onChange={() => handleCardTypeToggle(card.uid)}
//                               sx={{
//                                 '&.Mui-checked': {
//                                   color: isEditMode ? '#2e7d32' : undefined,
//                                 },
//                               }}
//                             />
//                           }
//                           label={card.cardName || card.cardType}
//                         />
//                       </Grid>
//                     ))}
//                   </Grid>
//                   {selectedCardTypes.some(uid => {
//                     const card = cardTypesList.find(c => c.uid === uid)
//                     return card && (card.cardName === 'Other' || card.cardType === 'Other')
//                   }) && (
//                     <Box sx={{ mt: 2 }}>
//                       <SmartTextField
//                         label="Other Card Details"
//                         name="otherCardDetails"
//                         value={otherCardDetails}
//                         onChange={(e) => setOtherCardDetails(e.target.value)}
//                         placeholder="Please specify other card types..."
//                         multiline
//                         rows={2}
//                         isEditMode={isEditMode}
//                       />
//                     </Box>
//                   )}
//                 </Grid>

//                 <Grid item xs={12}>
//                   <SmartSwitch
//                     label="Do you offer / make use of affiliate programs?"
//                     checked={business.is_offer_affiliate_prog}
//                     onChange={handleBusinessChange}
//                     name="is_offer_affiliate_prog"
//                     isEditMode={isEditMode}
//                   />
//                   {business.is_offer_affiliate_prog && (
//                     <Box sx={{ mt: 2, ml: 4 }}>
//                       <SmartTextField
//                         label="Please provide details"
//                         name="offer_affiliate_prog_details"
//                         value={business.offer_affiliate_prog_details}
//                         onChange={handleBusinessChange}
//                         placeholder="Please provide details about your affiliate programs..."
//                         multiline
//                         rows={3}
//                         isEditMode={isEditMode}
//                       />
//                     </Box>
//                   )}
//                 </Grid>

//                 <Grid item xs={12}>
//                   <SmartSwitch
//                     label="Need Software As A Service"
//                     checked={business.is_need_soft_service}
//                     onChange={handleBusinessChange}
//                     name="is_need_soft_service"
//                     isEditMode={isEditMode}
//                   />
//                   {business.is_need_soft_service && (
//                     <Box sx={{ mt: 2, ml: 4 }}>
//                       <SmartTextField
//                         label="Please provide details"
//                         name="software_service_details"
//                         value={business.software_service_details}
//                         onChange={handleBusinessChange}
//                         placeholder="Please provide details about your software requirements..."
//                         multiline
//                         rows={3}
//                         isEditMode={isEditMode}
//                       />
//                     </Box>
//                   )}
//                 </Grid>
//               </Grid>
//             </Paper>

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

//             {/* Navigation */}
//             <Stack direction="row" spacing={2} justifyContent="flex-end">
//               <Button
//                 type="button"
//                 variant="outlined"
//                 size="large"
//                 onClick={onPrevious}
//                 sx={{ textTransform: 'none', px: 4 }}
//                 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 BusinessProfile


// tyscript issye 
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 MenuItem from '@mui/material/MenuItem'
import FormControlLabel from '@mui/material/FormControlLabel'
import Checkbox from '@mui/material/Checkbox'
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 FormControl from '@mui/material/FormControl'
import FormLabel from '@mui/material/FormLabel'

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

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

interface ValidationErrors {
  [key: string]: string
}

interface CreditHistory {
  months_ago: string
  number_of_transaction: string
  transaction_volume: string
  number_of_chargeback: string
  chargeback_volume: string
  number_of_refunds: string
  refund_volume: string
}

interface MerchantCategory {
  id: number
  uid: string
  createdAt: string
  updatedAt: string
  name: string
  code: string
  isActive: boolean
}

interface CardType {
  uid: string
  cardType: string
  cardName: string
}

interface CardTypeMapping {
  id: number
  uid: string
  createdAt: string
  updatedAt: string
  cardtypeId: string
}

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

const validateDescription = (val: string): string => {
  if (!val) return ''
  if (val.trim().length < 10)
    return 'Please provide at least 10 characters of detail. e.g. We sell electronics and provide repair services.'
  if (val.trim().length > 2000)
    return 'Description must not exceed 2000 characters.'
  if (/[<>@#\\]/.test(val))
    return 'Special characters like < > @ # \\ are not allowed.'
  return ''
}

const validateWebsite = (val: string): string => {
  if (!val) return ''
  const urls = val.split(',').map(u => u.trim())
  for (const url of urls) {
    if (url && !/^https?:\/\/[^\s]+$/.test(url))
      return 'Please enter valid URLs starting with http:// or https://. e.g. https://example.com'
  }
  return ''
}

const validateDescriptor = (val: string): string => {
  if (!val) return ''
  if (val.trim().length > 22)
    return 'Descriptor must not exceed 22 characters.'
  if (/[<>@#\\]/.test(val))
    return 'Special characters like < > @ # \\ are not allowed.'
  return ''
}

const validateCityField = (val: string): string => {
  if (!val) return ''
  if (val.trim().length > 12)
    return 'DBA/City must not exceed 12 characters.'
  if (!/^[A-Za-zÀ-ÿ\s'\-]+$/.test(val.trim()))
    return 'Only letters, spaces, hyphens and apostrophes are allowed.'
  return ''
}

const validateMonthlySales = (val: string): string => {
  if (!val) return ''
  if (!/^\d+(\.\d{1,2})?$/.test(val.trim()))
    return 'Please enter a valid numeric amount. e.g. 10000 or 25000.50'
  if (parseFloat(val) <= 0)
    return 'Amount must be greater than 0.'
  return ''
}

const validatePercentage = (val: string): string => {
  if (!val) return ''
  if (!/^\d+(\.\d{1,2})?$/.test(val.trim()))
    return 'Please enter a valid number. e.g. 25 or 50.5'
  const num = parseFloat(val)
  if (num < 0 || num > 100)
    return 'Please enter a value between 0 and 100.'
  return ''
}

const validateMonths = (val: string): string => {
  if (!val) return ''
  if (!/^\d+$/.test(val.trim()))
    return 'Please enter a valid number. e.g. 3'
  const num = parseInt(val)
  if (num < 1 || num > 6)
    return 'Please enter a number between 1 and 6.'
  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,
  required,
  inputProps,
  hideStatus,
}: any) => {
  const filled = value !== null && value !== undefined && String(value).trim() !== ''
  return (
    <Box>
      {!hideStatus && (
        <FieldLabel label={label} value={value} isEditMode={isEditMode} />
      )}
      {hideStatus && (
        <Typography variant="body2" sx={{ fontWeight: 500, color: 'text.secondary', mb: 0.5 }}>
          {label}
        </Typography>
      )}
      <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}
        required={required}
        inputProps={inputProps}
        sx={{
          '& .MuiOutlinedInput-root': {
            '& fieldset': { borderColor: isEditMode && filled && !hideStatus ? '#A5D6A7' : undefined },
            '&:hover fieldset': { borderColor: isEditMode && filled && !hideStatus ? '#66BB6A' : undefined },
          },
        }}
      >
        {children}
      </TextField>
    </Box>
  )
}

// ─── SmartCheckbox ────────────────────────────────────────────────────────────
const SmartCheckbox = ({
  label,
  checked,
  onChange,
  name,
  isEditMode,
}: {
  label: string
  checked: boolean
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void
  name: string
  isEditMode: boolean
}) => {
  return (
    <FormControlLabel
      control={
        <Checkbox
          checked={checked}
          onChange={onChange}
          name={name}
          sx={{
            '&.Mui-checked': {
              color: isEditMode ? '#2e7d32' : undefined,
            },
          }}
        />
      }
      label={label}
    />
  )
}

// ─── 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>
  )
}

// Helper function to calculate length of time in business
const calculateLengthOfTime = (incorporationDate: string): string => {
  if (!incorporationDate) return 'Not available'
  
  const start = new Date(incorporationDate)
  const now = new Date()
  
  let years = now.getFullYear() - start.getFullYear()
  let months = now.getMonth() - start.getMonth()
  let days = now.getDate() - start.getDate()
  
  if (days < 0) {
    months -= 1
    const prevMonth = new Date(now.getFullYear(), now.getMonth(), 0)
    days += prevMonth.getDate()
  }
  
  if (months < 0) {
    years -= 1
    months += 12
  }
  
  if (years < 0) {
    const absYears = Math.abs(years)
    const absMonths = Math.abs(months)
    const absDays = Math.abs(days)
    
    const parts: string[] = []
    if (absYears > 0) parts.push(`${absYears} year${absYears > 1 ? 's' : ''}`)
    if (absMonths > 0) parts.push(`${absMonths} month${absMonths > 1 ? 's' : ''}`)
    if (absDays > 0) parts.push(`${absDays} day${absDays > 1 ? 's' : ''}`)
    
    if (parts.length === 0) return 'Today'
    return parts.join(', ')
  }
  
  const parts: string[] = []
  if (years > 0) parts.push(`${years} year${years > 1 ? 's' : ''}`)
  if (months > 0) parts.push(`${months} month${months > 1 ? 's' : ''}`)
  if (days > 0) parts.push(`${days} day${days > 1 ? 's' : ''}`)
  
  if (parts.length === 0) return 'Today'
  return parts.join(', ')
}

const BusinessProfile = ({ onNext, onPrevious, applicationId }: BusinessProfileProps) => {
  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)

  // Dropdown data states
  const [merchantCategories, setMerchantCategories] = useState<MerchantCategory[]>([])
  const [cardTypesList, setCardTypesList] = useState<CardType[]>([])
  const [loadingDropdowns, setLoadingDropdowns] = useState<boolean>(true)

  // Main business state
  const [business, setBusiness] = useState({
    description_of_products: '',
    length_of_time_business: '',
    merchant_cat_code: '',
    website: '',
    descriptor: '',
    city_field: '',
    dynamic_descriptors: false,
    field_for_bankruptcy: false,
    field_for_bankruptcy_date: '',
    accepted_credit_cards: false,
    accepted_credit_cards_months: '',
    card_scheme_program: false,
    card_scheme_program_provide_details: '',
    previous_payment_service_provider: '',
    previous_acquirer: '',
    leaving_current_acquirer: '',
    monthly_sales_volume: '',
    currency: '$',
    avg_transaction_value: '',
    highest_transaction_value: '',
    one_time_payment: false,
    recurring_payment: false,
    domestic: '',
    europe: '',
    usa: '',
    asia: '',
    rest_of_world: '',
    e_commerce: '',
    card_present: '',
    m_pos: '',
    moto: '',
    immediately: '',
    within_four_weeks: '',
    within_5_14_weeks: '',
    more_than_14_weeks: '',
    is_upon_purchase: false,
    is_with_download: false,
    is_on_delivery: false,
    is_other_payment_option: false,
    other_payment_details: '',
    is_offer_affiliate_prog: false,
    offer_affiliate_prog_details: '',
    is_need_soft_service: false,
    software_service_details: '',
  })

  // Beta website state
  const [hasBetaSite, setHasBetaSite] = useState(false)
  const [betaWebsite, setBetaWebsite] = useState('')
  const [betaUsername, setBetaUsername] = useState('')
  const [betaPassword, setBetaPassword] = useState('')
  const [hasExistingPassword, setHasExistingPassword] = useState(false)
  const [isEditingPassword, setIsEditingPassword] = useState(false)

  // Credit card history - dynamic based on months entered (max 6)
  const [creditCardHistory, setCreditCardHistory] = useState<CreditHistory[]>([])
  const [savedCreditHistory, setSavedCreditHistory] = useState<CreditHistory[]>([])

  // Show credit card history table
  const [showCreditHistory, setShowCreditHistory] = useState<boolean>(false)
  const [numberOfMonths, setNumberOfMonths] = useState<number>(0)

  // Card types
  const [selectedCardTypes, setSelectedCardTypes] = useState<string[]>([])
  const [otherCardDetails, setOtherCardDetails] = useState('')

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

  // ─── Live validation router ───────────────────────────────────────────────
  const runLiveValidation = (field: string, value: string): string => {
    switch (field) {
      case 'description_of_products':
        return validateDescription(value)
      case 'website':
        return validateWebsite(value)
      case 'descriptor':
        return validateDescriptor(value)
      case 'city_field':
        return validateCityField(value)
      case 'monthly_sales_volume':
        return validateMonthlySales(value)
      case 'highest_transaction_value':
        return validateMonthlySales(value)
      case 'avg_transaction_value':
        return validateMonthlySales(value)
      case 'accepted_credit_cards_months':
        return validateMonths(value)
      case 'domestic':
      case 'europe':
      case 'usa':
      case 'asia':
      case 'rest_of_world':
      case 'e_commerce':
      case 'card_present':
      case 'm_pos':
      case 'moto':
      case 'immediately':
      case 'within_four_weeks':
      case 'within_5_14_weeks':
      case 'more_than_14_weeks':
        return validatePercentage(value)
      default:
        return ''
    }
  }

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

  // Fetch dropdown data
  useEffect(() => {
    const fetchDropdownData = async () => {
      try {
        setLoadingDropdowns(true)
        
        // Fetch merchant categories
        const mccResponse = await axiosInstance.get(endpoints.merchantApplication.merchantcategory)
        console.log('Merchant Categories Response:', mccResponse.data)
        
        if (mccResponse.data && Array.isArray(mccResponse.data)) {
          setMerchantCategories(mccResponse.data)
        }

        // Fetch card types
        const cardResponse = await axiosInstance.get(endpoints.merchantApplication.cardtype)
        console.log('Card Types Response:', cardResponse.data)
        
        if (cardResponse.data && Array.isArray(cardResponse.data)) {
          setCardTypesList(cardResponse.data)
        }
      } catch (err: any) {
        console.error('Error fetching dropdown data:', err)
        toast.error('Failed to load dropdown data')
      } finally {
        setLoadingDropdowns(false)
      }
    }

    fetchDropdownData()
  }, [])

  // Initialize credit card history based on months
  const initializeCreditHistory = (months: number, existingData?: CreditHistory[]) => {
    const maxMonths = Math.min(months, 6)
    const newHistory: CreditHistory[] = []
    
    for (let i = 1; i <= maxMonths; i++) {
      const existingEntry = existingData && i <= existingData.length 
        ? existingData[i - 1] 
        : null
      
      newHistory.push({
        months_ago: String(i),
        number_of_transaction: existingEntry?.number_of_transaction || '',
        transaction_volume: existingEntry?.transaction_volume || '',
        number_of_chargeback: existingEntry?.number_of_chargeback || '',
        chargeback_volume: existingEntry?.chargeback_volume || '',
        number_of_refunds: existingEntry?.number_of_refunds || '',
        refund_volume: existingEntry?.refund_volume || '',
      })
    }
    
    setCreditCardHistory(newHistory)
    setNumberOfMonths(maxMonths)
  }

  // Fetch existing business data
  useEffect(() => {
    if (applicationId) {
      fetchBusinessData()
    }
  }, [applicationId])

  const fetchBusinessData = 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.businessProfile) {
        const formData = response.data.businessProfile
        setIsEditMode(true)
        prefillFormData(formData)
      } else {
        setIsEditMode(false)
      }

      // Handle card types from the response
      if (response.data && response.data.cardTypes && Array.isArray(response.data.cardTypes)) {
        const cardTypeIds = response.data.cardTypes.map((card: CardTypeMapping) => card.cardtypeId)
        setSelectedCardTypes(cardTypeIds)
      }

      // Handle other card details
      if (response.data && response.data.businessProfile && response.data.businessProfile.otherCardDetails) {
        setOtherCardDetails(response.data.businessProfile.otherCardDetails)
      }

      // Now check for incorporation date from company profile to calculate length of time
      if (response.data && response.data.companyProfile && Array.isArray(response.data.companyProfile)) {
        const mainCompany = response.data.companyProfile.find((item: any) => item.isparent === false || item.isparent === null)
        if (mainCompany && mainCompany.incorporationDate) {
          const calculatedLength = calculateLengthOfTime(mainCompany.incorporationDate)
          if (calculatedLength) {
            setBusiness(prev => ({
              ...prev,
              length_of_time_business: calculatedLength
            }))
          }
        }
      }
    } catch (err: any) {
      console.error('Error fetching business data:', err)
      if (err.response?.status === 404) {
        setIsEditMode(false)
      } else {
        toast.error('Failed to load business data')
      }
    } finally {
      setFetchingData(false)
    }
  }

  const prefillFormData = (data: any) => {
    if (data.descriptionOfProducts) {
      setBusiness(prev => ({ ...prev, description_of_products: data.descriptionOfProducts }))
    }
    if (data.lengthOfBusiness) {
      setBusiness(prev => ({ ...prev, length_of_time_business: data.lengthOfBusiness }))
    }
    if (data.merchantCategoryCode) {
      setBusiness(prev => ({ ...prev, merchant_cat_code: data.merchantCategoryCode }))
    }
    if (data.website) {
      setBusiness(prev => ({ ...prev, website: data.website }))
    }
    if (data.betaWebsite) {
      setHasBetaSite(true)
      setBetaWebsite(data.betaWebsite)
    }
    if (data.username) {
      setBetaUsername(data.username)
    }
    if (data.password) {
      setHasExistingPassword(true)
      setIsEditingPassword(false)
      setBetaPassword('')
    } else {
      setHasExistingPassword(false)
      setBetaPassword('')
    }
    if (data.descriptor !== undefined && data.descriptor !== null) {
      setBusiness(prev => ({ ...prev, descriptor: data.descriptor || '' }))
    }
    if (data.cityField) {
      setBusiness(prev => ({ ...prev, city_field: data.cityField }))
    }
    if (data.isDynamicDescriptor !== undefined) {
      setBusiness(prev => ({ ...prev, dynamic_descriptors: data.isDynamicDescriptor }))
    }
    if (data.isBankruptcy !== undefined) {
      setBusiness(prev => ({ ...prev, field_for_bankruptcy: data.isBankruptcy }))
    }
    if (data.fieldForBankruptcyDate) {
      setBusiness(prev => ({ ...prev, field_for_bankruptcy_date: data.fieldForBankruptcyDate }))
    }
    if (data.isAcceptedCreditCards !== undefined) {
      setBusiness(prev => ({ ...prev, accepted_credit_cards: data.isAcceptedCreditCards }))
    }
    
    let savedHistory: CreditHistory[] = []
    if (data.creditCardHistory && Array.isArray(data.creditCardHistory) && data.creditCardHistory.length > 0) {
      savedHistory = data.creditCardHistory.map((item: any) => ({
        months_ago: item.months_ago || '',
        number_of_transaction: item.number_of_transaction || item.numberOfTransaction || '',
        transaction_volume: item.transaction_volume || item.transactionVolume || '',
        number_of_chargeback: item.number_of_chargeback || item.numberOfChargeback || '',
        chargeback_volume: item.chargeback_volume || item.chargebackVolume || '',
        number_of_refunds: item.number_of_refunds || item.numberOfRefunds || '',
        refund_volume: item.refund_volume || item.refundVolume || '',
      }))
    }
    
    if (savedHistory.length > 0) {
      setSavedCreditHistory(savedHistory)
    }
    
    if (data.acceptedCreditCardMonths) {
      const months = parseInt(data.acceptedCreditCardMonths)
      setBusiness(prev => ({ ...prev, accepted_credit_cards_months: String(months) }))
      if (months > 0) {
        setShowCreditHistory(true)
        initializeCreditHistory(months, savedHistory.length > 0 ? savedHistory : undefined)
      }
    } else if (savedHistory.length > 0) {
      const months = Math.min(savedHistory.length, 6)
      setBusiness(prev => ({ ...prev, accepted_credit_cards_months: String(months) }))
      setShowCreditHistory(true)
      initializeCreditHistory(months, savedHistory)
    }

    if (data.hasCardSchemeProgram !== undefined) {
      setBusiness(prev => ({ ...prev, card_scheme_program: data.hasCardSchemeProgram }))
    }
    if (data.cardSchemeProgramDetails && data.cardSchemeProgramDetails !== 'NA') {
      setBusiness(prev => ({ ...prev, card_scheme_program_provide_details: data.cardSchemeProgramDetails }))
    }
    if (data.previousPaymentServiceProvider) {
      setBusiness(prev => ({ ...prev, previous_payment_service_provider: data.previousPaymentServiceProvider }))
    }
    if (data.previousAcquirer) {
      setBusiness(prev => ({ ...prev, previous_acquirer: data.previousAcquirer }))
    }
    if (data.reasonForLeavingAcquirer) {
      setBusiness(prev => ({ ...prev, leaving_current_acquirer: data.reasonForLeavingAcquirer }))
    }
    if (data.monthlySalesVolume !== undefined && data.monthlySalesVolume !== null) {
      setBusiness(prev => ({ ...prev, monthly_sales_volume: String(data.monthlySalesVolume) }))
    }
    if (data.salesCurrency) {
      setBusiness(prev => ({ ...prev, currency: data.salesCurrency }))
    }
    if (data.avgTransValue !== undefined && data.avgTransValue !== null) {
      setBusiness(prev => ({ ...prev, avg_transaction_value: String(data.avgTransValue) }))
    }
    if (data.highestTransValue !== undefined && data.highestTransValue !== null) {
      setBusiness(prev => ({ ...prev, highest_transaction_value: String(data.highestTransValue) }))
    }
    if (data.oneTimePayment !== undefined) {
      setBusiness(prev => ({ ...prev, one_time_payment: data.oneTimePayment }))
    }
    if (data.recurringPayment !== undefined) {
      setBusiness(prev => ({ ...prev, recurring_payment: data.recurringPayment }))
    }
    if (data.domestic !== undefined && data.domestic !== null) {
      setBusiness(prev => ({ ...prev, domestic: String(data.domestic) }))
    }
    if (data.europe !== undefined && data.europe !== null) {
      setBusiness(prev => ({ ...prev, europe: String(data.europe) }))
    }
    if (data.usa !== undefined && data.usa !== null) {
      setBusiness(prev => ({ ...prev, usa: String(data.usa) }))
    }
    if (data.asia !== undefined && data.asia !== null) {
      setBusiness(prev => ({ ...prev, asia: String(data.asia) }))
    }
    if (data.restOfWorld !== undefined && data.restOfWorld !== null) {
      setBusiness(prev => ({ ...prev, rest_of_world: String(data.restOfWorld) }))
    }
    if (data.ecommerce !== undefined && data.ecommerce !== null) {
      setBusiness(prev => ({ ...prev, e_commerce: String(data.ecommerce) }))
    }
    if (data.cardPresent !== undefined && data.cardPresent !== null) {
      setBusiness(prev => ({ ...prev, card_present: String(data.cardPresent) }))
    }
    if (data.mpos !== undefined && data.mpos !== null) {
      setBusiness(prev => ({ ...prev, m_pos: String(data.mpos) }))
    }
    if (data.moto !== undefined && data.moto !== null) {
      setBusiness(prev => ({ ...prev, moto: String(data.moto) }))
    }
    if (data.immediately !== undefined && data.immediately !== null) {
      setBusiness(prev => ({ ...prev, immediately: String(data.immediately) }))
    }
    if (data.withinFourWeeks !== undefined && data.withinFourWeeks !== null) {
      setBusiness(prev => ({ ...prev, within_four_weeks: String(data.withinFourWeeks) }))
    }
    if (data.within5To14Weeks !== undefined && data.within5To14Weeks !== null) {
      setBusiness(prev => ({ ...prev, within_5_14_weeks: String(data.within5To14Weeks) }))
    }
    if (data.moreThan14Weeks !== undefined && data.moreThan14Weeks !== null) {
      setBusiness(prev => ({ ...prev, more_than_14_weeks: String(data.moreThan14Weeks) }))
    }
    if (data.isUponPurchase !== undefined) {
      setBusiness(prev => ({ ...prev, is_upon_purchase: data.isUponPurchase }))
    }
    if (data.isWithDownload !== undefined) {
      setBusiness(prev => ({ ...prev, is_with_download: data.isWithDownload }))
    }
    if (data.isonDelivery !== undefined) {
      setBusiness(prev => ({ ...prev, is_on_delivery: data.isonDelivery }))
    }
    if (data.isOtherPaymentOption !== undefined) {
      setBusiness(prev => ({ ...prev, is_other_payment_option: data.isOtherPaymentOption }))
    }
    if (data.otherPaymentDetails && data.otherPaymentDetails !== 'NA') {
      setBusiness(prev => ({ ...prev, other_payment_details: data.otherPaymentDetails }))
    }
    if (data.isOfferAffiliateProg !== undefined) {
      setBusiness(prev => ({ ...prev, is_offer_affiliate_prog: data.isOfferAffiliateProg }))
    }
    if (data.offerAffiliateProgDetails && data.offerAffiliateProgDetails !== 'NA') {
      setBusiness(prev => ({ ...prev, offer_affiliate_prog_details: data.offerAffiliateProgDetails }))
    }
    if (data.isNeedSoftwService !== undefined) {
      setBusiness(prev => ({ ...prev, is_need_soft_service: data.isNeedSoftwService }))
    }
    if (data.softwareServDetails && data.softwareServDetails !== 'NA') {
      setBusiness(prev => ({ ...prev, software_service_details: data.softwareServDetails }))
    }
  }

  const handleBusinessChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type, checked } = e.target
    
    // Handle checkbox/switch fields
    if (type === 'checkbox') {
      setBusiness(prev => ({ ...prev, [name]: checked }))
      if (errors[name]) {
        setErrors(prev => ({ ...prev, [name]: '' }))
      }
      return
    }
    
    // Handle months field specially
    if (name === 'accepted_credit_cards_months') {
      const numValue = parseInt(value) || 0
      setBusiness(prev => ({ ...prev, [name]: value }))
      
      // Run live validation
      const errorMsg = runLiveValidation(name, value)
      setErrors(prev => ({ ...prev, [name]: errorMsg }))
      
      if (numValue > 0 && business.accepted_credit_cards) {
        const maxMonths = Math.min(numValue, 6)
        setShowCreditHistory(true)
        
        const existingData = savedCreditHistory.length > 0 ? savedCreditHistory : creditCardHistory
        
        const newHistory: CreditHistory[] = []
        for (let i = 1; i <= maxMonths; i++) {
          const existingEntry = existingData && i <= existingData.length 
            ? existingData[i - 1] 
            : null
          
          newHistory.push({
            months_ago: String(i),
            number_of_transaction: existingEntry?.number_of_transaction || '',
            transaction_volume: existingEntry?.transaction_volume || '',
            number_of_chargeback: existingEntry?.number_of_chargeback || '',
            chargeback_volume: existingEntry?.chargeback_volume || '',
            number_of_refunds: existingEntry?.number_of_refunds || '',
            refund_volume: existingEntry?.refund_volume || '',
          })
        }
        
        setCreditCardHistory(newHistory)
        setNumberOfMonths(maxMonths)
        
        if (numValue > creditCardHistory.length) {
          setSavedCreditHistory(newHistory)
        }
      } else {
        setShowCreditHistory(false)
        setCreditCardHistory([])
        setNumberOfMonths(0)
      }
      return
    }

    // Handle other text fields
    if (name === 'length_of_time_business') {
      return
    }

    setBusiness(prev => ({ ...prev, [name]: value }))

    // Run live validation
    const errorMsg = runLiveValidation(name, value)
    setErrors(prev => ({ ...prev, [name]: errorMsg }))

    if (name === 'accepted_credit_cards' && !checked) {
      setShowCreditHistory(false)
      setCreditCardHistory([])
      setSavedCreditHistory([])
      setNumberOfMonths(0)
    }
  }

  const handleCreditHistoryChange = (index: number, field: string, value: string) => {
    const newHistory = [...creditCardHistory]
    newHistory[index] = { ...newHistory[index], [field]: value }
    setCreditCardHistory(newHistory)
    setSavedCreditHistory(newHistory)
  }

  const handleCardTypeToggle = (cardUid: string) => {
    setSelectedCardTypes(prev =>
      prev.includes(cardUid)
        ? prev.filter(id => id !== cardUid)
        : [...prev, cardUid]
    )
  }

  const handleEditPassword = () => {
    setIsEditingPassword(true)
    setBetaPassword('')
  }

  const handleCancelEditPassword = () => {
    setIsEditingPassword(false)
    setBetaPassword('')
  }

  const buildRequestBody = () => {
    const requestBody: any = {
      application_id: parseInt(applicationId),
      description_of_products: business.description_of_products || '',
      length_of_time_business: business.length_of_time_business || '',
      merchant_cat_code: business.merchant_cat_code || '',
      website: business.website || '',
      descriptor: business.descriptor || '',
      city_field: business.city_field || '',
      dynamic_descriptors: business.dynamic_descriptors,
      field_for_bankruptcy: business.field_for_bankruptcy,
      field_for_bankruptcy_date: business.field_for_bankruptcy_date || '',
      accepted_credit_cards: business.accepted_credit_cards,
      accepted_credit_cards_months: business.accepted_credit_cards_months || '',
      card_scheme_program: business.card_scheme_program,
      card_scheme_program_provide_details: business.card_scheme_program_provide_details || '',
      previous_payment_service_provider: business.previous_payment_service_provider || '',
      previous_acquirer: business.previous_acquirer || '',
      leaving_current_acquirer: business.leaving_current_acquirer || '',
      monthly_sales_volume: business.monthly_sales_volume || '',
      currency: business.currency || '$',
      avg_transaction_value: business.avg_transaction_value || '',
      highest_transaction_value: business.highest_transaction_value || '',
      one_time_payment: business.one_time_payment,
      recurring_payment: business.recurring_payment,
      domestic: business.domestic || '',
      europe: business.europe || '',
      usa: business.usa || '',
      asia: business.asia || '',
      rest_of_world: business.rest_of_world || '',
      e_commerce: business.e_commerce || '',
      card_present: business.card_present || '',
      m_pos: business.m_pos || '',
      moto: business.moto || '',
      immediately: business.immediately || '',
      within_four_weeks: business.within_four_weeks || '',
      within_5_14_weeks: business.within_5_14_weeks || '',
      more_than_14_weeks: business.more_than_14_weeks || '',
      is_upon_purchase: business.is_upon_purchase,
      is_with_download: business.is_with_download,
      is_on_delivery: business.is_on_delivery,
      is_other_payment_option: business.is_other_payment_option,
      other_payment_details: business.other_payment_details || '',
      is_offer_affiliate_prog: business.is_offer_affiliate_prog,
      offer_affiliate_prog_details: business.offer_affiliate_prog_details || '',
      is_need_soft_service: business.is_need_soft_service,
      software_service_details: business.software_service_details || '',
    }

    if (hasBetaSite) {
      requestBody.beta_website = betaWebsite || ''
      requestBody.username = betaUsername || ''
      
      if (isEditingPassword && betaPassword) {
        requestBody.password = betaPassword
      } else if (!hasExistingPassword && betaPassword) {
        requestBody.password = betaPassword
      } else if (!isEditingPassword && hasExistingPassword) {
        requestBody.password = 'True'
      }
    }

    if (business.accepted_credit_cards && parseInt(business.accepted_credit_cards_months) > 0 && creditCardHistory.length > 0) {
      const historyWithMonths = creditCardHistory.map(({ months_ago, number_of_transaction, transaction_volume, number_of_chargeback, chargeback_volume, number_of_refunds, refund_volume }) => ({
        months_ago: parseInt(months_ago),
        number_of_transaction: number_of_transaction || '0',
        transaction_volume: transaction_volume || '0',
        number_of_chargeback: number_of_chargeback || '0',
        chargeback_volume: chargeback_volume || '0',
        number_of_refunds: number_of_refunds || '0',
        refund_volume: refund_volume || '0',
      }))
      requestBody.credit_card_history = historyWithMonths
    }

    if (selectedCardTypes && selectedCardTypes.length > 0) {
      requestBody.card_type = selectedCardTypes
    }

    const otherCard = cardTypesList.find(card => card.cardName === 'Other' || card.cardType === 'Other')
    if (otherCard && selectedCardTypes.includes(otherCard.uid) && otherCardDetails) {
      requestBody.otherCardDetails = otherCardDetails
    }

    return requestBody
  }

  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.businessProfile}${applicationId}`,
          requestBody
        )
        toast.success('Business profile updated successfully!')
      } else {
        response = await axiosInstance.post(
          endpoints.merchantApplication.businessProfile,
          requestBody
        )
        toast.success('Business profile created successfully!')
        setIsEditMode(true)
      }

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

      let errorMessage = isEditMode
        ? 'Failed to update business profile. Please try again.'
        : 'Failed to create business profile. 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)
    }
  }

  const getMonthSuffix = (num: number) => {
    if (num === 1) return '1st'
    if (num === 2) return '2nd'
    if (num === 3) return '3rd'
    return `${num}th`
  }

  // ─── 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 || loadingDropdowns) {
    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 }}>
                Business Profile Details
              </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 filled fields, orange "Not Provided" indicates missing information.'
                  : 'Fill the form to create a new record.'}
              </Typography>
            </Alert>

            {/* Main Form */}
            <Paper elevation={0} sx={{ mb: 4, p: 3, bgcolor: 'background.paper', borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
              <SectionHeader color="primary.main" title="Business Information" />
              <Grid container spacing={3}>
                <Grid item xs={12}>
                  <SmartTextField
                    label="Detailed Description of Products/Services Sold"
                    name="description_of_products"
                    value={business.description_of_products}
                    onChange={handleBusinessChange}
                    error={errors.description_of_products}
                    helperText={errors.description_of_products}
                    placeholder="Please provide a detailed description of the products or services your business sells..."
                    multiline
                    rows={3}
                    isEditMode={isEditMode}
                  />
                </Grid>

                <Grid item xs={12} sm={6}>
                  <SmartTextField
                    label="Length of time in business"
                    name="length_of_time_business"
                    value={business.length_of_time_business}
                    onChange={handleBusinessChange}
                    error={errors.length_of_time_business}
                    helperText={errors.length_of_time_business || "Auto-calculated from incorporation date"}
                    placeholder="e.g., 5 years, 2 months, 10 days"
                    isEditMode={isEditMode}
                    disabled
                    InputProps={{
                      sx: { bgcolor: 'action.hover' }
                    }}
                  />
                </Grid>

                <Grid item xs={12} sm={6}>
                  <SmartTextField
                    label="Merchant Category (MCC)"
                    name="merchant_cat_code"
                    value={business.merchant_cat_code}
                    onChange={handleBusinessChange}
                    error={errors.merchant_cat_code}
                    helperText={errors.merchant_cat_code}
                    select
                    isEditMode={isEditMode}
                  >
                    <MenuItem value="" disabled>Select</MenuItem>
                    {merchantCategories.map((category) => (
                      <MenuItem key={category.id} value={category.code}>
                        {category.name} ({category.code})
                      </MenuItem>
                    ))}
                  </SmartTextField>
                </Grid>

                <Grid item xs={12}>
                  <Grid container spacing={3} alignItems="flex-start">
                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="Website(s) (Comma-Separated)"
                        name="website"
                        value={business.website}
                        onChange={handleBusinessChange}
                        error={errors.website}
                        helperText={errors.website}
                        placeholder="https://example.com, https://store.example.com"
                        isEditMode={isEditMode}
                      />
                    </Grid>

                    <Grid item xs={12} sm={6}>
                      <SmartSwitch
                        label="Beta Site(s)"
                        checked={hasBetaSite}
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) => setHasBetaSite(e.target.checked)}
                        name="hasBetaSite"
                        isEditMode={isEditMode}
                        helperText="Toggle on to add website details"
                      />
                    </Grid>

                    {hasBetaSite && (
                      <Grid item xs={12}>
                        <Box sx={{ bgcolor: 'action.hover', borderRadius: 2, p: 3, mt: 1 }}>
                          <Typography variant="h6" sx={{ fontWeight: 600, mb: 3 }}>
                            Beta Website Details
                          </Typography>
                          <Grid container spacing={2}>
                            <Grid item xs={12}>
                              <SmartTextField
                                label="Beta Website URL"
                                name="betaWebsite"
                                value={betaWebsite}
                                onChange={(e: React.ChangeEvent<HTMLInputElement>) => setBetaWebsite(e.target.value)}
                                placeholder="https://beta.example.com"
                                isEditMode={isEditMode}
                              />
                            </Grid>
                            <Grid item xs={12} sm={6}>
                              <SmartTextField
                                label="Username"
                                name="betaUsername"
                                value={betaUsername}
                                onChange={(e: React.ChangeEvent<HTMLInputElement>) => setBetaUsername(e.target.value)}
                                isEditMode={isEditMode}
                              />
                            </Grid>
                            <Grid item xs={12} sm={6}>
                              <Box>
                                <SmartTextField
                                  label="Password"
                                  name="betaPassword"
                                  value={betaPassword}
                                  onChange={(e: React.ChangeEvent<HTMLInputElement>) => setBetaPassword(e.target.value)}
                                  type="password"
                                  disabled={!isEditingPassword && hasExistingPassword}
                                  isEditMode={isEditMode}
                                  placeholder={!isEditingPassword && hasExistingPassword ? "••••••••" : "Enter password"}
                                  hideStatus={true}
                                  InputProps={{
                                    sx: {
                                      backgroundColor: !isEditingPassword && hasExistingPassword ? '#f5f5f5' : 'transparent',
                                    }
                                  }}
                                />
                                <Box sx={{ display: 'flex', gap: 1, mt: 1, alignItems: 'center', flexWrap: 'wrap' }}>
                                  {hasExistingPassword && !isEditingPassword ? (
                                    <>
                                      <Chip 
                                        label="✓ Password Already Set" 
                                        color="success" 
                                        size="small"
                                      />
                                      <Typography variant="caption" color="text.secondary">
                                        Click
                                      </Typography>
                                      <Button
                                        size="small"
                                        variant="outlined"
                                        color="primary"
                                        onClick={handleEditPassword}
                                        sx={{ minWidth: '80px', height: '30px' }}
                                      >
                                        Edit
                                      </Button>
                                      <Typography variant="caption" color="text.secondary">
                                        to change password
                                      </Typography>
                                    </>
                                  ) : hasExistingPassword && isEditingPassword ? (
                                    <>
                                      <Chip 
                                        label="Editing Password" 
                                        color="warning" 
                                        size="small"
                                      />
                                      <Button
                                        size="small"
                                        variant="outlined"
                                        color="error"
                                        onClick={handleCancelEditPassword}
                                        sx={{ minWidth: '80px', height: '30px' }}
                                      >
                                        Cancel
                                      </Button>
                                      <Typography variant="caption" color="warning.main">
                                        Enter new password or cancel to keep existing
                                      </Typography>
                                    </>
                                  ) : (
                                    <Typography variant="caption" color="text.secondary">
                                      Set a password for the beta site
                                    </Typography>
                                  )}
                                </Box>
                              </Box>
                            </Grid>
                          </Grid>
                        </Box>
                      </Grid>
                    )}
                  </Grid>
                </Grid>

                <Grid item xs={12} sm={6}>
                  <SmartTextField
                    label="Credit Card Descriptor (Max 22 Char.)"
                    name="descriptor"
                    value={business.descriptor}
                    onChange={handleBusinessChange}
                    error={errors.descriptor}
                    helperText={errors.descriptor}
                    inputProps={{ maxLength: 22 }}
                    isEditMode={isEditMode}
                  />
                </Grid>

                <Grid item xs={12} sm={6}>
                  <SmartTextField
                    label="DBA/City (Max 12 Char.)"
                    name="city_field"
                    value={business.city_field}
                    onChange={handleBusinessChange}
                    error={errors.city_field}
                    helperText={errors.city_field}
                    inputProps={{ maxLength: 12 }}
                    isEditMode={isEditMode}
                  />
                </Grid>

                <Grid item xs={12}>
                  <SmartCheckbox
                    label="Will You use 'Dynamic Descriptor'"
                    checked={business.dynamic_descriptors}
                    onChange={handleBusinessChange}
                    name="dynamic_descriptors"
                    isEditMode={isEditMode}
                  />
                </Grid>

                <Grid item xs={12}>
                  <SmartCheckbox
                    label="Have you filed for bankruptcy before?"
                    checked={business.field_for_bankruptcy}
                    onChange={handleBusinessChange}
                    name="field_for_bankruptcy"
                    isEditMode={isEditMode}
                  />
                  {business.field_for_bankruptcy && (
                    <Box sx={{ mt: 2, ml: 4 }}>
                      <SmartTextField
                        label="Date of Bankruptcy"
                        name="field_for_bankruptcy_date"
                        value={business.field_for_bankruptcy_date}
                        onChange={handleBusinessChange}
                        type="date"
                        InputLabelProps={{ shrink: true }}
                        isEditMode={isEditMode}
                      />
                    </Box>
                  )}
                </Grid>

                <Grid item xs={12}>
                  <SmartCheckbox
                    label="Have you previously accepted Credit Card payments?"
                    checked={business.accepted_credit_cards}
                    onChange={handleBusinessChange}
                    name="accepted_credit_cards"
                    isEditMode={isEditMode}
                  />
                  {business.accepted_credit_cards && (
                    <Box sx={{ mt: 2, ml: 4 }}>
                      <Grid container spacing={2}>
                        <Grid item xs={12} sm={6}>
                          <SmartTextField
                            label="How Many Months (Max 6)"
                            name="accepted_credit_cards_months"
                            value={business.accepted_credit_cards_months}
                            onChange={handleBusinessChange}
                            error={errors.accepted_credit_cards_months}
                            helperText={errors.accepted_credit_cards_months || "Enter 1-6 months to show credit history"}
                            type="number"
                            inputProps={{ min: 0, max: 6 }}
                            placeholder="Enter number of months (max 6)"
                            isEditMode={isEditMode}
                          />
                        </Grid>
                        <Grid item xs={12} sm={6}>
                          <SmartTextField
                            label="Previous Payment Service Provider"
                            name="previous_payment_service_provider"
                            value={business.previous_payment_service_provider}
                            onChange={handleBusinessChange}
                            placeholder="Enter provider name"
                            isEditMode={isEditMode}
                          />
                        </Grid>
                        <Grid item xs={12} sm={6}>
                          <SmartTextField
                            label="Previous Acquirer"
                            name="previous_acquirer"
                            value={business.previous_acquirer}
                            onChange={handleBusinessChange}
                            placeholder="Enter acquirer name"
                            isEditMode={isEditMode}
                          />
                        </Grid>
                        <Grid item xs={12} sm={6}>
                          <SmartTextField
                            label="Reason for leaving current acquirer"
                            name="leaving_current_acquirer"
                            value={business.leaving_current_acquirer}
                            onChange={handleBusinessChange}
                            placeholder="Enter reason"
                            isEditMode={isEditMode}
                          />
                        </Grid>
                      </Grid>

                      {showCreditHistory && creditCardHistory.length > 0 && (
                        <Box sx={{ mt: 4 }}>
                          <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, color: 'primary.main' }}>
                            PLEASE PROVIDE {creditCardHistory.length} MONTH{creditCardHistory.length > 1 ? 'S' : ''} OF MOST RECENT PROCESSING HISTORY BELOW
                          </Typography>
                          <Box sx={{ overflowX: 'auto' }}>
                            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                              <thead>
                                <tr style={{ backgroundColor: '#f5f5f5' }}>
                                  <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '80px' }}>
                                    MONTH
                                  </th>
                                  <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
                                    Number of transactions
                                  </th>
                                  <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
                                    Transaction volume
                                  </th>
                                  <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
                                    Number of chargebacks
                                  </th>
                                  <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
                                    Chargeback volume
                                  </th>
                                  <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
                                    Number of refunds
                                  </th>
                                  <th style={{ padding: '12px', border: '1px solid #ddd', textAlign: 'left', fontWeight: 600, minWidth: '150px' }}>
                                    Refund volume
                                  </th>
                                </tr>
                              </thead>
                              <tbody>
                                {creditCardHistory.map((history, index) => (
                                  <tr key={index}>
                                    <td style={{ padding: '12px', border: '1px solid #ddd', fontWeight: 500, textAlign: 'center' }}>
                                      {getMonthSuffix(index + 1)}
                                    </td>
                                    <td style={{ padding: '8px', border: '1px solid #ddd' }}>
                                      <TextField
                                        fullWidth
                                        type="number"
                                        size="small"
                                        value={history.number_of_transaction}
                                        onChange={(e) => handleCreditHistoryChange(index, 'number_of_transaction', e.target.value)}
                                        placeholder="0"
                                      />
                                    </td>
                                    <td style={{ padding: '8px', border: '1px solid #ddd' }}>
                                      <TextField
                                        fullWidth
                                        type="number"
                                        size="small"
                                        value={history.transaction_volume}
                                        onChange={(e) => handleCreditHistoryChange(index, 'transaction_volume', e.target.value)}
                                        placeholder="0"
                                      />
                                    </td>
                                    <td style={{ padding: '8px', border: '1px solid #ddd' }}>
                                      <TextField
                                        fullWidth
                                        type="number"
                                        size="small"
                                        value={history.number_of_chargeback}
                                        onChange={(e) => handleCreditHistoryChange(index, 'number_of_chargeback', e.target.value)}
                                        placeholder="0"
                                      />
                                    </td>
                                    <td style={{ padding: '8px', border: '1px solid #ddd' }}>
                                      <TextField
                                        fullWidth
                                        type="number"
                                        size="small"
                                        value={history.chargeback_volume}
                                        onChange={(e) => handleCreditHistoryChange(index, 'chargeback_volume', e.target.value)}
                                        placeholder="0"
                                      />
                                    </td>
                                    <td style={{ padding: '8px', border: '1px solid #ddd' }}>
                                      <TextField
                                        fullWidth
                                        type="number"
                                        size="small"
                                        value={history.number_of_refunds}
                                        onChange={(e) => handleCreditHistoryChange(index, 'number_of_refunds', e.target.value)}
                                        placeholder="0"
                                      />
                                    </td>
                                    <td style={{ padding: '8px', border: '1px solid #ddd' }}>
                                      <TextField
                                        fullWidth
                                        type="number"
                                        size="small"
                                        value={history.refund_volume}
                                        onChange={(e) => handleCreditHistoryChange(index, 'refund_volume', e.target.value)}
                                        placeholder="0"
                                      />
                                    </td>
                                  </tr>
                                ))}
                              </tbody>
                            </table>
                          </Box>
                        </Box>
                      )}
                    </Box>
                  )}
                </Grid>

                <Grid item xs={12}>
                  <SmartCheckbox
                    label="Have you ever flagged or been in violation of any card schema program?"
                    checked={business.card_scheme_program}
                    onChange={handleBusinessChange}
                    name="card_scheme_program"
                    isEditMode={isEditMode}
                  />
                  {business.card_scheme_program && (
                    <Box sx={{ mt: 2, ml: 4 }}>
                      <SmartTextField
                        label="Please Provide Details"
                        name="card_scheme_program_provide_details"
                        value={business.card_scheme_program_provide_details}
                        onChange={handleBusinessChange}
                        placeholder="Please provide details about the violation..."
                        multiline
                        rows={3}
                        isEditMode={isEditMode}
                      />
                    </Box>
                  )}
                </Grid>

                <Grid item xs={12} sm={4}>
                  <SmartTextField
                    label="Estimated monthly sales volume"
                    name="monthly_sales_volume"
                    value={business.monthly_sales_volume}
                    onChange={handleBusinessChange}
                    error={errors.monthly_sales_volume}
                    helperText={errors.monthly_sales_volume}
                    type="number"
                    placeholder="Enter amount"
                    isEditMode={isEditMode}
                    InputProps={{ startAdornment: <span>$ </span> }}
                  />
                </Grid>

                <Grid item xs={12} sm={4}>
                  <SmartTextField
                    label="Highest transaction value"
                    name="highest_transaction_value"
                    value={business.highest_transaction_value}
                    onChange={handleBusinessChange}
                    error={errors.highest_transaction_value}
                    helperText={errors.highest_transaction_value}
                    type="number"
                    placeholder="Enter amount"
                    isEditMode={isEditMode}
                    InputProps={{ startAdornment: <span>$ </span> }}
                  />
                </Grid>

                <Grid item xs={12} sm={4}>
                  <SmartTextField
                    label="Average transaction value"
                    name="avg_transaction_value"
                    value={business.avg_transaction_value}
                    onChange={handleBusinessChange}
                    error={errors.avg_transaction_value}
                    helperText={errors.avg_transaction_value}
                    type="number"
                    placeholder="Enter amount"
                    isEditMode={isEditMode}
                    InputProps={{ startAdornment: <span>$ </span> }}
                  />
                </Grid>

                <Grid item xs={12} sm={6}>
                  <FormControl component="fieldset">
                    <FormLabel component="legend">Payment frequency</FormLabel>
                    <Stack direction="row" spacing={2}>
                      <SmartCheckbox
                        label="One-time payment"
                        checked={business.one_time_payment}
                        onChange={handleBusinessChange}
                        name="one_time_payment"
                        isEditMode={isEditMode}
                      />
                      <SmartCheckbox
                        label="Recurring payment"
                        checked={business.recurring_payment}
                        onChange={handleBusinessChange}
                        name="recurring_payment"
                        isEditMode={isEditMode}
                      />
                    </Stack>
                  </FormControl>
                </Grid>

                <Grid item xs={12}>
                  <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
                    ORIGIN OF TRANSACTIONS (%)
                  </Typography>
                  <Grid container spacing={2}>
                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="Domestic"
                        type="number"
                        name="domestic"
                        value={business.domestic}
                        onChange={handleBusinessChange}
                        error={errors.domestic}
                        helperText={errors.domestic}
                        isEditMode={isEditMode}
                        InputProps={{ endAdornment: '%' }}
                      />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="Europe"
                        type="number"
                        name="europe"
                        value={business.europe}
                        onChange={handleBusinessChange}
                        error={errors.europe}
                        helperText={errors.europe}
                        isEditMode={isEditMode}
                        InputProps={{ endAdornment: '%' }}
                      />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="USA (Oceania)"
                        type="number"
                        name="usa"
                        value={business.usa}
                        onChange={handleBusinessChange}
                        error={errors.usa}
                        helperText={errors.usa}
                        isEditMode={isEditMode}
                        InputProps={{ endAdornment: '%' }}
                      />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="Asia"
                        type="number"
                        name="asia"
                        value={business.asia}
                        onChange={handleBusinessChange}
                        error={errors.asia}
                        helperText={errors.asia}
                        isEditMode={isEditMode}
                        InputProps={{ endAdornment: '%' }}
                      />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="Rest of world"
                        type="number"
                        name="rest_of_world"
                        value={business.rest_of_world}
                        onChange={handleBusinessChange}
                        error={errors.rest_of_world}
                        helperText={errors.rest_of_world}
                        isEditMode={isEditMode}
                        InputProps={{ endAdornment: '%' }}
                      />
                    </Grid>
                  </Grid>
                </Grid>

                <Grid item xs={12}>
                  <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
                    METHOD OF ACCEPTANCE (%)
                  </Typography>
                  <Grid container spacing={2}>
                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="E-commerce / M-Commerce"
                        type="number"
                        name="e_commerce"
                        value={business.e_commerce}
                        onChange={handleBusinessChange}
                        error={errors.e_commerce}
                        helperText={errors.e_commerce}
                        isEditMode={isEditMode}
                        InputProps={{ endAdornment: '%' }}
                      />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="Card Present (POS)"
                        type="number"
                        name="card_present"
                        value={business.card_present}
                        onChange={handleBusinessChange}
                        error={errors.card_present}
                        helperText={errors.card_present}
                        isEditMode={isEditMode}
                        InputProps={{ endAdornment: '%' }}
                      />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="M-Pos (Mobile POS)"
                        type="number"
                        name="m_pos"
                        value={business.m_pos}
                        onChange={handleBusinessChange}
                        error={errors.m_pos}
                        helperText={errors.m_pos}
                        isEditMode={isEditMode}
                        InputProps={{ endAdornment: '%' }}
                      />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="MOTO"
                        type="number"
                        name="moto"
                        value={business.moto}
                        onChange={handleBusinessChange}
                        error={errors.moto}
                        helperText={errors.moto}
                        isEditMode={isEditMode}
                        InputProps={{ endAdornment: '%' }}
                      />
                    </Grid>
                  </Grid>
                </Grid>

                <Grid item xs={12}>
                  <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
                    DELIVERY TIME FOR GOODS/SERVICES (%)
                  </Typography>
                  <Grid container spacing={2}>
                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="Immediately"
                        type="number"
                        name="immediately"
                        value={business.immediately}
                        onChange={handleBusinessChange}
                        error={errors.immediately}
                        helperText={errors.immediately}
                        isEditMode={isEditMode}
                        InputProps={{ endAdornment: '%' }}
                      />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="Within 4 weeks"
                        type="number"
                        name="within_four_weeks"
                        value={business.within_four_weeks}
                        onChange={handleBusinessChange}
                        error={errors.within_four_weeks}
                        helperText={errors.within_four_weeks}
                        isEditMode={isEditMode}
                        InputProps={{ endAdornment: '%' }}
                      />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="Within 5-14 weeks"
                        type="number"
                        name="within_5_14_weeks"
                        value={business.within_5_14_weeks}
                        onChange={handleBusinessChange}
                        error={errors.within_5_14_weeks}
                        helperText={errors.within_5_14_weeks}
                        isEditMode={isEditMode}
                        InputProps={{ endAdornment: '%' }}
                      />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                      <SmartTextField
                        label="More than 14 weeks"
                        type="number"
                        name="more_than_14_weeks"
                        value={business.more_than_14_weeks}
                        onChange={handleBusinessChange}
                        error={errors.more_than_14_weeks}
                        helperText={errors.more_than_14_weeks}
                        isEditMode={isEditMode}
                        InputProps={{ endAdornment: '%' }}
                      />
                    </Grid>
                  </Grid>
                </Grid>

                <Grid item xs={12}>
                  <FormControl component="fieldset">
                    <FormLabel component="legend">When does payment take place?</FormLabel>
                    <Stack direction="row" spacing={2} flexWrap="wrap">
                      <SmartCheckbox
                        label="Upon purchase"
                        checked={business.is_upon_purchase}
                        onChange={handleBusinessChange}
                        name="is_upon_purchase"
                        isEditMode={isEditMode}
                      />
                      <SmartCheckbox
                        label="With download"
                        checked={business.is_with_download}
                        onChange={handleBusinessChange}
                        name="is_with_download"
                        isEditMode={isEditMode}
                      />
                      <SmartCheckbox
                        label="On delivery"
                        checked={business.is_on_delivery}
                        onChange={handleBusinessChange}
                        name="is_on_delivery"
                        isEditMode={isEditMode}
                      />
                      <SmartCheckbox
                        label="Other"
                        checked={business.is_other_payment_option}
                        onChange={handleBusinessChange}
                        name="is_other_payment_option"
                        isEditMode={isEditMode}
                      />
                    </Stack>
                  </FormControl>
                  {business.is_other_payment_option && (
                    <Box sx={{ mt: 2 }}>
                      <SmartTextField
                        label="Please Provide Details"
                        name="other_payment_details"
                        value={business.other_payment_details}
                        onChange={handleBusinessChange}
                        placeholder="Please provide details about when payment takes place..."
                        multiline
                        rows={3}
                        isEditMode={isEditMode}
                      />
                    </Box>
                  )}
                </Grid>

                <Grid item xs={12}>
                  <Typography variant="subtitle1" sx={{ fontWeight: 500, mb: 2 }}>
                    Card types applying for
                  </Typography>
                  <Grid container spacing={2}>
                    {cardTypesList.map((card) => (
                      <Grid item xs={6} sm={4} md={3} key={card.uid}>
                        <FormControlLabel
                          control={
                            <Checkbox
                              checked={selectedCardTypes.includes(card.uid)}
                              onChange={() => handleCardTypeToggle(card.uid)}
                              sx={{
                                '&.Mui-checked': {
                                  color: isEditMode ? '#2e7d32' : undefined,
                                },
                              }}
                            />
                          }
                          label={card.cardName || card.cardType}
                        />
                      </Grid>
                    ))}
                  </Grid>
                  {selectedCardTypes.some(uid => {
                    const card = cardTypesList.find(c => c.uid === uid)
                    return card && (card.cardName === 'Other' || card.cardType === 'Other')
                  }) && (
                    <Box sx={{ mt: 2 }}>
                      <SmartTextField
                        label="Other Card Details"
                        name="otherCardDetails"
                        value={otherCardDetails}
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) => setOtherCardDetails(e.target.value)}
                        placeholder="Please specify other card types..."
                        multiline
                        rows={2}
                        isEditMode={isEditMode}
                      />
                    </Box>
                  )}
                </Grid>

                <Grid item xs={12}>
                  <SmartSwitch
                    label="Do you offer / make use of affiliate programs?"
                    checked={business.is_offer_affiliate_prog}
                    onChange={handleBusinessChange}
                    name="is_offer_affiliate_prog"
                    isEditMode={isEditMode}
                  />
                  {business.is_offer_affiliate_prog && (
                    <Box sx={{ mt: 2, ml: 4 }}>
                      <SmartTextField
                        label="Please provide details"
                        name="offer_affiliate_prog_details"
                        value={business.offer_affiliate_prog_details}
                        onChange={handleBusinessChange}
                        placeholder="Please provide details about your affiliate programs..."
                        multiline
                        rows={3}
                        isEditMode={isEditMode}
                      />
                    </Box>
                  )}
                </Grid>

                <Grid item xs={12}>
                  <SmartSwitch
                    label="Need Software As A Service"
                    checked={business.is_need_soft_service}
                    onChange={handleBusinessChange}
                    name="is_need_soft_service"
                    isEditMode={isEditMode}
                  />
                  {business.is_need_soft_service && (
                    <Box sx={{ mt: 2, ml: 4 }}>
                      <SmartTextField
                        label="Please provide details"
                        name="software_service_details"
                        value={business.software_service_details}
                        onChange={handleBusinessChange}
                        placeholder="Please provide details about your software requirements..."
                        multiline
                        rows={3}
                        isEditMode={isEditMode}
                      />
                    </Box>
                  )}
                </Grid>
              </Grid>
            </Paper>

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

            {/* Navigation */}
            <Stack direction="row" spacing={2} justifyContent="flex-end">
              <Button
                type="button"
                variant="outlined"
                size="large"
                onClick={onPrevious}
                sx={{ textTransform: 'none', px: 4 }}
                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 BusinessProfile