import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { InfoOutlined } from '@mui/icons-material';

import * as selectors from '../../../redux/selectors';
import { setAction } from '../../../redux/slices';

import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Stack,
  Switch,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Tooltip,
  Typography,
} from '@/mui/components';

import styles from './FeaturesTab.module.scss';

const findDependFeatureIdByCurrentId = (featuresDependsFieldData, targetValue) =>
  Object.entries(featuresDependsFieldData).find(([, value]) => value === targetValue)?.[0];

function FeaturesTab() {
  const dispatch = useDispatch();

  const featuresUi = useSelector(selectors.featuresUiSelector);
  const featuresData = useSelector(selectors.featuresDataSelector);
  const featuresDependsFieldData = useSelector(selectors.featuresDependsFieldDataSelector);
  const [removeConfirmationDialog, setRemoveConfirmationDialog] = useState(null);
  const [confirmMessage, setConfirmMessage] = useState(null);
  const [pendingChange, setPendingChange] = React.useState(null); // { id, value }

  const handleStateChange = ({ id, value }) => {
    const updatedFeatures = { ...featuresData };
    const disableDependents = (featureId) => {
      let dependentFeatureId = featuresDependsFieldData[featureId];
      while (dependentFeatureId) {
        if (updatedFeatures[dependentFeatureId] !== false) {
          updatedFeatures[dependentFeatureId] = false;
        }
        dependentFeatureId = featuresDependsFieldData[dependentFeatureId];
      }
    };

    if (!value) {
      disableDependents(id);
    }

    updatedFeatures[id] = value;

    dispatch(setAction({ featuresData: updatedFeatures }));
  };

  // Show confirmation ONLY when disabling sponsoredContent; otherwise apply immediately
  const maybeConfirm = ({ id, name, value, title }) => {
    if (!value && name === 'sponsoredContent') {
      setConfirmMessage(
        <>
          Disabling <strong>{title}</strong> will permanently remove all related settings from your channel and playlist
          configuration forms.
          <br />
          These settings cannot be restored once removed.
          <br />
          Are you sure you want to proceed?
        </>,
      );
      // we are about to go from true -> false; store for confirm
      setPendingChange({ id, value: false });
      setRemoveConfirmationDialog(true);
      return;
    }

    // All other cases → apply immediately
    handleStateChange({ id, value });
  };

  const handleConfirm = () => {
    if (pendingChange) {
      handleStateChange(pendingChange); // apply false (and disable dependents)
    }
    setRemoveConfirmationDialog(false);
    setPendingChange(null);
    setConfirmMessage(null);
  };

  const handleCancel = () => {
    // Explicitly restore sponsoredContent to TRUE if we were disabling it.
    if (pendingChange?.id) {
      const updated = { ...featuresData, [pendingChange.id]: true };
      dispatch(setAction({ featuresData: updated }));
    }
    setRemoveConfirmationDialog(false);
    setPendingChange(null);
    setConfirmMessage(null);
  };

  return (
    <TableContainer className={styles.Root}>
      <Table>
        <TableHead>
          <TableRow>
            <TableCell>Category</TableCell>
            <TableCell>Feature</TableCell>
            <TableCell>Status</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {featuresUi?.map((entity) => (
            <TableRow key={entity.categoryName}>
              <TableCell>
                <Typography variant="body2" color="text.primary" fontWeight={700}>
                  {entity.categoryName}
                </Typography>
              </TableCell>

              <TableCell>
                <Stack spacing={2} alignContent="center">
                  {entity.features.map((feature) => (
                    <Stack
                      key={feature.title}
                      direction="row"
                      gap={1}
                      alignItems="center"
                      className={styles.FeatureTitleRoot}
                    >
                      <Typography variant="body2" color="text.primary">
                        {feature.title}
                      </Typography>

                      {feature.name !== 'secureVideoPlayback' && feature.featureTooltipText && (
                        <Tooltip title={feature.featureTooltipText}>
                          <InfoOutlined fontSize="small" htmlColor="info.main" />
                        </Tooltip>
                      )}

                      {feature.name === 'secureVideoPlayback' && (
                        <Tooltip
                          title={
                            <>
                              Please use with caution! <br />
                              Enabling this feature significantly increases the load on the Traffic Manager, especially
                              for watches containing a large number of videos.
                              <br />
                              This may result in empty playlists being returned if the pods are not properly scaled.{' '}
                              <br />
                              Consider increasing the resources (CPU/memory) allocated to the Traffic Manager pods to
                              ensure stable performance.
                            </>
                          }
                        >
                          <InfoOutlined fontSize="small" htmlColor="info.main" />
                        </Tooltip>
                      )}
                    </Stack>
                  ))}
                </Stack>
              </TableCell>

              <TableCell>
                <Stack spacing={2} alignContent="center">
                  {entity.features.map((feature) => {
                    const dependFeatureValue =
                      featuresData[findDependFeatureIdByCurrentId(featuresDependsFieldData, feature.id)];
                    const disabled = feature.blockedByFeature && !dependFeatureValue;

                    return (
                      <Switch
                        key={feature.id}
                        color="primary"
                        size="small"
                        checked={featuresData[feature.id]}
                        disabled={disabled}
                        onChange={({ target }) =>
                          maybeConfirm({
                            id: feature.id,
                            value: target.checked,
                            name: feature.name,
                            title: feature.title,
                          })
                        }
                      />
                    );
                  })}
                </Stack>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
      {removeConfirmationDialog && (
        <Dialog open={!!removeConfirmationDialog} onClose={handleCancel} maxWidth="md">
          <DialogTitle onClose={() => setRemoveConfirmationDialog(null)}>Warning</DialogTitle>
          <DialogContent>{confirmMessage}</DialogContent>
          <DialogActions>
            <Button variant="outlined" color="primary" onClick={handleCancel}>
              Cancel
            </Button>
            <Button variant="contained" color="primary" onClick={handleConfirm}>
              Confirm
            </Button>
          </DialogActions>
        </Dialog>
      )}
    </TableContainer>
  );
}

export default FeaturesTab;
