import { useState } from "react";
import {
  Popover,
  Box,
  IconButton,
  MenuItem,
  Select,
  Typography,
  Button,
} from "@mui/material";
import {
  DndContext,
  closestCenter,
  useSensor,
  useSensors,
  MouseSensor,
  TouchSensor,
  KeyboardSensor,
} from "@dnd-kit/core";
import {
  arrayMove,
  SortableContext,
  verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import SortableItem from "./sorting-item";
import { AddIcon, CloseIcon } from "../../assets/svg";

interface SortItem {
  id: string;
  field: string;
  direction: "asc" | "desc";
}

type SortPopoverProps = {
  anchorEl: HTMLElement | null;
  onClose: () => void;
  columns: { id: string; label: string }[];
  onChange: (sorting: { id: string; desc: boolean }[]) => void;
};

const SortPopover = ({
  anchorEl,
  onClose,
  columns,
  onChange,
}: SortPopoverProps) => {
  const [sorts, setSorts] = useState<SortItem[]>([]);

  const sensors = useSensors(
    useSensor(MouseSensor),
    useSensor(TouchSensor),
    useSensor(KeyboardSensor)
  );

  const handleDragEnd = (event: any) => {
    const { active, over } = event;
    if (active.id !== over.id) {
      const oldIndex = sorts.findIndex((item) => item.id === active.id);
      const newIndex = sorts.findIndex((item) => item.id === over.id);
      const updated = arrayMove(sorts, oldIndex, newIndex);
      setSorts(updated);
      triggerTableSortUpdate(updated);
    }
  };

  const handleChange = (id: string, field: keyof SortItem, value: any) => {
    const updated = sorts.map((item) =>
      item.id === id ? { ...item, [field]: value } : item
    );
    setSorts(updated);
    triggerTableSortUpdate(updated);
  };

  const handleAddSort = () => {
    const newSort: SortItem = {
      id: Date.now().toString(),
      field: columns[0]?.id ?? "",
      direction: "asc",
    };
    const updated = [...sorts, newSort];
    setSorts(updated);
    triggerTableSortUpdate(updated);
  };

  const handleRemove = (id: string) => {
    const updated = sorts.filter((item) => item.id !== id);
    setSorts(updated);
    triggerTableSortUpdate(updated);
  };

  const triggerTableSortUpdate = (sortItems: SortItem[]) => {
    const sortingPayload = sortItems.map((item) => ({
      id: item.field,
      desc: item.direction === "desc",
    }));
    onChange(sortingPayload);
  };

  return (
    <Popover
      open={Boolean(anchorEl)}
      anchorEl={anchorEl}
      onClose={onClose}
      anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
    >
      <Box p={2} minWidth={300}>
        <Box
          display="flex"
          justifyContent="space-between"
          alignItems="center"
          px={2}
          py={1}
          sx={{
            backgroundColor: "#F9FAFB",
            // borderBottom: "1px solid #E0E0E0",
            margin: "-16px -16px 16px -16px",
          }}
        >
          <Typography fontSize="18px" fontWeight={600} color="#0C2033">
            Sort By
          </Typography>
          <IconButton size="small" onClick={onClose}>
            <CloseIcon />
          </IconButton>
        </Box>

        {sorts.length > 0 && (
          <DndContext
            sensors={sensors}
            collisionDetection={closestCenter}
            onDragEnd={handleDragEnd}
          >
            <SortableContext
              items={sorts.map((s) => s.id)}
              strategy={verticalListSortingStrategy}
            >
              {sorts.map((sort) => (
                <SortableItem key={sort.id} id={sort.id}>
                  <Box display="flex" gap={1} alignItems="center" mb={1}>
                    <Select
                      value={sort.field}
                      onChange={(e) =>
                        handleChange(sort.id, "field", e.target.value)
                      }
                      size="small"
                      fullWidth
                      sx={{ fontWeight: 400, fontSize: 14, color: "#000" }}
                    >
                      {columns.map((col) => (
                        <MenuItem key={col.id} value={col.id}>
                          {col.label}
                        </MenuItem>
                      ))}
                    </Select>
                    <Select
                      value={sort.direction}
                      onChange={(e) =>
                        handleChange(sort.id, "direction", e.target.value)
                      }
                      size="small"
                      sx={{ fontWeight: 400, fontSize: 14, color: "#000" }}
                    >
                      <MenuItem value="asc">Ascending</MenuItem>
                      <MenuItem value="desc">Descending</MenuItem>
                    </Select>
                    <IconButton
                      size="small"
                      onClick={() => handleRemove(sort.id)}
                    >
                      <CloseIcon />
                    </IconButton>
                  </Box>
                </SortableItem>
              ))}
            </SortableContext>
          </DndContext>
        )}

        <Button
          onClick={handleAddSort}
          startIcon={
            <span>
              <AddIcon />
            </span>
          }
          size="small"
          sx={{
            fontWeight: 400,
            fontSize: 12,
            color: "#888888",
          }}
        >
          Add Sort
        </Button>
      </Box>
    </Popover>
  );
};

export default SortPopover;
