import * as React from 'react';
import PropTypes from 'prop-types';
import Tabs from '@mui/material/Tabs';
import Tab from '@mui/material/Tab';
import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';
import Switch from '@mui/material/Switch';
import useMediaQuery from '@mui/material/useMediaQuery';
import { useTheme } from '@mui/material/styles';
import { Phone, MessageSquare, Shield, Bell, UserCheck, ChevronLeft } from 'lucide-react';

function TabPanel(props) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`tabpanel-${index}`}
      aria-labelledby={`tab-${index}`}
      {...other}
      style={{ width: '100%' }}
    >
      {value === index && (
        <Box sx={{ p: 0 }}>
          {children}
        </Box>
      )}
    </div>
  );
}

TabPanel.propTypes = {
  children: PropTypes.node,
  index: PropTypes.number.isRequired,
  value: PropTypes.number.isRequired,
};

function a11yProps(index, isMobile) {
  return {
    id: `${isMobile ? 'horizontal' : 'vertical'}-tab-${index}`,
    'aria-controls': `${isMobile ? 'horizontal' : 'vertical'}-tabpanel-${index}`,
  };
}

const SettingItem = ({ title, description, enabled, onToggle }) => (
  <Box sx={{ py: 2, borderBottom: '1px solid #e5e7eb', '&:last-child': { borderBottom: 'none' } }}>
    <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 1 }}>
      <Typography variant="body1" sx={{ fontWeight: 'bold', color: '#111827', fontSize: { xs: '0.875rem', sm: '1rem' } }}>
        {title}
      </Typography>
      <Switch
        checked={enabled}
        onChange={onToggle}
        sx={{
          '& .MuiSwitch-switchBase.Mui-checked': {
            color: '#fff',
          },
          '& .MuiSwitch-switchBase.Mui-checked + .MuiSwitch-track': {
            backgroundColor: '#16a34a',
          },
        }}
      />
    </Box>
    <Typography variant="body2" sx={{ color: '#6b7280', lineHeight: 1.6, fontSize: { xs: '0.75rem', sm: '0.875rem' } }}>
      {description}
    </Typography>
  </Box>
);

const TabContent = ({ title, settings, states, onToggle }) => (
  <Box sx={{borderRadius:"10px", flex: 1, bgcolor: '#ebf7ff', height: { xs: 'auto', md: '100vh' }, overflow: 'auto', width:"100%", maxWidth:"1000px", margin:"0 auto" }}>
    <Box sx={{ 
      position: 'sticky', 
      top: 0, 
      bgcolor: '#034E08', 
      borderBottom: '1px solid #e5e7eb', 
      px: { xs: 2, sm: 3 }, 
      py: 2,
      display: 'flex',
      alignItems: 'center',
      gap: 2,
      zIndex: 10,
      borderRadius:"10px",
    }}>
      <Typography variant="h6" sx={{ fontWeight: 'bold', color: '#fefefeff', fontSize: { xs: '1rem', sm: '1.25rem' } }}>
        {title}
      </Typography>
    </Box>
    <Box sx={{ px: { xs: 2, sm: 3 }, py: 2 }}>
      {settings.map((setting, index) => (
        <SettingItem
          key={index}
          title={setting.title}
          description={setting.description}
          enabled={states[setting.key]}
          onToggle={() => onToggle(setting.key)}
        />
      ))}
    </Box>
  </Box>
);

export default function AccountSettingPage() {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('md'));
  const [value, setValue] = React.useState(0);
  const [settings, setSettings] = React.useState({
    phoneVisibility: true,
    chatAlertsNotification: true,
    chatProtection: true,
    protectProfilePhoto: true,
    callProtection: true,
    matchAlerts: true,
    profileViews: false,
    messagePermission: true,
    blockUnverified: false,
  });

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  const toggleSetting = (key) => {
    setSettings(prev => ({ ...prev, [key]: !prev[key] }));
  };

  const tabs = [
    {
      id: 0,
      label: 'Phone Number',
      fullLabel: 'Phone Number Visibility Controls',
      icon: <Phone size={20} />,
      settings: [
        {
          key: 'phoneVisibility',
          title: 'Phone Number Visibility',
          description: 'You can control phone number visibility through temporary and permanent methods on your phone. For a single call, dial *67 before the number.',
        },
      ],
    },
    {
      id: 1,
      label: 'Chat Alerts',
      fullLabel: 'Chat Alerts',
      icon: <MessageSquare size={20} />,
      settings: [
        {
          key: 'chatAlertsNotification',
          title: 'Chat Alerts Notification',
          description: 'Matrimony sites send chat alerts with standard, automated content to notify you of new interactions related to your profile.',
        },
        {
          key: 'chatProtection',
          title: 'Chat Protection',
          description: 'To protect yourself while using matrimonial sites, the primary "chat protection content" is restricting the personal and sensitive information you share both on your public profile and in early conversations.',
        },
      ],
    },
    {
      id: 2,
      label: 'Profile',
      fullLabel: 'Profile Protection',
      icon: <Shield size={20} />,
      settings: [
        {
          key: 'protectProfilePhoto',
          title: 'Protect Profile photo to all',
          description: 'The photograph privacy settings options are available in the \'My Photos\' section of the \'My Profile\' page.',
        },
        {
          key: 'callProtection',
          title: 'Call Protection',
          description: 'To implement call protection, most major matrimony sites offer built-in privacy features that allow you to control who sees your contact details and photos.',
        },
      ],
    },
    {
      id: 3,
      label: 'Match Alerts',
      fullLabel: 'Match Alerts Preferences',
      icon: <Bell size={20} />,
      settings: [
        {
          key: 'matchAlerts',
          title: 'Match Alert Notifications',
          description: 'Receive notifications when new profiles match your preferences and requirements.',
        },
        {
          key: 'profileViews',
          title: 'Profile View Alerts',
          description: 'Get notified when someone views your profile or shows interest in connecting with you.',
        },
      ],
    },
    {
      id: 4,
      label: 'Messages',
      fullLabel: 'Who Can Message Me?',
      icon: <UserCheck size={20} />,
      settings: [
        {
          key: 'messagePermission',
          title: 'Message Permissions',
          description: 'Control who can send you messages. You can restrict messages to only verified profiles or profiles that match your preferences.',
        },
        {
          key: 'blockUnverified',
          title: 'Block Unverified Profiles',
          description: 'Automatically block messages from profiles that haven\'t completed verification process.',
        },
      ],
    },
  ];

  return (
    <Box sx={{ flexGrow: 1, 
     display: 'flex', flexDirection: { xs: 'column', md: 'row' }, gap:"20px",
      minHeight: '90vh', marginTop:"50px", marginBottom:"50px" }}>
      {/* Desktop: Vertical Sidebar */}
      {!isMobile && (
        <Box sx={{ width: 300, borderRadius:"10px" ,background:"#ffeac9", borderRight: '1px solid #e5e7eb', display: { xs: 'none', md: 'block' } }}>
          <Box sx={{ 
            position: 'sticky', 
            top: 0, 
            bgcolor: '#ffeac9', 
            borderBottom: '1px solid #e5e7eb', 
            px: 3, 
            py: 2,
            zIndex: 10,
             borderRadius:"10px" ,
          }}>
            <Typography variant="h5" sx={{ fontWeight: 'bold', color: '#111827' }}>
              Settings
            </Typography>
          </Box>
          <Tabs
            orientation="vertical"
            variant="scrollable"
            value={value}
            onChange={handleChange}
            aria-label="Settings tabs"
            sx={{
              '& .MuiTabs-indicator': {
                left: 0,
                width: 4,
                backgroundColor: '#A70710',
              },
              '& .MuiTab-root': {
                // alignItems: 'flex-start',
                // textAlign: 'left',
                justifyContent:"left",
                minHeight: 64,
                px: 3,
                py: 2,
                textTransform: 'none',
                fontSize: '0.875rem',
                fontWeight: 500,
                color: '#374151',
                '&.Mui-selected': {
                  color: '#A70710',
                  backgroundColor: '#fff7ed',
                },
                '&:hover': {
                  backgroundColor: '#f9fafb',
                },
              },
            }}
          >
            {tabs.map((tab, index) => (
              <Tab
                key={tab.id}
                icon={tab.icon}
                iconPosition="start"
                label={tab.fullLabel}
                {...a11yProps(index, false)}
              />
            ))}
          </Tabs>
        </Box>
      )}

      {/* Mobile: Horizontal Tabs */}
      {isMobile && (
        <Box sx={{ bgcolor: 'white', borderBottom: '1px solid #e5e7eb', display: { xs: 'block', md: 'none' } }}>
          <Box sx={{ px: 2, py: 2 }}>
            <Typography variant="h6" sx={{ fontWeight: 'bold', color: '#111827' }}>
              Settings
            </Typography>
          </Box>
          <Tabs
            value={value}
            onChange={handleChange}
            variant="scrollable"
            scrollButtons="auto"
            aria-label="Settings tabs"
            sx={{
              '& .MuiTabs-indicator': {
                backgroundColor: '#A70710',
                height: 3,
              },
              '& .MuiTab-root': {
                textTransform: 'none',
                fontSize: '0.75rem',
                fontWeight: 500,
                minWidth: 'auto',
                px: 2,
                py: 1.5,
                color: '#ffffffff',
                '&.Mui-selected': {
                  color: '#A70710',
                },
              },
              '& .MuiTabs-flexContainer': {
                gap: 1,
              },
            }}
          >
            {tabs.map((tab, index) => (
              <Tab
                key={tab.id}
                icon={tab.icon}
                iconPosition="start"
                label={tab.label}
                {...a11yProps(index, true)}
              />
            ))}
          </Tabs>
        </Box>
      )}

      {/* Tab Content */}
      <Box sx={{ flex: 1, width: '100%' }}>
        {tabs.map((tab, index) => (
          <TabPanel key={tab.id} value={value} index={index}>
            <TabContent
              title={tab.fullLabel}
              settings={tab.settings}
              states={settings}
              onToggle={toggleSetting}
            />
          </TabPanel>
        ))}
      </Box>
    </Box>
  );
}