"use client";

import { useState, useEffect, useCallback } from "react";
import {
  ListEntity,
  ListItem,
  getChannelLists,
  createListItem,
  updateListItem,
  deleteListItem,
} from "@/lib/api";
import { ListColumn } from "./ListColumn";
import { CreateListModal } from "./CreateListModal";
import { ItemDetailModal } from "./ItemDetailModal";
import { Plus, ListChecks, Trash2 } from "lucide-react";

interface ListsViewProps {
  channelId: string;
}

export function ListsView({ channelId }: ListsViewProps) {
  const [lists, setLists] = useState<ListEntity[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [selectedItem, setSelectedItem] = useState<ListItem | null>(null);
  const [showItemModal, setShowItemModal] = useState(false);
  const [draggingItem, setDraggingItem] = useState<ListItem | null>(null);
  const [draggingItemId, setDraggingItemId] = useState<string | null>(null);

  const loadLists = useCallback(() => {
    setLoading(true);
    getChannelLists(channelId)
      .then((data) => setLists(data))
      .catch((err) => {
        console.error("Failed to load lists:", err);
        setError("Failed to load lists");
      })
      .finally(() => setLoading(false));
  }, [channelId]);

  useEffect(() => {
    loadLists();
  }, [loadLists]);

  const handleAddItem = async (listId: string, name: string) => {
    try {
      const newItem = await createListItem(listId, { name });
      setLists((prev) =>
        prev.map((l) =>
          l.id === listId ? { ...l, items: [...(l.items || []), newItem] } : l
        )
      );
    } catch (err) {
      console.error("Failed to create item:", err);
    }
  };

  const handleDeleteItem = async (listId: string, itemId: string) => {
    try {
      await deleteListItem(listId, itemId);
      setLists((prev) =>
        prev.map((l) =>
          l.id === listId ? { ...l, items: (l.items || []).filter((i) => i.id !== itemId) } : l
        )
      );
    } catch (err) {
      console.error("Failed to delete item:", err);
    }
  };

  const handleDragStart = (e: React.DragEvent, item: ListItem) => {
    setDraggingItem(item);
    setDraggingItemId(item.id);
    e.dataTransfer.effectAllowed = "move";
    e.dataTransfer.setData("text/plain", item.id);
  };

  const handleDragEnd = () => {
    setDraggingItem(null);
    setDraggingItemId(null);
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = "move";
  };

  const handleDrop = async (e: React.DragEvent, targetListId: string) => {
    e.preventDefault();
    if (!draggingItem) return;

    const sourceListId = lists.find((l) => l.items?.some((i) => i.id === draggingItem.id))?.id;
    if (!sourceListId) return;

    // Optimistic: move item in state
    setLists((prev) => {
      const newLists = prev.map((l) => ({ ...l, items: [...(l.items || [])] }));
      const sourceList = newLists.find((l) => l.id === sourceListId);
      const targetList = newLists.find((l) => l.id === targetListId);
      if (!sourceList || !targetList) return prev;

      sourceList.items = sourceList.items.filter((i) => i.id !== draggingItem.id);
      targetList.items = [...targetList.items, draggingItem];
      return newLists;
    });

    // API call to persist move
    try {
      await updateListItem(targetListId, draggingItem.id, {});
    } catch (err) {
      console.error("Failed to move item:", err);
      // Revert on failure
      loadLists();
    }

    setDraggingItem(null);
    setDraggingItemId(null);
  };

  const handleItemClick = (item: ListItem) => {
    setSelectedItem(item);
    setShowItemModal(true);
  };

  const handleListCreated = (list: ListEntity) => {
    setLists((prev) => [...prev, { ...list, items: [] }]);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-full text-gray-400">
        <div className="animate-pulse">Loading lists...</div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-full text-slack-red">
        <p>{error}</p>
      </div>
    );
  }

  // Determine the listId for the selected item
  const selectedItemListId = selectedItem
    ? lists.find((l) => l.items?.some((i) => i.id === selectedItem.id))?.id || ""
    : "";

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="flex items-center justify-between px-6 py-3 border-b border-gray-200 bg-white">
        <div className="flex items-center gap-2">
          <ListChecks size={22} className="text-slack-purple" />
          <h1 className="text-lg font-bold text-gray-800">Lists</h1>
          <span className="text-sm text-gray-400">({lists.length} lists)</span>
        </div>
        <button
          onClick={() => setShowCreateModal(true)}
          className="flex items-center gap-1.5 px-3 py-1.5 rounded-md bg-slack-purple text-white text-sm font-medium hover:bg-slack-darkpurple transition-colors"
        >
          <Plus size={16} />
          <span>New list</span>
        </button>
      </div>

      {/* Board */}
      <div className="flex-1 overflow-x-auto overflow-y-hidden p-4">
        <div className="flex gap-4 h-full">
          {lists.length === 0 ? (
            <div className="flex items-center justify-center w-full text-gray-400 flex-col gap-3">
              <ListChecks size={48} />
              <p>No lists yet. Create one to get started.</p>
            </div>
          ) : (
            lists.map((list) => (
              <ListColumn
                key={list.id}
                list={list}
                onItemClick={handleItemClick}
                onAddItem={handleAddItem}
                onDragStart={handleDragStart}
                onDragEnd={handleDragEnd}
                onDrop={handleDrop}
                onDragOver={handleDragOver}
                draggingItemId={draggingItemId}
              />
            ))
          )}
        </div>
      </div>

      {/* Modals */}
      <CreateListModal
        open={showCreateModal}
        channelId={channelId}
        onClose={() => setShowCreateModal(false)}
        onCreated={handleListCreated}
      />
      <ItemDetailModal
        open={showItemModal}
        item={selectedItem}
        listId={selectedItemListId}
        onClose={() => {
          setShowItemModal(false);
          setSelectedItem(null);
        }}
        onItemUpdated={loadLists}
      />
    </div>
  );
}