/* eslint-disable react-hooks/exhaustive-deps */
"use client";

import { useEffect, useState } from "react";
import { DragDropContext } from "@hello-pangea/dnd";
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
import { KanbanColumn } from "./_ui/kanvan-column";
import {
  useLeads,
  useLeadsWithoutPagination,
} from "@/app/_features/leads/useLead";
import Spinner from "@/app/components/ui/Spinner";
import { changeLeadStatus } from "@/app/_services/apiLead";
import { handleAxiosError } from "@/app/lib/utils";

export default function KanbanBoard() {
  const { isLoading, isError, error, data } = useLeadsWithoutPagination();

  const statuses = [
    "New",
    // "Qualified",
    "Test_Derived",
    // "Discussion",
    // "Negotiation",
    "Won",
    "Lost",
  ];

  const columnAccentColors = {
    New: "#fbbf24",
    // Qualified: "#60a5fa",
    Test_Derived: "#a78bfa",
    // Discussion: "#f87171",
    // Negotiation: "#c084fc",
    Won: "#10b981",
    Lost: "#ef4444",
  };

  const [state, setState] = useState(null);

  useEffect(() => {
    if (data) {
      const columns = statuses.reduce((columns, status) => {
        const filteredLeads = data?.filter((lead) => lead.status === status);

        columns[status] = {
          id: status,
          title: status.replace("_", " "),
          tasks: filteredLeads.map((lead) => {
            return {
              id: `${lead.id}`,
              title: lead.name,
              leadId: lead.id,
              assignee: {
                avatar: "/placeholder.svg",
                name: lead.name,
                email: lead.email,
                phone: lead.phone,
              },
              find_bike_questions: lead.find_bike_questions,
            };
          }),
          accentColor: columnAccentColors[status],
        };

        return columns;
      }, {});

      setState({ columns });
    }
  }, [data]);

  const onDragEnd = async (result) => {
    const { destination, source, draggableId } = result;

    // If there's no destination (dropped outside the board), do nothing
    if (!destination) {
      return;
    }

    const sourceColumn = state.columns[source.droppableId];
    const destColumn = state.columns[destination.droppableId];

    // Get the task to move
    const task = sourceColumn.tasks.find((t) => t.id === draggableId);

    if (!task) return;

    // Optimistically update the UI (before making the API request)
    const newSourceTasks = Array.from(sourceColumn.tasks);
    newSourceTasks.splice(source.index, 1); // Remove the task from the source column

    const newDestTasks = Array.from(destColumn.tasks);
    newDestTasks.splice(destination.index, 0, task); // Add the task to the destination column

    setState({
      ...state,
      columns: {
        ...state.columns,
        [sourceColumn.id]: {
          ...sourceColumn,
          tasks: newSourceTasks, // Updated source column
        },
        [destColumn.id]: {
          ...destColumn,
          tasks: newDestTasks, // Updated destination column
        },
      },
    });

    try {
      // Delay the API request to ensure the UI is updated first (for smoother experience)
      setTimeout(async () => {
        await changeLeadStatus({
          lead_id: draggableId,
          status: destination.droppableId,
        });
      }, 100); // Slight delay for API request
    } catch (err) {
      handleAxiosError(err);
    }

    // If the task is dropped in the same position, do nothing
    if (
      destination.droppableId === source.droppableId &&
      destination.index === source.index
    ) {
      return;
    }
  };

  if (isLoading) {
    return <Spinner />;
  }

  if (isError) {
    return <div>Error: {error.message}</div>;
  }

  if (!state) {
    return <div>No data available</div>;
  }

  return (
    <div className="flex flex-col h-screen bg-background">
      <ScrollArea className="w-dvw lg:w-[80dvw] whitespace-nowrap rounded-md border p-6">
        <DragDropContext onDragEnd={onDragEnd}>
          <div className="flex space-x-4">
            {Object.values(state.columns).map((column, index) => (
              <KanbanColumn key={column.id} column={column} index={index} />
            ))}
          </div>
        </DragDropContext>
        <ScrollBar orientation="horizontal" />
      </ScrollArea>
    </div>
  );
}
