import { Link, usePage } from '@inertiajs/react';
import { useState, useEffect } from 'react';
import axios from 'axios';

import { Project, SharedData, Collection, UserCan } from '@/types/index.d';

import { Button } from '@/components/ui/button';
import { Plus, Settings, GripVertical, MoreVertical } from 'lucide-react';
import { SearchBar } from '@/components/ui/search-bar';
import { DragDropContext, Droppable, Draggable, DropResult, DroppableProvided, DraggableProvided } from '@hello-pangea/dnd';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

import CreateCollectionModal from '@/pages/Collections/CreateCollectionModal';
import DeleteCollectionModal from '@/pages/Collections/DeleteCollectionModal';

interface Props {
    project: Project;
}

export default function ProjectSidebar({ project }: Props) {
    const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
    const [selectedCollection, setSelectedCollection] = useState<any>(null);
    const [searchQuery, setSearchQuery] = useState('');
    const [collections, setCollections] = useState(project.collections ?? []);
    const page = usePage<SharedData>();
    const can = page.props.userCan as UserCan;
    const { collection } = page.props as { collection?: Collection };

    // Update collections when project data changes
    useEffect(() => {
        setCollections(project.collections ?? []);
    }, [project.collections]);

    // Check if we're on any collection edit page
    const isEditPage = page.component === 'Collections/Edit';

    const isCollectionActive = (collectionId: number) => {
        if(page.component === 'Collections/Show' || page.component === 'Collections/Edit') {
            return collection?.id === collectionId;
        }

        return false;
    };

    const filteredCollections = collections.filter(collection =>
        collection.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        collection.slug.toLowerCase().includes(searchQuery.toLowerCase())
    );

    const handleDragEnd = async (result: DropResult) => {
        if (!result.destination) return;

        const items = Array.from(collections);
        const [reorderedItem] = items.splice(result.source.index, 1);
        items.splice(result.destination.index, 0, reorderedItem);

        // Update local state immediately for smooth UI
        setCollections(items);

        // Update the order in the backend
        try {
            await axios.post(route('projects.collections.reorder', project.id), {
                collections: items.map((item, index) => ({
                    id: item.id,
                    order: index,
                })),
            });
        } catch (error) {
            console.error('Failed to update collection order:', error);
            // Revert to original order if the API call fails
            setCollections(project.collections ?? []);
        }
    };

    return (
        <div>
            <aside className="w-full lg:w-64 space-y-4 sticky top-4">
                <div className="flex items-center justify-between">
                    <h3 className="font-medium">Collections</h3>
                    {can.create_collection && (
                    <Button
                        variant="default"
                        size="sm"
                        className="h-6 px-1 text-xs"
                        onClick={() => setIsCreateModalOpen(true)}
                    >
                        <Plus className="mr-1" />
                        Add New
                    </Button>
                    )}
                </div>

                <SearchBar
                    value={searchQuery}
                    onChange={setSearchQuery}
                    placeholder="Search collections..."
                    className="px-1"
                />

                <DragDropContext onDragEnd={handleDragEnd}>
                    <Droppable droppableId="collections">
                        {(provided: DroppableProvided) => (
                            <div
                                {...provided.droppableProps}
                                ref={provided.innerRef}
                                className="space-y-1"
                            >
                                {filteredCollections.map((collection, index) => (
                                    <Draggable
                                        key={collection.id}
                                        draggableId={collection.id.toString()}
                                        index={index}
                                        isDragDisabled={!isEditPage}
                                    >
                                        {(provided: DraggableProvided) => (
                                            <div
                                                ref={provided.innerRef}
                                                {...provided.draggableProps}
                                                className="flex items-center space-x-2"
                                            >
                                                {isEditPage && (
                                                    <div
                                                        {...provided.dragHandleProps}
                                                        className="p-2 text-muted-foreground hover:text-foreground cursor-grab"
                                                    >
                                                        <GripVertical className="w-4 h-4" />
                                                    </div>
                                                )}
                                                <Link
                                                    href={route('projects.collections.show', [project.id, collection.id])}
                                                    className={`flex-1 p-2 text-sm rounded-md hover:bg-accent ${
                                                        isCollectionActive(collection.id) ? 'bg-accent text-accent-foreground' : ''
                                                    }`}
                                                >
                                                    {collection.name}
                                                </Link>
                                                {can.access_collection_settings && (
                                                    <Link
                                                        href={route('projects.collections.edit', [project.id, collection.id])}
                                                        className="block p-2 text-sm rounded-md hover:bg-accent"
                                                    >
                                                        <Settings className="w-4 h-4" />
                                                    </Link>
                                                )}
                                                {(isEditPage && (can.update_collection || can.delete_collection)) && (
                                                    <DropdownMenu>
                                                        <DropdownMenuTrigger asChild>
                                                            <button
                                                                className="block p-2 text-sm rounded-md hover:bg-accent"
                                                            >
                                                                <MoreVertical className="w-4 h-4" />
                                                            </button>
                                                        </DropdownMenuTrigger>
                                                        <DropdownMenuContent align="end">
                                                            {can.update_collection && (
                                                                <DropdownMenuItem
                                                                    className="cursor-pointer"
                                                                    onClick={() => {
                                                                        setSelectedCollection(collection);
                                                                        setIsEditModalOpen(true);
                                                                    }}
                                                                >
                                                                    Edit Collection
                                                                </DropdownMenuItem>
                                                            )}
                                                            {can.delete_collection && (
                                                                <DropdownMenuItem
                                                                    className="text-destructive cursor-pointer"
                                                                    onClick={() => {
                                                                        setSelectedCollection(collection);
                                                                        setIsDeleteModalOpen(true);
                                                                    }}
                                                                >
                                                                    Delete Collection
                                                                </DropdownMenuItem>
                                                            )}
                                                        </DropdownMenuContent>
                                                    </DropdownMenu>
                                                )}
                                            </div>
                                        )}
                                    </Draggable>
                                ))}
                                {provided.placeholder}
                                {filteredCollections.length === 0 && (
                                    <p className="text-sm text-muted-foreground px-2">
                                        {searchQuery ? 'No collections found' : 'No collections yet'}
                                    </p>
                                )}
                            </div>
                        )}
                    </Droppable>
                </DragDropContext>
            </aside>

            <CreateCollectionModal
                open={isCreateModalOpen}
                onOpenChange={setIsCreateModalOpen}
                projectId={project.id}
            />

            <CreateCollectionModal
                open={isEditModalOpen}
                onOpenChange={setIsEditModalOpen}
                projectId={project.id}
                collection={selectedCollection}
            />

            <DeleteCollectionModal
                open={isDeleteModalOpen}
                onOpenChange={setIsDeleteModalOpen}
                projectId={project.id}
                collection={selectedCollection}
            />
        </div>
    );
}
