import {
    closestCenter,
    DndContext,
    KeyboardSensor,
    PointerSensor,
    useSensor,
    useSensors,
} from '@dnd-kit/core';
import type { DragEndEvent } from '@dnd-kit/core';
import {
    arrayMove,
    SortableContext,
    sortableKeyboardCoordinates,
    useSortable,
    verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { GripVertical } from 'lucide-react';
import { useEffect, useState } from 'react';
import { EmptyState } from '@/components/layout/empty-state';
import { ResourceActionsMenu } from '@/components/resource-actions-menu';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';
import { stripHtml } from '@/lib/strip-html';

export type FaqQuestionRow = {
    id: number;
    question: string;
    answer: string;
    is_active: boolean;
};

type FaqQuestionSortableListProps = {
    items: FaqQuestionRow[];
    disabled?: boolean;
    onReorder: (orderedIds: number[]) => void;
    onEdit: (item: FaqQuestionRow) => void;
    onDelete: (itemId: number) => void;
};

function SortableQuestionRow({
    item,
    index,
    disabled,
    onEdit,
    onDelete,
}: {
    item: FaqQuestionRow;
    index: number;
    disabled: boolean;
    onEdit: (item: FaqQuestionRow) => void;
    onDelete: (itemId: number) => void;
}) {
    const {
        attributes,
        listeners,
        setNodeRef,
        transform,
        transition,
        isDragging,
    } = useSortable({ id: item.id, disabled });

    const style: React.CSSProperties = {
        transform: CSS.Transform.toString(transform),
        transition,
    };

    return (
        <div
            ref={setNodeRef}
            style={style}
            className={cn(
                'group relative flex items-start gap-3 rounded-xl border border-border/70 bg-background p-4 shadow-sm transition-shadow hover:border-border hover:shadow-md',
                isDragging && 'z-10 border-primary/30 shadow-lg ring-2 ring-primary/10',
                !item.is_active && 'opacity-70',
            )}
        >
            <div className="flex shrink-0 flex-col items-center gap-2 pt-0.5">
                <span className="flex size-7 items-center justify-center rounded-lg bg-muted text-xs font-semibold text-muted-foreground">
                    {index + 1}
                </span>
                <button
                    type="button"
                    aria-label="Drag to reorder"
                    disabled={disabled}
                    className={cn(
                        'flex size-8 items-center justify-center rounded-lg border border-transparent text-muted-foreground transition-colors',
                        disabled
                            ? 'cursor-not-allowed opacity-40'
                            : 'cursor-grab hover:border-border hover:bg-muted hover:text-foreground active:cursor-grabbing',
                    )}
                    {...attributes}
                    {...listeners}
                >
                    <GripVertical className="size-4" />
                </button>
            </div>

            <div className="min-w-0 flex-1 space-y-2">
                <div className="flex flex-wrap items-start justify-between gap-3">
                    <div className="min-w-0 space-y-1">
                        <p className="font-medium leading-snug text-foreground">
                            {item.question}
                        </p>
                        {!item.is_active && (
                            <Badge variant="secondary" className="text-[10px] uppercase tracking-wide">
                                Draft
                            </Badge>
                        )}
                    </div>
                    <ResourceActionsMenu
                        onEdit={() => onEdit(item)}
                        onDelete={() => onDelete(item.id)}
                        deleteTitle="Delete question?"
                        deleteDescription="This question will be removed from the homepage FAQ."
                    />
                </div>
                <p className="line-clamp-3 text-sm leading-relaxed text-muted-foreground">
                    {stripHtml(item.answer)}
                </p>
            </div>
        </div>
    );
}

export function FaqQuestionSortableList({
    items,
    disabled = false,
    onReorder,
    onEdit,
    onDelete,
}: FaqQuestionSortableListProps) {
    const [localItems, setLocalItems] = useState(items);

    useEffect(() => {
        setLocalItems(items);
    }, [items]);

    const sensors = useSensors(
        useSensor(PointerSensor),
        useSensor(KeyboardSensor, {
            coordinateGetter: sortableKeyboardCoordinates,
        }),
    );

    const handleDragEnd = (event: DragEndEvent) => {
        const { active, over } = event;

        if (!over || active.id === over.id) {
            return;
        }

        const oldIndex = localItems.findIndex((item) => item.id === active.id);
        const newIndex = localItems.findIndex((item) => item.id === over.id);

        if (oldIndex === -1 || newIndex === -1) {
            return;
        }

        const reordered = arrayMove(localItems, oldIndex, newIndex);
        setLocalItems(reordered);
        onReorder(reordered.map((item) => item.id));
    };

    if (localItems.length === 0) {
        return (
            <EmptyState
                title="No questions yet"
                description="Add your first question to populate this category on the homepage."
                className="border-border/70 bg-muted/20 py-12"
            />
        );
    }

    return (
        <DndContext
            sensors={sensors}
            collisionDetection={closestCenter}
            onDragEnd={handleDragEnd}
        >
            <SortableContext
                items={localItems.map((item) => item.id)}
                strategy={verticalListSortingStrategy}
            >
                <div className="space-y-3">
                    <div className="flex items-center justify-between rounded-lg border border-dashed border-border/70 bg-muted/20 px-4 py-2.5 text-xs text-muted-foreground">
                        <span className="flex items-center gap-2">
                            <GripVertical className="size-3.5" />
                            Drag rows to reorder how questions appear on the site
                        </span>
                        <span>{localItems.length} item{localItems.length === 1 ? '' : 's'}</span>
                    </div>

                    {localItems.map((item, index) => (
                        <SortableQuestionRow
                            key={item.id}
                            item={item}
                            index={index}
                            disabled={disabled}
                            onEdit={onEdit}
                            onDelete={onDelete}
                        />
                    ))}
                </div>
            </SortableContext>
        </DndContext>
    );
}
