import React from "react";
import {
  DndContext,
  closestCenter,
  useSensor,
  useSensors,
  MouseSensor,
  TouchSensor,
  KeyboardSensor,
  DragEndEvent,
} from "@dnd-kit/core";
import {
  SortableContext,
  arrayMove,
  verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { Popover, IconButton, Typography, Box } from "@mui/material";
import { Table } from "@tanstack/react-table";
import DraggableColumn from "./column-list-item";
import "./index.scss";
import { CloseIcon } from "../../../assets/svg";

interface ColumnToggleProps<T> {
  anchorEl: HTMLElement | null;
  onClose: () => void;
  table: Table<T>;
  columnOrder: string[];
  setColumnOrder: React.Dispatch<React.SetStateAction<string[]>>;
}

const ColumnToggle = <T,>({
  anchorEl,
  onClose,
  table,
  columnOrder,
  setColumnOrder,
}: ColumnToggleProps<T>) => {
  const open = Boolean(anchorEl);
  const sensors = useSensors(
    useSensor(MouseSensor),
    useSensor(TouchSensor),
    useSensor(KeyboardSensor)
  );

  const allColumns = table.getAllLeafColumns();

  const shownColumns = columnOrder
    .map((id) => allColumns.find((col) => col.id === id))
    .filter((col) => col?.getIsVisible());

  const hiddenColumns = columnOrder
    .map((id) => allColumns.find((col) => col.id === id))
    .filter((col) => col && !col.getIsVisible());

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;

    if (!over || active.id === over.id) return;

    const activeCol = table.getColumn(active.id as string);
    const overCol = table.getColumn(over.id as string);
    if (!activeCol || !overCol) return;

    const activeVisible = activeCol.getIsVisible();
    const overVisible = overCol.getIsVisible();

    if (activeVisible !== overVisible) {
      activeCol.toggleVisibility();
    }

    const oldIndex = columnOrder.indexOf(active.id as string);
    const newIndex = columnOrder.indexOf(over.id as string);
    setColumnOrder(arrayMove(columnOrder, oldIndex, newIndex));
  };

  const toggleVisibility = (columnId: string) => {
    const col = table.getColumn(columnId);
    col?.toggleVisibility();
  };

  const handleHideAll = () => {
    allColumns.forEach((col) => col.toggleVisibility(false));
  };

  const handleShowAll = () => {
    allColumns.forEach((col) => col.toggleVisibility(true));
  };

  return (
    <Popover
      open={open}
      anchorEl={anchorEl}
      onClose={onClose}
      anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
      sx={{ width: "600px" }}
    >
      <div className="column-manager">
        <div className="header">
          <Typography variant="h6">Column</Typography>
          <IconButton size="small" onClick={onClose}>
            <CloseIcon />
          </IconButton>
        </div>

        <div className="content-wrapper">
          <DndContext
            sensors={sensors}
            collisionDetection={closestCenter}
            onDragEnd={handleDragEnd}
          >
            <div className="list-section">
              <div className="list-header">
                <Typography variant="subtitle2">Shown in List</Typography>
                {/* <button onClick={handleHideAll}>Hide All</button> */}
                <Box
                  onClick={handleHideAll}
                  fontStyle={{
                    cursor: "pointer",
                    color: "#C5C5C5",
                    fontSize: "12px",
                  }}
                >
                  Hide All
                </Box>
              </div>
              <SortableContext
                items={shownColumns.map((col) => col!.id)}
                strategy={verticalListSortingStrategy}
              >
                {shownColumns.map((col) => (
                  <DraggableColumn
                    key={col!.id}
                    column={col!}
                    onToggle={() => toggleVisibility(col!.id)}
                  />
                ))}
              </SortableContext>
            </div>

            <div className="list-section">
              <div className="list-header">
                <Typography variant="subtitle2">Hidden in List</Typography>
                {/* <button onClick={handleShowAll}>Show All</button> */}
                <Box
                  onClick={handleShowAll}
                  fontStyle={{
                    cursor: "pointer",
                    color: "#C5C5C5",
                    fontSize: "12px",
                  }}
                >
                  Show All
                </Box>
              </div>
              <SortableContext
                items={hiddenColumns.map((col) => col!.id)}
                strategy={verticalListSortingStrategy}
              >
                {hiddenColumns.map((col) => (
                  <DraggableColumn
                    key={col!.id}
                    column={col!}
                    onToggle={() => toggleVisibility(col!.id)}
                  />
                ))}
              </SortableContext>
            </div>
          </DndContext>
        </div>
      </div>
    </Popover>
  );
};

export default ColumnToggle;
