import React, { useEffect, useState } from "react";
import {
  Box,
  Typography,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  IconButton,
} from "@mui/material";
import SettingsOutlinedIcon from "@mui/icons-material/SettingsOutlined";
import {
  ExpandMore as ExpandMoreIcon,
  Settings as SettingsIcon,
} from "@mui/icons-material";
import ArrowDropDownIcon from "@mui/icons-material/ArrowDropDown";
import { kanbanStyles } from "./styles/styles";
import { Lane, SubLane, SwimLane } from "./types/types";
import {
  COLOR_CONSTANTS,
  LEAD_STATUS,
  STAGE,
  STAGE_GROUP,
} from "./constants/kanban-constants";
import Loader from "../listing/components/common/loader/loader";
import { KanbanSettingsDataProps } from "../listing/types/filter-settings";

const Kanban = ({
  metaData,
  data,
  kanbanSettingsData,
  isLoading,
  KanbanCardComponent,
  showSettings,
  onOpenSettings,
  isFlatJson = false,
  entity,
}: {
  metaData: any;
  data: any;
  kanbanSettingsData: KanbanSettingsDataProps;
  isLoading?: boolean;
  KanbanCardComponent: React.ComponentType<{
    key: string | number;
    cardData: any;
    color?: string;
    darkColor?: string;
    darkerColor?: string;
  }>;
  showSettings: boolean;
  onOpenSettings?: () => void;
  isFlatJson?: boolean;
  entity?: string;
}) => {
  const [expandedPanels, setExpandedPanels] = useState<{
    [key: string]: boolean;
  }>({
    Active: true,
  });

  const [subLaneExpanded, setSubLaneExpanded] = useState<{
    [key: string]: boolean;
  }>({});

  const [showMoreMap, setShowMoreMap] = useState<Record<string, boolean>>({});

  useEffect(() => {
    if (metaData?.swim_lanes?.length) {
      const initial: { [key: string]: boolean } = {};
      metaData?.swim_lanes.forEach((swim_lane: SwimLane) => {
        swim_lane?.sub_lanes?.forEach((sub_lane: SubLane) => {
          const key = `${swim_lane.name}-${sub_lane.name}`;
          initial[key] = sub_lane.expanded || false;
        });
      });
      setSubLaneExpanded(initial);
    }
  }, [metaData]);

  const toggleShowMore = (key: string) => {
    setShowMoreMap((prev) => ({ ...prev, [key]: !prev[key] }));
  };

  const handleAccordionChange =
    (panel: string) => (event: React.SyntheticEvent, isExpanded: boolean) => {
      setExpandedPanels((prev) => ({
        ...prev,
        [panel]: isExpanded,
      }));
    };

  const toggleSubLane = (subLaneKey: string) => {
    setSubLaneExpanded((prev) => ({
      ...prev,
      [subLaneKey]: !prev[subLaneKey],
    }));
  };

  const getLeadValue = (lead: any, attribute?: string) => {
    if (!attribute) return undefined;

    return isFlatJson ? lead?.[`${entity}__${attribute}`] : lead?.[attribute];
  };

  // Count leads in a main lane (by stage_group name)
  const getLeadCount = (laneName: string): number =>
    getFilteredLeads({ laneName })?.length;

  // Count leads in a swim lane (by lead_status name)
  const getSwimLaneCount = (swimLaneName: string): number =>
    getFilteredLeads({ swimLaneName })?.length;

  // Count leads in a specific sub-lane within a swim-lane
  const getSubLaneCount = ({
    laneName,
    swimLaneName,
    subLaneName,
  }: {
    laneName?: string;
    swimLaneName?: string;
    subLaneName?: string;
  }): number =>
    getFilteredLeads({ laneName, swimLaneName, subLaneName })?.length;

  const getFilteredLeads = ({
    laneName,
    swimLaneName,
    subLaneName,
  }: {
    laneName?: string;
    swimLaneName?: string;
    subLaneName?: string;
  }) => {
    if (!data?.length) return [];

    return data.filter((lead: any) => {
      if (
        laneName &&
        getLeadValue(
          lead,
          kanbanSettingsData?.lane?.attribute || STAGE_GROUP
        ) !== laneName
      ) {
        return false;
      }

      if (
        swimLaneName &&
        getLeadValue(
          lead,
          kanbanSettingsData?.swim_lane?.attribute || LEAD_STATUS
        ) !== swimLaneName
      ) {
        return false;
      }

      if (subLaneName && getLeadValue(lead, STAGE) !== subLaneName) {
        return false;
      }

      return true;
    });
  };

  return (
    <>
      {isLoading ? (
        <Loader />
      ) : (
        <Box>
          <Box
            className="kanban-container"
            sx={{ width: "100%", bgcolor: "white", overflowX: "auto" }}
          >
            {/* Header */}
            <Box sx={kanbanStyles.topHeader}>
              <IconButton
                onClick={onOpenSettings}
                sx={{
                  ...kanbanStyles.settingStyle,
                  visibility: showSettings ? "visible" : "hidden",
                }}
              >
                <SettingsOutlinedIcon />
              </IconButton>

              {/* Lane Headers */}
              <Box sx={{ ...kanbanStyles.syncingStyle, flex: 1 }}>
                {metaData?.lanes?.map((lane: Lane, index: number) => (
                  <Box
                    className="lane-header"
                    sx={{
                      ...kanbanStyles.laneHeader,
                      bgcolor: lane.color || COLOR_CONSTANTS[index % 4].color,
                    }}
                    key={lane.id}
                  >
                    <Box
                      sx={{
                        ...kanbanStyles.badge,
                        bgcolor:
                          lane.darkColor ||
                          COLOR_CONSTANTS[index % 4].darkerColor,
                      }}
                    >
                      {getLeadCount(lane.name)}
                    </Box>

                    <Typography variant="h6" fontWeight="bold" sx={{ px: 2 }}>
                      {lane?.name}
                    </Typography>
                  </Box>
                ))}
              </Box>
            </Box>

            {/* Content */}
            <Box
              className="kanban-content"
              id="kanban-content"
              sx={{
                maxHeight: "calc(100vh - 186px)",
                width: "fit-content",
              }}
            >
              {/* Swim Lanes */}
              {metaData?.swim_lanes?.length > 0 &&
                metaData?.swim_lanes?.map((swim_lane: SwimLane) => (
                  <Accordion
                    key={swim_lane.id}
                    expanded={!!expandedPanels[swim_lane.name]}
                    onChange={handleAccordionChange(swim_lane.name)}
                    sx={kanbanStyles.swimLaneAccordionStyle}
                    // disabled={getSwimLaneCount(swim_lane.id) === 0 ? true : false}
                  >
                    <AccordionSummary
                      // disabled={swim_lane?.sub_lanes?.length > 0 ? false : true}
                      expandIcon={<ArrowDropDownIcon sx={{ color: "black" }} />}
                      sx={kanbanStyles.swimlaneWrapperStyle}
                    >
                      <Typography
                        variant="body1"
                        fontWeight="medium"
                        sx={{ ml: 1.5 }}
                      >
                        {swim_lane?.name} ({getSwimLaneCount(swim_lane.name)})
                      </Typography>
                    </AccordionSummary>

                    <AccordionDetails
                      sx={{
                        pl: "16px",
                        pr: "8px",
                        width: "fit-content",
                        py: 0,
                      }}
                    >
                      <Box sx={{ ...kanbanStyles.syncingStyle, pl: 7 }}>
                        {metaData?.lanes?.map((lane: Lane, index: number) => (
                          <Box
                            className="column"
                            sx={{
                              ...kanbanStyles.columnStyle,
                              bgcolor:
                                lane?.color || COLOR_CONSTANTS[index % 4].color,
                            }}
                            key={lane.id}
                          >
                            {swim_lane?.sub_lanes?.length > 0 &&
                              swim_lane?.sub_lanes
                                ?.filter(
                                  (sub_lane: SubLane) =>
                                    sub_lane.lane_id.toString() ==
                                    lane.id.toString()
                                )
                                ?.map((sub_section: SubLane) => {
                                  const subLaneKey = `${swim_lane.name}-${sub_section.name}`;

                                  const subLaneCount = getSubLaneCount({
                                    laneName: lane?.name,
                                    swimLaneName: swim_lane?.name,
                                    subLaneName: sub_section?.name,
                                  });
                                  const hasLeads = subLaneCount > 0;

                                  return (
                                    <Accordion
                                      key={sub_section.id}
                                      expanded={
                                        hasLeads
                                          ? subLaneExpanded[subLaneKey] ?? true // auto-expand only if leads exist
                                          : false // force collapse if no leads
                                      }
                                      onChange={() => toggleSubLane(subLaneKey)}
                                      sx={{
                                        ...kanbanStyles.stageStyle,
                                        borderLeft: `4px solid ${
                                          lane.darkColor ||
                                          COLOR_CONSTANTS[index % 4].darkColor
                                        }`,
                                      }}
                                    >
                                      <AccordionSummary
                                        expandIcon={
                                          <ExpandMoreIcon
                                            sx={{
                                              display: hasLeads
                                                ? "block"
                                                : "none",
                                            }}
                                          />
                                        }
                                        sx={kanbanStyles.subSectionAccordion}
                                      >
                                        <Box
                                          sx={
                                            kanbanStyles.subSectionHeaderContainer
                                          }
                                        >
                                          <Box
                                            className="sub-section-count"
                                            sx={{
                                              ...kanbanStyles.subSectionCountContainer,
                                              bgcolor:
                                                lane?.darkColor ||
                                                COLOR_CONSTANTS[index % 4]
                                                  .darkColor,
                                            }}
                                          >
                                            {getSubLaneCount({
                                              laneName: lane?.name,
                                              swimLaneName: swim_lane?.name,
                                              subLaneName: sub_section?.name,
                                            })}
                                          </Box>
                                          <Typography
                                            fontWeight="700"
                                            color="#555354"
                                            fontSize="12px"
                                          >
                                            {sub_section?.name}
                                          </Typography>
                                        </Box>
                                      </AccordionSummary>

                                      <AccordionDetails
                                        sx={kanbanStyles.cardsContainer}
                                      >
                                        {(() => {
                                          const cards =
                                            data?.filter(
                                              (lead: any) =>
                                                getLeadValue(
                                                  lead,
                                                  kanbanSettingsData?.swim_lane
                                                    ?.attribute || LEAD_STATUS
                                                ) === swim_lane.name &&
                                                getLeadValue(lead, STAGE) ===
                                                  sub_section.name &&
                                                getLeadValue(
                                                  lead,
                                                  kanbanSettingsData?.lane
                                                    ?.attribute || STAGE_GROUP
                                                ) === lane.name
                                            ) ?? [];

                                          const key = `${lane.name}-${swim_lane.name}-${sub_section.name}`;
                                          const isExpanded = showMoreMap[key];

                                          const visibleCards = isExpanded
                                            ? cards
                                            : cards?.slice(0, 3);

                                          return (
                                            <>
                                              {visibleCards.map((card: any) => (
                                                <KanbanCardComponent
                                                  key={card.id}
                                                  cardData={card}
                                                  color={
                                                    lane?.color ||
                                                    COLOR_CONSTANTS[index % 4]
                                                      .color
                                                  }
                                                  darkColor={
                                                    lane?.darkColor ||
                                                    COLOR_CONSTANTS[index % 4]
                                                      .darkColor
                                                  }
                                                  darkerColor={
                                                    lane?.darkerColor ||
                                                    COLOR_CONSTANTS[index % 4]
                                                      .darkerColor
                                                  }
                                                />
                                              ))}

                                              {cards?.length > 3 && (
                                                <Typography
                                                  onClick={() =>
                                                    toggleShowMore(key)
                                                  }
                                                  sx={
                                                    kanbanStyles.showMoreStyle
                                                  }
                                                >
                                                  {isExpanded
                                                    ? "Show Less"
                                                    : "Show More"}
                                                </Typography>
                                              )}
                                            </>
                                          );
                                        })()}
                                      </AccordionDetails>
                                    </Accordion>
                                  );
                                })}

                            {!(swim_lane?.sub_lanes?.length > 0) && (
                              <Box
                                sx={{
                                  display: "flex",
                                  flexDirection: "column",
                                  gap: "12px",
                                }}
                              >
                                {(() => {
                                  const cards =
                                    data?.filter(
                                      (lead: any) =>
                                        getLeadValue(
                                          lead,
                                          kanbanSettingsData?.swim_lane
                                            ?.attribute || LEAD_STATUS
                                        ) === swim_lane.name &&
                                        getLeadValue(
                                          lead,
                                          kanbanSettingsData?.lane?.attribute ||
                                            STAGE_GROUP
                                        ) === lane.name
                                    ) ?? [];

                                  const key = `${lane.name}-${swim_lane.name}`;
                                  const isExpanded = showMoreMap[key];

                                  const visibleCards = isExpanded
                                    ? cards
                                    : cards?.slice(0, 3);

                                  return (
                                    <>
                                      {visibleCards.map((card: any) => (
                                        <KanbanCardComponent
                                          key={card.id}
                                          cardData={card}
                                          color={
                                            lane?.color ||
                                            COLOR_CONSTANTS[index % 4].color
                                          }
                                          darkColor={
                                            lane?.darkColor ||
                                            COLOR_CONSTANTS[index % 4].darkColor
                                          }
                                          darkerColor={
                                            lane?.darkerColor ||
                                            COLOR_CONSTANTS[index % 4]
                                              .darkerColor
                                          }
                                        />
                                      ))}

                                      {cards?.length > 3 && (
                                        <Typography
                                          onClick={() => toggleShowMore(key)}
                                          sx={kanbanStyles.showMoreStyle}
                                        >
                                          {isExpanded
                                            ? "Show Less"
                                            : "Show More"}
                                        </Typography>
                                      )}
                                    </>
                                  );
                                })()}
                              </Box>
                            )}
                          </Box>
                        ))}
                      </Box>
                    </AccordionDetails>
                  </Accordion>
                ))}
              {!(metaData?.swim_lanes?.length > 0) &&
                !(metaData?.sub_lanes?.length > 0) && (
                  <Box sx={{ ...kanbanStyles.syncingStyle, pl: "72px" }}>
                    {metaData?.lanes?.map((lane: Lane, index: number) => (
                      <Box
                        className="column"
                        sx={{
                          ...kanbanStyles.columnStyle,
                          bgcolor:
                            lane?.color || COLOR_CONSTANTS[index % 4].color,
                        }}
                        key={lane.id}
                      >
                        {!(metaData?.swim_lanes?.length > 0) && (
                          <Box
                            sx={{
                              display: "flex",
                              flexDirection: "column",
                              gap: "12px",
                            }}
                          >
                            {(() => {
                              const cards =
                                data?.filter(
                                  (lead: any) =>
                                    getLeadValue(
                                      lead,
                                      kanbanSettingsData?.lane?.attribute ||
                                        STAGE_GROUP
                                    ) === lane.name
                                ) ?? [];

                              const key = `${lane.name}`;
                              const isExpanded = showMoreMap[key];

                              const visibleCards = isExpanded
                                ? cards
                                : cards?.slice(0, 3);

                              return (
                                <>
                                  {visibleCards.map((card: any) => (
                                    <KanbanCardComponent
                                      key={card.id}
                                      cardData={card}
                                      color={
                                        lane?.color ||
                                        COLOR_CONSTANTS[index % 4].color
                                      }
                                      darkColor={
                                        lane?.darkColor ||
                                        COLOR_CONSTANTS[index % 4].darkColor
                                      }
                                      darkerColor={
                                        lane?.darkerColor ||
                                        COLOR_CONSTANTS[index % 4].darkerColor
                                      }
                                    />
                                  ))}

                                  {cards?.length > 3 && (
                                    <Typography
                                      onClick={() => toggleShowMore(key)}
                                      sx={kanbanStyles.showMoreStyle}
                                    >
                                      {isExpanded ? "Show Less" : "Show More"}
                                    </Typography>
                                  )}
                                </>
                              );
                            })()}
                          </Box>
                        )}
                      </Box>
                    ))}
                  </Box>
                )}
              {!(metaData?.swim_lanes?.length > 0) &&
                metaData?.sub_lanes?.length > 0 && (
                  <Box sx={{ ...kanbanStyles.syncingStyle, pl: "72px" }}>
                    {metaData?.lanes?.map((lane: Lane, index: number) => (
                      <Box
                        className="column"
                        sx={{
                          ...kanbanStyles.columnStyle,
                          bgcolor:
                            lane?.color || COLOR_CONSTANTS[index % 4].color,
                        }}
                        key={lane.id}
                      >
                        {metaData?.sub_lanes?.length > 0 &&
                          metaData?.sub_lanes
                            ?.filter(
                              (sub_lane: SubLane) =>
                                sub_lane.lane_id.toString() ==
                                lane.id.toString()
                            )
                            ?.map((sub_section: SubLane) => {
                              const subLaneKey = `${lane.name}-${sub_section.name}`;

                              const subLaneCount = getSubLaneCount({
                                laneName: lane?.name,
                                subLaneName: sub_section?.name,
                              });
                              const hasLeads = subLaneCount > 0;
                              console.log("hasLeads", hasLeads);

                              return (
                                <Accordion
                                  key={sub_section.id}
                                  expanded={
                                    hasLeads
                                      ? subLaneExpanded[subLaneKey] ?? true // auto-expand only if leads exist
                                      : false // force collapse if no leads
                                  }
                                  onChange={() => toggleSubLane(subLaneKey)}
                                  sx={{
                                    ...kanbanStyles.stageStyle,
                                    borderLeft: `4px solid ${
                                      lane.darkColor ||
                                      COLOR_CONSTANTS[index % 4].darkColor
                                    }`,
                                  }}
                                >
                                  <AccordionSummary
                                    expandIcon={
                                      <ExpandMoreIcon
                                        sx={{
                                          display: hasLeads ? "block" : "none",
                                        }}
                                      />
                                    }
                                    sx={kanbanStyles.subSectionAccordion}
                                  >
                                    <Box
                                      sx={
                                        kanbanStyles.subSectionHeaderContainer
                                      }
                                    >
                                      <Box
                                        className="sub-section-count"
                                        sx={{
                                          ...kanbanStyles.subSectionCountContainer,
                                          bgcolor:
                                            lane?.darkColor ||
                                            COLOR_CONSTANTS[index % 4]
                                              .darkColor,
                                        }}
                                      >
                                        {getSubLaneCount({
                                          laneName: lane?.name,
                                          subLaneName: sub_section?.name,
                                        })}
                                      </Box>
                                      <Typography
                                        fontWeight="700"
                                        color="#555354"
                                        fontSize="12px"
                                      >
                                        {sub_section?.name}
                                      </Typography>
                                    </Box>
                                  </AccordionSummary>

                                  <AccordionDetails
                                    sx={kanbanStyles.cardsContainer}
                                  >
                                    {(() => {
                                      const cards =
                                        data?.filter(
                                          (lead: any) =>
                                            getLeadValue(lead, STAGE) ===
                                              sub_section.name &&
                                            getLeadValue(
                                              lead,
                                              kanbanSettingsData?.lane
                                                ?.attribute || STAGE_GROUP
                                            ) === lane.name
                                        ) ?? [];

                                      const key = `${lane.name}-${sub_section.name}`;
                                      const isExpanded = showMoreMap[key];

                                      const visibleCards = isExpanded
                                        ? cards
                                        : cards?.slice(0, 3);

                                      return (
                                        <>
                                          {visibleCards.map((card: any) => (
                                            <KanbanCardComponent
                                              key={card.id}
                                              cardData={card}
                                              color={
                                                lane?.color ||
                                                COLOR_CONSTANTS[index % 4].color
                                              }
                                              darkColor={
                                                lane?.darkColor ||
                                                COLOR_CONSTANTS[index % 4]
                                                  .darkColor
                                              }
                                              darkerColor={
                                                lane?.darkerColor ||
                                                COLOR_CONSTANTS[index % 4]
                                                  .darkerColor
                                              }
                                            />
                                          ))}

                                          {cards?.length > 3 && (
                                            <Typography
                                              onClick={() =>
                                                toggleShowMore(key)
                                              }
                                              sx={kanbanStyles.showMoreStyle}
                                            >
                                              {isExpanded
                                                ? "Show Less"
                                                : "Show More"}
                                            </Typography>
                                          )}
                                        </>
                                      );
                                    })()}
                                  </AccordionDetails>
                                </Accordion>
                              );
                            })}
                      </Box>
                    ))}
                  </Box>
                )}
            </Box>
          </Box>
        </Box>
      )}
    </>
  );
};

export default Kanban;
