// React Imports
import { useState, useEffect } from "react";

// MUI Imports
import Checkbox from "@mui/material/Checkbox";
import IconButton from "@mui/material/IconButton";
import Typography from "@mui/material/Typography";
import Chip from "@mui/material/Chip";
import Box from "@mui/material/Box";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import Divider from "@mui/material/Divider";
import Button from "@mui/material/Button";
import Badge from "@mui/material/Badge";
import Tooltip from "@mui/material/Tooltip";
import { useTheme } from "@mui/material/styles";

// Third-party Imports
import classnames from "classnames";

// Type Imports
import type { TodoType } from "@/types/apps/todoTypes";
import type { ThemeColor } from "@core/types";

// Component Imports
import CustomTextField from "@core/components/mui/TextField";

// API Imports
import { todoService } from "@/libs/api";

type Props = {
  todo: TodoType;
  onToggleComplete: (id: number) => void;
  onToggleStar: (id: number) => void;
  onToggleImportant: (id: number) => void;
  onDelete: (id: number) => void;
  onClick: (todo: TodoType) => void;
  onUpdate?: (todo: TodoType) => void;
};

const defaultLabels = ["Frontend", "Backend", "Doc", "Bug"];
const defaultLabelColors: Record<string, ThemeColor> = {
  Frontend: "primary",
  Backend: "warning",
  Doc: "success",
  Bug: "error",
};

const STORAGE_KEY = "todo_custom_labels";
const STORAGE_COLORS_KEY = "todo_label_colors";

// Helper functions for localStorage
const getCustomLabels = (): string[] => {
  if (typeof window === "undefined") return [];
  try {
    const stored = localStorage.getItem(STORAGE_KEY);
    return stored ? JSON.parse(stored) : [];
  } catch {
    return [];
  }
};

const getLabelColors = (): Record<string, ThemeColor> => {
  if (typeof window === "undefined") return defaultLabelColors;
  try {
    const stored = localStorage.getItem(STORAGE_COLORS_KEY);
    const customColors = stored ? JSON.parse(stored) : {};
    return { ...defaultLabelColors, ...customColors };
  } catch {
    return defaultLabelColors;
  }
};

const saveCustomLabels = (labels: string[]) => {
  if (typeof window === "undefined") return;
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(labels));
  } catch (error) {
    console.error("Error saving custom labels:", error);
  }
};

const saveLabelColor = (label: string, color: ThemeColor) => {
  if (typeof window === "undefined") return;
  try {
    const stored = localStorage.getItem(STORAGE_COLORS_KEY);
    const customColors = stored ? JSON.parse(stored) : {};
    customColors[label] = color;
    localStorage.setItem(STORAGE_COLORS_KEY, JSON.stringify(customColors));
  } catch (error) {
    console.error("Error saving label color:", error);
  }
};

const TodoItem = (props: Props) => {
  // Props
  const {
    todo,
    onToggleComplete,
    onToggleStar,
    onToggleImportant,
    onDelete,
    onClick,
    onUpdate,
  } = props;

  // States
  const [labelsAnchorEl, setLabelsAnchorEl] = useState<null | HTMLElement>(
    null
  );
  const [colorMenuAnchor, setColorMenuAnchor] = useState<{
    el: HTMLElement;
    label: string;
  } | null>(null);
  const [customLabels, setCustomLabels] = useState<string[]>(getCustomLabels());
  const [labelColors, setLabelColors] =
    useState<Record<string, ThemeColor>>(getLabelColors());
  const [newLabelInput, setNewLabelInput] = useState("");

  // Hooks
  const theme = useTheme();

  // Update label colors when localStorage changes
  useEffect(() => {
    setLabelColors(getLabelColors());
    setCustomLabels(getCustomLabels());
  }, []);

  const handleClick = () => {
    onClick(todo);
  };

  const handleCheckboxChange = (e: React.MouseEvent) => {
    e.stopPropagation();
    onToggleComplete(todo.id);
  };

  const handleStarClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    onToggleStar(todo.id);
  };

  const handleImportantClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    onToggleImportant(todo.id);
  };

  const handleDeleteClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    onDelete(todo.id);
  };

  const handleLabelsMenuOpen = (e: React.MouseEvent<HTMLElement>) => {
    e.stopPropagation();
    setLabelsAnchorEl(e.currentTarget);
  };

  const handleLabelsMenuClose = () => {
    setLabelsAnchorEl(null);
    setNewLabelInput("");
    setColorMenuAnchor(null);
  };

  const handleLabelToggle = async (label: string) => {
    const currentLabels = todo.labels || [];
    const newLabels = currentLabels.includes(label)
      ? currentLabels.filter((l) => l !== label)
      : [...currentLabels, label];

    try {
      const updatedTodo = await todoService.updateTodo(todo.id, {
        labels: newLabels,
      });
      if (onUpdate) {
        onUpdate(updatedTodo);
      }
    } catch (error) {
      console.error("Error updating todo labels:", error);
    }
  };

  const handleAddLabel = async () => {
    const trimmedLabel = newLabelInput.trim();
    const availableLabels = [...defaultLabels, ...customLabels];

    if (trimmedLabel && !availableLabels.includes(trimmedLabel)) {
      const updatedCustomLabels = [...customLabels, trimmedLabel];
      setCustomLabels(updatedCustomLabels);
      saveCustomLabels(updatedCustomLabels);

      // Set default color for new label
      const colors: ThemeColor[] = [
        "primary",
        "secondary",
        "success",
        "error",
        "warning",
        "info",
      ];
      const defaultColor =
        colors[updatedCustomLabels.length % colors.length] || "primary";
      const updatedColors = { ...labelColors, [trimmedLabel]: defaultColor };
      setLabelColors(updatedColors);
      saveLabelColor(trimmedLabel, defaultColor);

      // Add label to todo
      const currentLabels = todo.labels || [];
      const newLabels = [...currentLabels, trimmedLabel];

      try {
        const updatedTodo = await todoService.updateTodo(todo.id, {
          labels: newLabels,
        });
        if (onUpdate) {
          onUpdate(updatedTodo);
        }
      } catch (error) {
        console.error("Error adding label to todo:", error);
      }

      setNewLabelInput("");
    }
  };

  const handleNewLabelKeyDown = (
    event: React.KeyboardEvent<HTMLInputElement>
  ) => {
    if (event.key === "Enter") {
      event.preventDefault();
      handleAddLabel();
    }
  };

  const handleColorMenuOpen = (
    e: React.MouseEvent<HTMLElement>,
    label: string
  ) => {
    e.stopPropagation();
    setColorMenuAnchor({ el: e.currentTarget, label });
  };

  const handleColorMenuClose = () => {
    setColorMenuAnchor(null);
  };

  const handleColorChange = async (label: string, color: ThemeColor) => {
    const updatedColors = { ...labelColors, [label]: color };
    setLabelColors(updatedColors);
    saveLabelColor(label, color);
    handleColorMenuClose();
  };

  const getColorValue = (colorName: ThemeColor): string => {
    const colorMap: Record<ThemeColor, string> = {
      primary: theme.palette.primary.main,
      secondary: theme.palette.secondary.main,
      success: theme.palette.success.main,
      error: theme.palette.error.main,
      warning: theme.palette.warning.main,
      info: theme.palette.info.main,
    };
    return colorMap[colorName] || colorMap.primary;
  };

  const availableColors: ThemeColor[] = [
    "primary",
    "secondary",
    "success",
    "error",
    "warning",
    "info",
  ];
  const availableLabels = [...defaultLabels, ...customLabels];

  return (
    <li
      className={classnames(
        "todo-item cursor-pointer p-4 border-be border-solid border-bs",
        {
          completed: todo.status === "completed",
        }
      )}
      onClick={handleClick}
    >
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2 flex-1 overflow-hidden">
          <Checkbox
            checked={todo.status === "completed"}
            onChange={(e) => {
              e.stopPropagation();
              onToggleComplete(todo.id);
            }}
            onClick={(e) => e.stopPropagation()}
            size="small"
          />
          <div className="flex items-center gap-2 flex-1 min-is-0">
            <Typography
              variant="h6"
              className={classnames("font-medium truncate", {
                "line-through opacity-60": todo.status === "completed",
              })}
              color="text.primary"
            >
              {todo.title}
            </Typography>
            {todo.isKanban && (
              <Tooltip title="در Kanban">
                <Badge
                  badgeContent={<i className="tabler-layout-kanban text-xs" />}
                  color="success"
                  sx={{
                    '& .MuiBadge-badge': {
                      backgroundColor: theme.palette.success.main,
                      color: theme.palette.success.contrastText,
                      fontSize: '0.75rem',
                      padding: '2px 4px',
                      minWidth: 'auto',
                      height: '16px'
                    }
                  }}
                />
              </Tooltip>
            )}
          </div>
        </div>
        <div className="flex items-center gap-1">
          {todo.labels && todo.labels.length > 0 && (
            <>
              {todo.labels.map((label, index) => (
                <Chip
                  key={index}
                  label={label}
                  size="small"
                  variant="tonal"
                  color={labelColors[label] || "default"}
                  className="text-xs"
                  onDelete={(e) => {
                    e.stopPropagation();
                    handleLabelToggle(label);
                  }}
                  onClick={(e) => {
                    e.stopPropagation();
                    handleColorMenuOpen(e as any, label);
                  }}
                />
              ))}
            </>
          )}
          {todo.tags && todo.tags.length > 0 && (
            <>
              {todo.tags.map((tag, index) => (
                <Chip
                  key={`tag-${index}`}
                  label={tag}
                  size="small"
                  variant="outlined"
                  className="text-xs"
                  onDelete={(e) => {
                    e.stopPropagation();
                    // Handle tag deletion if needed
                  }}
                />
              ))}
            </>
          )}
          <IconButton
            size="small"
            onClick={handleLabelsMenuOpen}
            className="text-textSecondary"
            sx={{ padding: "4px" }}
          >
            <i className="tabler-tag text-base" />
          </IconButton>
          <IconButton
            size="small"
            onClick={handleImportantClick}
            className={classnames({
              "text-success": todo.isImportant,
            })}
          >
            <i className="tabler-info-circle text-lg" />
          </IconButton>
          <IconButton
            size="small"
            onClick={handleStarClick}
            className={classnames({
              "text-warning": todo.isStarred,
            })}
          >
            <i
              className={classnames("tabler-star text-lg", {
                "fill-current": todo.isStarred,
              })}
            />
          </IconButton>
          <IconButton size="small" onClick={handleDeleteClick}>
            <i className="tabler-trash text-lg text-textSecondary" />
          </IconButton>
        </div>
      </div>
      {todo.description && (
        <Typography
          variant="body2"
          className={classnames("truncate mb-0", {
            "opacity-60": todo.status === "completed",
          })}
          color="text.secondary"
        >
          {todo.description}
        </Typography>
      )}

      {/* Labels Menu */}
      <Menu
        anchorEl={labelsAnchorEl}
        open={Boolean(labelsAnchorEl)}
        onClose={handleLabelsMenuClose}
        anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
        transformOrigin={{ vertical: "top", horizontal: "left" }}
        PaperProps={{
          sx: { minWidth: 250 },
        }}
        onClick={(e) => e.stopPropagation()}
      >
        {availableLabels.map((label) => {
          const labelColor = labelColors[label] || "primary";
          const colorValue = getColorValue(labelColor);
          const isSelected = todo.labels?.includes(label) || false;

          return (
            <MenuItem
              key={label}
              onClick={() => handleLabelToggle(label)}
              sx={{ display: "flex", alignItems: "center", gap: 1 }}
            >
              <ListItemIcon sx={{ minWidth: 40 }}>
                <Checkbox checked={isSelected} />
              </ListItemIcon>
              <ListItemText primary={label} sx={{ flex: 1 }} />
              <IconButton
                size="small"
                onClick={(e) => {
                  e.stopPropagation();
                  handleColorMenuOpen(e, label);
                }}
                sx={{ padding: 0.5 }}
              >
                <i className="tabler-palette text-base" />
              </IconButton>
              <Button
                size="small"
                sx={{
                  minWidth: 10,
                  width: 20,
                  height: 20,
                  padding: 0,
                  bgcolor: colorValue,
                  borderRadius: "50%",
                  "&:hover": {
                    bgcolor: colorValue,
                    opacity: 0.8,
                  },
                }}
                onClick={(e) => {
                  e.stopPropagation();
                  handleColorMenuOpen(e, label);
                }}
              />
            </MenuItem>
          );
        })}
        <Divider />
        <Box className="flex flex-col gap-2 p-2">
          <CustomTextField
            size="small"
            placeholder="برچسب جدید..."
            value={newLabelInput}
            onChange={(e) => setNewLabelInput(e.target.value)}
            onKeyDown={handleNewLabelKeyDown}
            fullWidth
            onClick={(e) => e.stopPropagation()}
          />
          <Button
            variant="contained"
            size="small"
            onClick={handleAddLabel}
            disabled={
              !newLabelInput.trim() ||
              availableLabels.includes(newLabelInput.trim())
            }
            fullWidth
          >
            افزودن برچسب
          </Button>
        </Box>
      </Menu>

      {/* Color Selection Menu */}
      <Menu
        anchorEl={colorMenuAnchor?.el || null}
        open={Boolean(colorMenuAnchor)}
        onClose={handleColorMenuClose}
        anchorOrigin={{ vertical: "center", horizontal: "right" }}
        transformOrigin={{ vertical: "center", horizontal: "left" }}
        PaperProps={{
          sx: { padding: 1 },
        }}
        onClick={(e) => e.stopPropagation()}
      >
        <Box sx={{ display: "flex", gap: 1, flexDirection: "row" }}>
          {availableColors.map((color) => {
            const colorValue = getColorValue(color);
            const currentLabel = colorMenuAnchor?.label;
            const isSelected =
              currentLabel && labelColors[currentLabel] === color;

            return (
              <Button
                key={color}
                size="small"
                sx={{
                  minWidth: 10,
                  width: 30,
                  height: 30,
                  padding: 0,
                  bgcolor: colorValue,
                  borderRadius: "50%",
                  border: isSelected
                    ? `2px solid ${theme.palette.text.primary}`
                    : "none",
                  "&:hover": {
                    bgcolor: colorValue,
                    opacity: 0.8,
                  },
                }}
                onClick={(e) => {
                  e.stopPropagation();
                  if (currentLabel) {
                    handleColorChange(currentLabel, color);
                  }
                }}
              />
            );
          })}
        </Box>
      </Menu>
    </li>
  );
};

export default TodoItem;