import React, { useRef, useState } from "react";
import {
  Box,
  Table,
  TableBody,
  TableCell,
  Switch,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Paper,
  Button,
  Tooltip,
  useMediaQuery,
  Snackbar,
  Alert,
} from "@mui/material";
import { styled, useTheme } from "@mui/material/styles";

interface TabData {
  id: number;
  name: string;
  isMandatory: boolean;
  enabled: boolean;
  renamedTo: string;
  order: number;
}
const initializeTabs = (renamedTabs: any, hasCustomQuestions: boolean): TabData[] => {
  const tabKeys = [
    { key: "STUDENT_DETAILS", defaultName: "Student Details", isMandatory: true },
    { key: "ADDRESS", defaultName: "Address Tab", isMandatory: true },
    { key: "CONTACT", defaultName: "Contact Tab", isMandatory: false },
    { key: "QUALIFICATION", defaultName: "Qualification Tab", isMandatory: false },
    { key: "SUBJECT", defaultName: "Subject Tab", isMandatory: false },
    { key: "FUTURE_PLANS", defaultName: "Future Plans Tab", isMandatory: false },
    { key: "NOTES", defaultName: "Notes Tab", isMandatory: false },
    { key: "ADDITIONAL_DETAILS", defaultName: "Additional Details", isMandatory: false },
    { key: "CONFIRMATION", defaultName: "Confirmation", isMandatory: true },
  ];

  const isEmpty = !renamedTabs || Object.keys(renamedTabs).length === 0;

  const tabData: TabData[] = tabKeys.map((tab, index) => {
    const orderKey = `TAB_${tab.key}_ORDER`;
    const renamedKey = `TAB_${tab.key}_RENAMED`;
    const showKey = `TAB_${tab.key}_SHOW`;

    let enabled: boolean;

    if (tab.isMandatory) {
      enabled = true;
    } else if (tab.key === "ADDITIONAL_DETAILS") {
      enabled = hasCustomQuestions;
    } else if (isEmpty) {
      enabled = true;
    } else {
      enabled = renamedTabs?.[showKey] === "1";
    }

    return {
      id: index + 1,
      name: tab.defaultName,
      isMandatory: tab.isMandatory,
      enabled,
      renamedTo: renamedTabs?.[renamedKey] || "",
      order: parseInt(renamedTabs?.[orderKey] || "999", 10),
    };
  });

  tabData.sort((a, b) => a.order - b.order);
  return tabData;
};

const StyledTableRow = styled(TableRow)({
  "&.dragging": {
    backgroundColor: "#f0f0f0",
    opacity: 0.5,
  },
});

const GreenSwitch = styled(Switch)({
  "& .MuiSwitch-switchBase.Mui-checked": {
    color: "#067a40",
    "&:hover": { backgroundColor: "rgba(6, 122, 64, 0.08)" },
  },
  "& .MuiSwitch-switchBase.Mui-checked + .MuiSwitch-track": {
    backgroundColor: "#067a40",
  },
  "& .MuiSwitch-switchBase.Mui-disabled": {
    color: "#ccc",
  },
  "& .MuiSwitch-switchBase.Mui-disabled + .MuiSwitch-track": {
    backgroundColor: "#ccc",
    opacity: 0.6,
  },
  "& .MuiSwitch-switchBase.Mui-disabled.Mui-checked": {
    color: "#ccc",
  },
  "& .MuiSwitch-switchBase.Mui-disabled.Mui-checked + .MuiSwitch-track": {
    backgroundColor: "#ccc",
    opacity: 0.6,
  },
});

const MuiInterviewTabs: React.FC<{
  interviewId: number;
  baseUrl: string;
  renamedTabs: any;
  hasCustomQuestions: boolean;
}> = ({ interviewId, baseUrl, renamedTabs, hasCustomQuestions }) => {
  const [tabs, setTabs] = useState<TabData[]>(initializeTabs(renamedTabs, hasCustomQuestions));
  const [showSuccess, setShowSuccess] = useState(false);
  const dragItem = useRef<number | null>(null);
  const dragOverItem = useRef<number | null>(null);
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));

  const updateTab = (id: number, changes: Partial<TabData>) =>
    setTabs((prev) => prev.map((tab) => (tab.id === id ? { ...tab, ...changes } : tab)));

  const handleDragEnd = () => {
    const from = dragItem.current;
    const to = dragOverItem.current;
    if (from === null || to === null || from === to) return;

    const updatedTabs = [...tabs];
    const [movedTab] = updatedTabs.splice(from, 1);
    updatedTabs.splice(to, 0, movedTab);

    const reordered = updatedTabs.map((tab, idx) => ({
      ...tab,
      order: idx + 1,
    }));

    setTabs(reordered);
    dragItem.current = null;
    dragOverItem.current = null;
  };

  const handleSave = async () => {
    const payload = {
      interviewId,
      tabs: tabs.map((tab, index) => ({
        name: tab.name,
        renamedTo: tab.renamedTo,
        enabled: tab.name === "Additional Details" ? hasCustomQuestions : tab.enabled,
        order: index + 1,
      })),
    };

    try {
      const response = await fetch(`${baseUrl}ev/interview`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      const resultText = await response.text();
      const result = JSON.parse(resultText);
      if (result?.success) {
        setShowSuccess(true);
        setTimeout(() => {
          setShowSuccess(false);
          if (result.redirect) {
            window.location.href = result.redirect;
          }
        }, 1500);
      } else {
        alert(result?.message || "Failed to save tabs.");
      }
    } catch (error) {
      console.error("Error saving tabs:", error);
      alert("An error occurred while saving.");
    }
  };

  return (
    <>
      <Snackbar
        open={showSuccess}
        autoHideDuration={1500}
        onClose={() => setShowSuccess(false)}
        anchorOrigin={{ vertical: "top", horizontal: "center" }}
        sx={{
          position: "fixed",
          top: 12,
          left: "50%",
          transform: "translateX(-50%)",
          zIndex: 9999,
        }}
      >
        <Alert
          onClose={() => setShowSuccess(false)}
          severity="success"
          variant="filled"
          sx={{ backgroundColor: "#067a40" }}
        >
          Tabs Saved
        </Alert>
      </Snackbar>

      <Box
        p={4}
        sx={{
          fontFamily: "Roboto, Helvetica, Arial, sans-serif",
          boxShadow: 3,
          borderRadius: 2,
          width: "80%",
          margin: "0 auto",
          backgroundColor: "#fff",
        }}
      >
        <TableContainer component={Paper}>
          <Table size="small">
            <TableHead>
              <TableRow>
                {!isMobile && (
                  <TableCell sx={{ width: "8%", fontWeight: "bold", textAlign: "center" }}>
                    Order
                  </TableCell>
                )}
                <TableCell sx={{ width: isMobile ? "40%" : "35%", fontWeight: "bold" }}>
                  Tab Name
                </TableCell>
                <TableCell sx={{ width: isMobile ? "40%" : "35%", fontWeight: "bold" }}>
                  Rename To
                </TableCell>
                <TableCell sx={{ width: "15%", fontWeight: "bold", textAlign: "center" }}>
                  Enable
                </TableCell>
              </TableRow>
            </TableHead>

            <TableBody>
              {tabs.map((tab, index) => (
                <StyledTableRow
                  key={tab.id}
                  draggable={!isMobile}
                  onDragStart={() => (dragItem.current = index)}
                  onDragEnter={() => (dragOverItem.current = index)}
                  onDragEnd={() => !isMobile && handleDragEnd()}
                  className={dragItem.current === index ? "dragging" : ""}
                >
                  {!isMobile && (
                    <TableCell sx={{ textAlign: "center" }}>
                      <Tooltip title="Drag to reorder" arrow>
                        <Box
                          component="span"
                          sx={{
                            cursor: "grab",
                            userSelect: "none",
                            fontSize: "1.3rem",
                            color: "#555",
                          }}
                        >
                          =
                        </Box>
                      </Tooltip>
                    </TableCell>
                  )}
                  <TableCell>{tab.name}</TableCell>
                  <TableCell>
                    <TextField
                      value={tab.renamedTo}
                      onChange={(e) => updateTab(tab.id, { renamedTo: e.target.value })}
                      size="small"
                      fullWidth
                      placeholder="Enter new tab name"
                      inputProps={{
                        style: { padding: "6px 8px", fontSize: "0.85rem" },
                        "aria-label": `Rename ${tab.name}`,
                      }}
                    />
                  </TableCell>
                 <TableCell sx={{ textAlign: "center" }}>
                      {(() => {
                        const [tooltipOpen, setTooltipOpen] = useState<number | null>(null);

                        let tooltipText = "";
                        let ariaLabel = "";
                        let isEditable = !tab.isMandatory && tab.name !== "Additional Details";
                        const isControlledByConfig = tab.name === "Additional Details";
                        const isEnabled = tab.enabled;
                        const isSwitchDisabled = !isEditable || isControlledByConfig;

                        if (isControlledByConfig) {
                          tooltipText = isEnabled
                            ? "Enabled. Visibility of this tab is controlled by the configuration setting 'Enable Custom Questions' on the Admin Interview page and cannot be changed here"
                            : "Disabled. Visibility of this tab is controlled by the configuration setting 'Enable Custom Questions' on the Admin Interview page and cannot be changed here";
                          ariaLabel = `Tab setting is ${isEnabled ? "enabled" : "disabled"}. Visibility of this tab is controlled by the configuration setting 'Enable Custom Questions' on the Admin Interview page and cannot be changed here`;
                        } else if (!isEditable) {
                          tooltipText = "Enabled (locked)";
                          ariaLabel = "Tab setting is enabled and cannot be changed.";
                        } else if (isEnabled) {
                          tooltipText = "Enabled – click to disable";
                          ariaLabel = "Tab setting is enabled. You can turn this off.";
                        } else {
                          tooltipText = "Disabled – click to enable";
                          ariaLabel = "Tab setting is disabled. You can turn this on.";
                        }

                        const handleMobileClick = () => {
                          if (isMobile) {
                            setTooltipOpen(tab.id);
                            setTimeout(() => setTooltipOpen(null), 2000);
                          }

                          // Only toggle if editable
                          if (!isSwitchDisabled) {
                            updateTab(tab.id, { enabled: !isEnabled });
                          }
                        };

                        const tooltipProps = {
                          title: tooltipText,
                          arrow: true,
                          open: isMobile ? tooltipOpen === tab.id : undefined,
                          disableHoverListener: isMobile,
                          disableFocusListener: isMobile,
                          disableTouchListener: isMobile,
                          componentsProps: {
                            popper: {
                              sx: {
                                "& .MuiTooltip-tooltip": {
                                  backgroundColor: "#fff",
                                  color: "#000",
                                  fontSize: "0.875rem",
                                  fontFamily: '"Open Sans", Arial, sans-serif',
                                  boxShadow: 2,
                                  border: "1px solid #ddd",
                                },
                              },
                            },
                          },
                        };

                        return (
                          <Tooltip {...tooltipProps}>
                            <span
                              onClick={handleMobileClick}
                              style={{ display: "inline-block", cursor: isMobile ? "pointer" : "default" }}
                            >
                              <GreenSwitch
                                checked={isEnabled}
                                disabled={isSwitchDisabled}
                                inputProps={{ "aria-label": ariaLabel }}
                              />
                            </span>
                          </Tooltip>
                        );
                      })()}
                  </TableCell>
                </StyledTableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>

        <Box mt={4} display="flex" justifyContent="center">
          <Button
            variant="outlined"
            onClick={handleSave}
            sx={{
              fontSize: "1rem",
              fontWeight: "bold",
              color: "#067a40",
              borderColor: "#067a40",
              padding: "0.3em 1em",
              textTransform: "none",
              borderWidth: "2px",
              "&:hover": {
                borderColor: "#067a40",
                backgroundColor: "#dcf9d4",
                
              },
            }}
          >
            Save Tabs
          </Button>
        </Box>
      </Box>
    </>
  );
};

export const InterviewConfiguration = MuiInterviewTabs;
