import type { ColumnDef } from '@tanstack/react-table';
import { format } from 'date-fns';
import { ClipboardList, Pencil, Trash2, Upload } from 'lucide-react';
import { RowActions } from '@/components/row-actions';
import { Badge } from '@/components/ui/badge';
import { index as submissionsIndex } from '@/routes/admin/academic-classes/assignments/submissions';
import type { Assignment } from '@/types/assignment';
import { AssignmentStatusLabels } from '@/types/assignment';
import { deadlineTextClass, percentageOf } from './utils';

export type { Assignment } from '@/types/assignment';

type CreateColumnsParams = {
    handleEdit: (assignment: Assignment) => void;
    handleDeleteClick: (assignment: Assignment) => void;
    handleSubmitClick: (assignment: Assignment) => void;
    canUpdate: boolean;
    canDelete: boolean;
    canSubmit: boolean;
    canViewSubmissions: boolean;
};

export function createAssignmentColumns(
    params: CreateColumnsParams,
): ColumnDef<Assignment>[] {
    const {
        handleEdit,
        handleDeleteClick,
        handleSubmitClick,
        canUpdate,
        canDelete,
        canSubmit,
        canViewSubmissions,
    } = params;

    const columns: ColumnDef<Assignment>[] = [
        {
            accessorKey: 'title',
            header: () => <span>Judul</span>,
            cell: ({ row }) => (
                <span className="font-medium">
                    {row.getValue('title') as string}
                </span>
            ),
        },
        {
            accessorKey: 'course_class.course.name',
            header: () => <span>Kelas</span>,
            cell: ({ row }) => {
                const courseClass = row.original.course_class;

                if (!courseClass) {
                    return '-';
                }

                return `${courseClass.course?.code ?? ''} - ${courseClass.course?.name ?? ''}`;
            },
        },
        {
            accessorKey: 'deadline',
            header: () => <span>Batas Waktu</span>,
            cell: ({ row }) => {
                const assignment = row.original;

                return (
                    <span className={deadlineTextClass(assignment.deadline)}>
                        {format(
                            new Date(assignment.deadline),
                            'd MMM yyyy, HH:mm',
                        )}
                    </span>
                );
            },
        },
        {
            accessorKey: 'status',
            header: () => <span className="block text-center">Status</span>,
            meta: {
                className: 'text-center',
                headerClassName: 'text-center',
            },
            cell: ({ row }) => {
                const assignment = row.original;

                return (
                    <Badge
                        variant={
                            assignment.status === 'open'
                                ? 'secondary'
                                : 'destructive'
                        }
                    >
                        {AssignmentStatusLabels[assignment.status]}
                    </Badge>
                );
            },
        },
        {
            id: 'submissions',
            header: () => <span>Pengumpulan</span>,
            cell: ({ row }) => {
                const assignment = row.original;

                if (canSubmit) {
                    const mySubmission = assignment.submissions?.[0];

                    return (
                        <Badge
                            variant={
                                mySubmission?.status === 'submitted'
                                    ? 'default'
                                    : 'secondary'
                            }
                        >
                            {mySubmission?.status === 'submitted'
                                ? 'Sudah Mengumpulkan'
                                : 'Belum Mengumpulkan'}
                        </Badge>
                    );
                }

                const enrollmentsCount =
                    assignment.course_class?.enrollments_count ?? 0;

                return (
                    <div className="flex flex-col gap-0.5 text-xs text-muted-foreground">
                        <span>
                            {assignment.submissions_count.toLocaleString(
                                'id-ID',
                            )}{' '}
                            / {enrollmentsCount.toLocaleString('id-ID')}{' '}
                            mengumpulkan (
                            {percentageOf(
                                assignment.submissions_count,
                                enrollmentsCount,
                            )}
                            %)
                        </span>
                        <span>
                            {assignment.graded_submissions_count.toLocaleString(
                                'id-ID',
                            )}{' '}
                            /{' '}
                            {assignment.submissions_count.toLocaleString(
                                'id-ID',
                            )}{' '}
                            dinilai (
                            {percentageOf(
                                assignment.graded_submissions_count,
                                assignment.submissions_count,
                            )}
                            %)
                        </span>
                    </div>
                );
            },
        },
    ];

    columns.push({
        id: 'actions',
        header: () => <span className="block text-center">Aksi</span>,
        meta: {
            className: 'w-[160px] text-center',
            headerClassName: 'w-[160px] text-center',
        },
        cell: ({ row }) => {
            const assignment = row.original;
            const mySubmission = assignment.submissions?.[0];

            return (
                <div className="flex items-center justify-center">
                    <RowActions
                        actions={[
                            {
                                label:
                                    mySubmission?.status === 'submitted'
                                        ? 'Kumpulkan Ulang'
                                        : 'Kumpulkan Tugas',
                                icon: <Upload className="h-4 w-4" />,
                                show:
                                    canSubmit && assignment.status === 'open',
                                onClick: () => handleSubmitClick(assignment),
                            },
                            {
                                label: 'Pengumpulan',
                                icon: <ClipboardList className="h-4 w-4" />,
                                show: canViewSubmissions,
                                href: submissionsIndex.url(assignment.id),
                            },
                            {
                                label: 'Edit',
                                icon: <Pencil className="h-4 w-4" />,
                                show: canUpdate,
                                onClick: () => handleEdit(assignment),
                            },
                            {
                                label: 'Hapus',
                                icon: (
                                    <Trash2 className="h-4 w-4 text-destructive" />
                                ),
                                show: canDelete,
                                onClick: () => handleDeleteClick(assignment),
                            },
                        ]}
                    />
                </div>
            );
        },
    });

    return columns;
}
