import { useState } from 'react';
import { useDroppable } from '@dnd-kit/core';
import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { PlusIcon, XMarkIcon } from '@heroicons/react/24/solid';
import { TextArea, TextField } from '@heroui/react';
import { TaskCard, TaskCardData } from './TaskCard';
import { todayLocal } from '@/lib/formatDate';

interface Props {
    id: number;
    index: number;
    name: string;
    tasks: TaskCardData[];
    isDropTarget?: boolean;
    assigneeFilter?: string;
    search?: string;
    currentUserId?: number;
    canMoveAny?: boolean;
    onTaskClick: (id: number) => void;
    onQuickAddTask: (title: string) => void;
    onDeleteTask: (id: number) => void;
    onRemoveLabel: (taskId: number, labelId: number) => void;
    labelOverTaskId?: number | null;
}

// Cycle through a small palette so any number of columns still reads well;
// the first four map onto the default To Do / In Progress / Review / Done flow.
const COLUMN_COLORS = [
    { bar: 'bg-slate-400', header: 'bg-slate-50', text: 'text-slate-700', count: 'text-slate-400' },
    { bar: 'bg-amber-400', header: 'bg-amber-50', text: 'text-amber-800', count: 'text-amber-500' },
    { bar: 'bg-cyan-400', header: 'bg-cyan-50', text: 'text-cyan-800', count: 'text-cyan-500' },
    { bar: 'bg-emerald-400', header: 'bg-emerald-50', text: 'text-emerald-800', count: 'text-emerald-500' },
    { bar: 'bg-sky-400', header: 'bg-sky-50', text: 'text-sky-800', count: 'text-sky-500' },
    { bar: 'bg-rose-400', header: 'bg-rose-50', text: 'text-rose-800', count: 'text-rose-500' },
];

const todayStr = () => todayLocal();

export function BoardColumnView({ id, index, name, tasks, isDropTarget, assigneeFilter, search = '', currentUserId, canMoveAny, onTaskClick, onQuickAddTask, onDeleteTask, onRemoveLabel, labelOverTaskId }: Props) {
    const { setNodeRef } = useDroppable({ id: `column-${id}` });
    const colors = COLUMN_COLORS[index % COLUMN_COLORS.length];
    const isDoneColumn = name.trim().toLowerCase() === 'done';
    const [adding, setAdding] = useState(false);
    const [title, setTitle] = useState('');

    function submit() {
        if (title.trim()) {
            onQuickAddTask(title.trim());
            setTitle('');
        }
    }

    return (
        <div className={`flex-1 min-w-[240px] rounded-xl flex flex-col max-h-full border-2 overflow-hidden transition-colors ${isDropTarget ? 'border-sky-300' : 'border-transparent'} bg-gray-100`}>
            <div className={`h-1 ${colors.bar}`} />
            <div className={`flex items-center justify-between px-3 py-2.5 ${colors.header}`}>
                <span className={`text-sm font-semibold ${colors.text}`}>{name} <span className={`font-normal ${colors.count}`}>({tasks.length})</span></span>
            </div>

            <div ref={setNodeRef} className={`flex-1 overflow-y-auto px-2 pb-2 pt-2 min-h-[120px] ${isDropTarget ? 'bg-sky-50' : ''}`}>
                <SortableContext items={tasks.map((t) => t.id)} strategy={verticalListSortingStrategy}>
                    <div className="flex flex-col gap-2">
                        {tasks.map((task) => {
                            const failsAssignee = !!assigneeFilter && String(task.assignee?.id) !== assigneeFilter;
                            const failsSearch = !!search.trim() && !task.title.toLowerCase().includes(search.trim().toLowerCase());
                            return (
                                <TaskCard
                                    key={task.id}
                                    task={task}
                                    onClick={() => onTaskClick(task.id)}
                                    onDelete={() => onDeleteTask(task.id)}
                                    onRemoveLabel={(labelId) => onRemoveLabel(task.id, labelId)}
                                    dimmed={failsAssignee || failsSearch}
                                    canDrag={!!canMoveAny || task.assignee?.id === currentUserId}
                                    isLabelDropTarget={labelOverTaskId === task.id}
                                    isOverdue={!isDoneColumn && !!task.due_date && task.due_date < todayStr()}
                                />
                            );
                        })}
                    </div>
                </SortableContext>
            </div>

            <div className="px-2 pb-2">
                {adding ? (
                    <div className="flex flex-col gap-1.5">
                        <TextField value={title} onChange={setTitle} aria-label="Judul tugas baru">
                            <TextArea
                                autoFocus
                                placeholder="Judul tugas ini..."
                                rows={2}
                                fullWidth
                                onKeyDown={(e) => {
                                    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); submit(); }
                                    if (e.key === 'Escape') { setAdding(false); setTitle(''); }
                                }}
                            />
                        </TextField>
                        <div className="flex items-center gap-2">
                            <button
                                onClick={submit}
                                className="flex items-center gap-1.5 text-sm font-medium text-white bg-sky-600 hover:bg-sky-700 rounded-lg px-3 py-1.5 shadow-sm"
                            >
                                Tambah Kartu
                            </button>
                            <button onClick={() => { setAdding(false); setTitle(''); }} className="p-1.5 text-gray-400 hover:text-gray-600" aria-label="Batal">
                                <XMarkIcon className="w-4 h-4" />
                            </button>
                        </div>
                    </div>
                ) : (
                    <button
                        onClick={() => setAdding(true)}
                        className="w-full flex items-center justify-center gap-1.5 text-sm font-medium text-white bg-sky-600 hover:bg-sky-700 rounded-lg px-3 py-2 shadow-sm"
                    >
                        <PlusIcon className="w-4 h-4" />
                        Tambah Tugas
                    </button>
                )}
            </div>
        </div>
    );
}
