import { useState } from "react";
import {
  CustomBox,
  CustomTypography,
  CustomTextField,
  CustomFormControl,
  CustomSelect,
  CustomMenuItem,
  CustomGrid,
  CustomDivider,
  CustomButton,
  CustomIconButton,
} from "../../../../../UI Components/Main";
import AddIcon from "@mui/icons-material/Add";
import CloseIcon from "@mui/icons-material/Close";
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";

const initialYearOptions = Array.from({ length: 3 }, (_, i) => `${2000 + i}`);
const initialStreamOptions = [
  "Science PCMB",
  "Science PCB",
  "Science PCM",
  "Commerce",
  "Arts",
];

const defaultEduData = {
  university: "",
  school: "",
  year: "",
  streamOrSubject: "",
  marksObtained: "",
  totalMarks: "",
};

const EducationQualification = () => {
  const [qualifications, setQualifications] = useState({
    tenth: { ...defaultEduData },
    twelfth: { ...defaultEduData },
    graduation: { ...defaultEduData },
  });

  const [yearOptions, setYearOptions] = useState(initialYearOptions);
  const [streamOptions, setStreamOptions] = useState(initialStreamOptions);
  const [showYearInput, setShowYearInput] = useState(false);
  const [showStreamInput, setShowStreamInput] = useState(false);
  const [newYear, setNewYear] = useState("");
  const [newStream, setNewStream] = useState("");

  const handleChange = (section, field, value) => {
    setQualifications((prev) => ({
      ...prev,
      [section]: {
        ...prev[section],
        [field]: value,
      },
    }));
  };

  const handleAddYear = () => {
    if (newYear && !yearOptions.includes(newYear)) {
      setYearOptions((prev) => [...prev, newYear]);
      setNewYear("");
    }
    setShowYearInput(false);
  };

  const handleAddStream = () => {
    if (newStream && !streamOptions.includes(newStream)) {
      setStreamOptions((prev) => [...prev, newStream]);
      setNewStream("");
    }
    setShowStreamInput(false);
  };

  const renderAddInputMenuItem = ({
    label,
    value,
    setValue,
    onAdd,
    onCancel,
  }) => (
    <CustomMenuItem disableRipple disableTouchRipple>
      <CustomBox
        display="flex"
        alignItems="center"
        width="100%"
        onClick={(e) => e.stopPropagation()}
      >
        <CustomTextField
          variant="standard"
          placeholder={`Enter ${label}`}
          value={value}
          onChange={(e) => setValue(e.target.value)}
          sx={{ flex: 1, mr: 1 }}
        />
        <CustomButton
          size="small"
          sx={{ minWidth: 48 }}
          onClick={(e) => {
            e.stopPropagation();
            onAdd();
          }}
        >
          Add
        </CustomButton>
        <CustomIconButton
          size="small"
          onClick={(e) => {
            e.stopPropagation();
            onCancel();
          }}
        >
          <CloseIcon fontSize="small" />
        </CustomIconButton>
      </CustomBox>
    </CustomMenuItem>
  );

  const renderSection = (label, key, streamLabel = "Stream") => (
    <CustomBox mb={4}>
      <CustomTypography variant="h6" fontWeight="bold" mb={2}>
        {label}
      </CustomTypography>

      <CustomTextField
        fullWidth
        variant="standard"
        placeholder="Name Of university or board"
        value={qualifications[key].university}
        onChange={(e) => handleChange(key, "university", e.target.value)}
        sx={{ mb: 2 }}
      />

      <CustomTextField
        fullWidth
        variant="standard"
        placeholder="Name of school or college"
        value={qualifications[key].school}
        onChange={(e) => handleChange(key, "school", e.target.value)}
        sx={{ mb: 2 }}
      />

      <CustomGrid container spacing={2}>
        <CustomGrid item xs={6}>
          <CustomFormControl fullWidth variant="standard" sx={{ width: "16.5rem" }}>
            <CustomSelect
              displayEmpty
              value={qualifications[key].year}
              onChange={(e) => handleChange(key, "year", e.target.value)}
              renderValue={(selected) =>
                selected ? selected : <CustomTypography>Year of Passing</CustomTypography>
              }
              IconComponent={KeyboardArrowDownIcon}
              MenuProps={{
                PaperProps: {
                  onMouseDown: (e) => e.stopPropagation(),
                  onClick: (e) => e.stopPropagation(),
                },
              }}
            >
              {yearOptions.map((year) => (
                <CustomMenuItem key={year} value={year}>
                  {year}
                </CustomMenuItem>
              ))}
              <CustomDivider />
              {showYearInput
                ? renderAddInputMenuItem({
                    label: "year",
                    value: newYear,
                    setValue: setNewYear,
                    onAdd: handleAddYear,
                    onCancel: () => setShowYearInput(false),
                  })
                : (
                  <CustomMenuItem
                    onClick={(e) => {
                      e.stopPropagation();
                      setShowYearInput(true);
                    }}
                  >
                    <CustomBox display="flex" alignItems="center">
                      <AddIcon fontSize="small" sx={{ mr: 0.5, color: "#284CFF" }} />
                      <CustomTypography sx={{ color: "#284CFF" }}>Add New</CustomTypography>
                    </CustomBox>
                  </CustomMenuItem>
                )}
            </CustomSelect>
          </CustomFormControl>
        </CustomGrid>

        <CustomGrid item xs={6}>
          <CustomFormControl fullWidth variant="standard" sx={{ width: "16.5rem" }}>
            <CustomSelect
              displayEmpty
              value={qualifications[key].streamOrSubject}
              onChange={(e) => handleChange(key, "streamOrSubject", e.target.value)}
              renderValue={(selected) =>
                selected ? selected : <CustomTypography>{streamLabel}</CustomTypography>
              }
              IconComponent={KeyboardArrowDownIcon}
              MenuProps={{
                PaperProps: {
                  onMouseDown: (e) => e.stopPropagation(),
                  onClick: (e) => e.stopPropagation(),
                },
              }}
            >
              {streamOptions.map((opt) => (
                <CustomMenuItem key={opt} value={opt}>
                  {opt}
                </CustomMenuItem>
              ))}
              <CustomDivider />
              {showStreamInput
                ? renderAddInputMenuItem({
                    label: "stream",
                    value: newStream,
                    setValue: setNewStream,
                    onAdd: handleAddStream,
                    onCancel: () => setShowStreamInput(false),
                  })
                : (
                  <CustomMenuItem
                    onClick={(e) => {
                      e.stopPropagation();
                      setShowStreamInput(true);
                    }}
                  >
                    <CustomBox display="flex" alignItems="center">
                      <AddIcon fontSize="small" sx={{ mr: 0.5, color: "#284CFF" }} />
                      <CustomTypography sx={{ color: "#284CFF" }}>Add New</CustomTypography>
                    </CustomBox>
                  </CustomMenuItem>
                )}
            </CustomSelect>
          </CustomFormControl>
        </CustomGrid>
      </CustomGrid>

      <CustomGrid container spacing={2} sx={{ mt: 1 }}>
        <CustomGrid item xs={6}>
          <CustomTextField
            fullWidth
            sx={{ width: "16.5rem" }}
            variant="standard"
            placeholder="Marks Obtained"
            value={qualifications[key].marksObtained}
            onChange={(e) => handleChange(key, "marksObtained", e.target.value)}
          />
        </CustomGrid>
        <CustomGrid item xs={6}>
          <CustomTextField
            fullWidth
            sx={{ width: "16.5rem" }}
            variant="standard"
            placeholder="Total Marks"
            value={qualifications[key].totalMarks}
            onChange={(e) => handleChange(key, "totalMarks", e.target.value)}
          />
        </CustomGrid>
      </CustomGrid>
    </CustomBox>
  );

  return (
    <>
      {renderSection("10th *", "tenth")}
      {renderSection("10 +2", "twelfth")}
      {renderSection("Graduation", "graduation")}
    </>
  );
};

export default EducationQualification;   this is my code when ever i click add new the menu is closing it should bot close it should remain open