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, Select, MenuItem } from '@mui/material';
import useMediaQuery from '@mui/material/useMediaQuery';
import { useTheme } from '@mui/material/styles';
import { Phone, MessageSquare, Shield, Bell, UserCheck, ChevronLeft } from 'lucide-react';
import { useQuery, useMutation } from '@tanstack/react-query';
import axiosInstance from '../api/axiosInstance';
import { API_ENDPOINTS } from '../api/apiEndpoints';
import toast from 'react-hot-toast';

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 SelectSettingItem = ({ title, description, value, onChange, options, disabled }) => (
  <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>
      <Select
        value={value}
        onChange={onChange}
        disabled={disabled}
        sx={{ minWidth: 150, fontSize: { xs: '0.875rem', sm: '1rem' } }}
        variant="standard"
      >
        {options.map(option => (
          <MenuItem key={option} value={option}>{option}</MenuItem>
        ))}
      </Select>
    </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, onSelectChange }) => (
  <Box sx={{borderRadius:"10px", flex: 1, bgcolor: '#ffff', 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) => {
        if (setting.type === 'select') {
          return (
            <SelectSettingItem
              key={index}
              title={setting.title}
              description={setting.description}
              value={states[setting.key]}
              onChange={(e) => onSelectChange(setting.key, e.target.value)}
              options={setting.options}
              disabled={!states.messagePermission}
            />
          );
        }
        return (<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: false,
    messageCategory: 'All Profile',
  });

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

  const { data: phoneVisibilityData } = useQuery({
    queryKey: ["phoneVisibility"],
    queryFn: async () => {
      const res = await axiosInstance.get(API_ENDPOINTS.PHONE_NUMBER_VISIBILITY);
      return res.data;
    },
  });

  React.useEffect(() => {
    if (phoneVisibilityData) {
      setSettings((prev) => ({
        ...prev,
        phoneVisibility: phoneVisibilityData.phone_number_visibility === 1,
      }));
    }
  }, [phoneVisibilityData]);

  const phoneVisibilityMutation = useMutation({
    mutationFn: async (isVisible) => {
      return await axiosInstance.post(API_ENDPOINTS.UPDATE_PHONE_NUMBER_VISIBILITY, null, {
        params: { phone_number_visibility: isVisible ? 1 : 0 },
      });
    },
    onSuccess: (res) => {
      toast.success(res.data.message);
    },
    onError: () => {
      toast.error("Failed to update phone visibility");
      setSettings((prev) => ({ ...prev, phoneVisibility: !prev.phoneVisibility }));
    },
  });

  const { data: chatAlertData } = useQuery({
    queryKey: ["chatAlerts"],
    queryFn: async () => {
      const res = await axiosInstance.get(API_ENDPOINTS.CHAT_ALERT_NOTIFICATION);
      return res.data;
    },
  });

  React.useEffect(() => {
    if (chatAlertData) {
      setSettings((prev) => ({
        ...prev,
        chatAlertsNotification: chatAlertData.chat_alert_notification === 1,
        chatProtection: chatAlertData.chat_protection === 1,
      }));
    }
  }, [chatAlertData]);

  const chatAlertMutation = useMutation({
    mutationFn: async (payload) => {
      return await axiosInstance.post(API_ENDPOINTS.UPDATE_CHAT_ALERT_NOTIFICATION, null, {
        params: {
          chat_alert_notification: payload.chatAlertsNotification ? 1 : 0,
          chat_protection: payload.chatProtection ? 1 : 0,
        },
      });
    },
    onSuccess: (res) => {
      toast.success(res.data.message);
    },
    onError: () => {
      toast.error("Failed to update chat settings");
    },
  });

  const { data: profileProtectionData } = useQuery({
    queryKey: ["profileProtection"],
    queryFn: async () => {
      const res = await axiosInstance.get(API_ENDPOINTS.PROFILE_PROTECT_API);
      return res.data;
    },
  });

  React.useEffect(() => {
    if (profileProtectionData) {
      setSettings((prev) => ({
        ...prev,
        protectProfilePhoto: profileProtectionData.profile_photo_protect === 1,
        callProtection: profileProtectionData.call_protection === 1,
      }));
    }
  }, [profileProtectionData]);

  const profileProtectionMutation = useMutation({
    mutationFn: async (payload) => {
      return await axiosInstance.post(
        API_ENDPOINTS.UPDATE_PROFILE_PROTECT_API,
        null,
        {
          params: {
            profile_photo_protect: payload.protectProfilePhoto ? 1 : 0,
            call_protection: payload.callProtection ? 1 : 0,
          },
        }
      );
    },
    onSuccess: (res) => {
      toast.success(res.data.message);
    },
    onError: () => {
      toast.error("Failed to update profile protection settings");
    },
  });

  const { data: matchAlertData } = useQuery({
    queryKey: ["matchAlerts"],
    queryFn: async () => {
      const res = await axiosInstance.get(API_ENDPOINTS.MATCH_ALERT);
      return res.data;
    },
  });

  React.useEffect(() => {
    if (matchAlertData) {
      setSettings((prev) => ({
        ...prev,
        matchAlerts: matchAlertData.match_alert_preference === 1,
      }));
    }
  }, [matchAlertData]);

  const matchAlertMutation = useMutation({
    mutationFn: async (isEnabled) => {
      return await axiosInstance.post(API_ENDPOINTS.UPDATE_MATCH_ALERT, null, {
        params: { match_alert_preference: isEnabled ? 1 : 0 },
      });
    },
    onSuccess: (res) => {
      toast.success(res.data.message);
    },
    onError: () => {
      toast.error("Failed to update match alert settings");
      setSettings((prev) => ({ ...prev, matchAlerts: !prev.matchAlerts }));
    },
  });

  const { data: whoCanMessageData } = useQuery({
    queryKey: ["whoCanMessage"],
    queryFn: async () => {
      const res = await axiosInstance.get(API_ENDPOINTS.WHO_CAN_VIEW_MESSAGE);
      return res.data;
    },
  });

  React.useEffect(() => {
    if (whoCanMessageData) {
      setSettings((prev) => ({
        ...prev,
        messagePermission: whoCanMessageData.who_can_message === 1,
        messageCategory: whoCanMessageData.who_can_message_categories || 'All Profile',
      }));
    }
  }, [whoCanMessageData]);

  const whoCanMessageMutation = useMutation({
    mutationFn: async (payload) => {
      return await axiosInstance.post(API_ENDPOINTS.UPDATE_WHO_CAN_VIEW_MESSAGE, null, {
        params: {
          who_can_message: payload.messagePermission ? 1 : 0,
          who_can_message_categories: payload.messageCategory,
        },
      });
    },
    onSuccess: (res) => {
      toast.success(res.data.message);
    },
    onError: (err, variables) => {
      toast.error("Failed to update message settings");
      // Revert optimistic update
      setSettings(variables.oldSettings);
    },
  });

  const toggleSetting = (key) => {
    if (key === "phoneVisibility") {
      const newValue = !settings.phoneVisibility;
      setSettings((prev) => ({ ...prev, [key]: newValue }));
      phoneVisibilityMutation.mutate(newValue);
    } else if (key === "chatAlertsNotification" || key === "chatProtection") {
      const newValue = !settings[key];
      setSettings((prev) => ({ ...prev, [key]: newValue }));
      const payload = {
        chatAlertsNotification: key === "chatAlertsNotification" ? newValue : settings.chatAlertsNotification,
        chatProtection: key === "chatProtection" ? newValue : settings.chatProtection,
      };
      chatAlertMutation.mutate(payload);
    } else if (key === "protectProfilePhoto" || key === "callProtection") {
      const newValue = !settings[key];
      setSettings((prev) => ({ ...prev, [key]: newValue }));
      const payload = {
        protectProfilePhoto:
          key === "protectProfilePhoto" ? newValue : settings.protectProfilePhoto,
        callProtection:
          key === "callProtection" ? newValue : settings.callProtection,
      };
      profileProtectionMutation.mutate(payload);
    } else if (key === "matchAlerts") {
      const newValue = !settings.matchAlerts;
      setSettings((prev) => ({ ...prev, [key]: newValue }));
      matchAlertMutation.mutate(newValue);
    } else if (key === 'messagePermission') {
      const oldSettings = { ...settings };
      const newValue = !settings.messagePermission;
      setSettings(prev => ({ ...prev, [key]: newValue }));
      whoCanMessageMutation.mutate({
        messagePermission: newValue,
        messageCategory: settings.messageCategory,
        oldSettings
      });
    } else {
      setSettings((prev) => ({ ...prev, [key]: !prev[key] }));
    }
  };

  const handleSelectChange = (key, value) => {
    const oldSettings = { ...settings };
    setSettings(prev => ({ ...prev, [key]: value }));
    whoCanMessageMutation.mutate({
      messagePermission: settings.messagePermission,
      messageCategory: value,
      oldSettings
    });
  };

  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 Alerts Preferences',
          description: 'Match Alerts Preferences content" typically refers to the various settings within an application (e.g., sports, finance, or business software)',
        },
        // {
        //   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: 'Who Can Message Me?',
          description: 'Control who is able to send you messages on the platform.',
        },
        {
          key: 'messageCategory',
          title: 'Allow messages from',
          description: 'Choose which category of users can message you.',
          type: 'select',
          options: ['All Profile', 'Matches', 'Premium Users']
        }
      ],
    },
  ];

  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:"#f2f2f2", 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}
              onSelectChange={handleSelectChange}
            />
          </TabPanel>
        ))}
      </Box>
    </Box>
  );
}