import { Head, Link, router } from '@inertiajs/react';
import type { ColumnDef } from '@tanstack/react-table';
import { format } from 'date-fns';
import { ArrowLeft, Save } from 'lucide-react';
import { useState } from 'react';
import { DataTable } from '@/components/data-table';
import { PageHeader } from '@/components/page-header';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { usePermissions } from '@/hooks/use-permissions';
import { index as assignmentIndex } from '@/routes/admin/academic-classes/assignments';
import { grade } from '@/routes/admin/academic-classes/assignments/submissions';
import { AssignmentStatusLabels } from '@/types/assignment';
import type { Assignment } from '@/types/assignment';
import type { Submission } from '@/types/submission';
import { SubmissionStatusLabels } from '@/types/submission';

type Props = {
    assignment: Assignment;
    submissions: Submission[];
};

function ScoreCell({
    assignmentId,
    submission,
    canUpdate,
}: {
    assignmentId: number;
    submission: Submission;
    canUpdate: boolean;
}) {
    const normalizedScore = submission.score ?? '';
    const [value, setValue] = useState(normalizedScore);
    const [savedScore, setSavedScore] = useState(normalizedScore);
    const [saving, setSaving] = useState(false);

    // Sync local state when the score changes externally (e.g. after save).
    if (normalizedScore !== savedScore) {
        setSavedScore(normalizedScore);
        setValue(normalizedScore);
    }

    if (!canUpdate) {
        return <div className="text-center">{submission.score ?? '-'}</div>;
    }

    const dirty = value !== normalizedScore;

    function handleSave() {
        setSaving(true);
        router.patch(
            grade.url([assignmentId, submission.id]),
            { score: value === '' ? null : value },
            {
                preserveScroll: true,
                preserveState: true,
                onFinish: () => setSaving(false),
            },
        );
    }

    return (
        <div className="flex items-center justify-center gap-1">
            <Input
                type="number"
                min={0}
                max={100}
                step="0.01"
                value={value}
                onChange={(event) => setValue(event.target.value)}
                className="h-8 w-20 text-center"
            />
            {dirty && (
                <Button
                    type="button"
                    size="icon"
                    variant="ghost"
                    className="h-8 w-8 shrink-0"
                    disabled={saving}
                    onClick={handleSave}
                >
                    <Save className="h-4 w-4" />
                </Button>
            )}
        </div>
    );
}

export default function SubmissionIndex({ assignment, submissions }: Props) {
    const { hasPermission } = usePermissions();
    const canUpdate = hasPermission('update-assignment-submissions');

    const columns: ColumnDef<Submission>[] = [
        {
            accessorKey: 'student.student_number',
            header: () => <span>NIM</span>,
            cell: ({ row }) => row.original.student?.student_number ?? '-',
        },
        {
            accessorKey: 'student.user.profile.full_name',
            header: () => <span>Nama Mahasiswa</span>,
            cell: ({ row }) =>
                row.original.student?.user?.profile?.full_name ?? '-',
        },
        {
            accessorKey: 'status',
            header: () => <span className="block text-center">Status</span>,
            meta: {
                className: 'w-[160px] text-center',
                headerClassName: 'w-[160px] text-center',
            },
            cell: ({ row }) => {
                const status = row.getValue('status') as
                    keyof typeof SubmissionStatusLabels | null;

                return (
                    <div className="flex justify-center">
                        {status ? (
                            <Badge
                                variant={
                                    status === 'submitted'
                                        ? 'default'
                                        : 'secondary'
                                }
                            >
                                {SubmissionStatusLabels[status]}
                            </Badge>
                        ) : (
                            <span className="text-muted-foreground">-</span>
                        )}
                    </div>
                );
            },
        },
        {
            accessorKey: 'submitted_at',
            header: () => <span>Waktu Kumpul</span>,
            cell: ({ row }) => {
                const submittedAt = row.getValue('submitted_at') as
                    string | null;

                return submittedAt
                    ? format(new Date(submittedAt), 'd MMM yyyy, HH:mm')
                    : '-';
            },
        },
        {
            accessorKey: 'score',
            header: () => <span className="block text-center">Nilai</span>,
            meta: {
                className: 'w-[140px] text-center',
                headerClassName: 'w-[140px] text-center',
            },
            cell: ({ row }) => (
                <ScoreCell
                    assignmentId={assignment.id}
                    submission={row.original}
                    canUpdate={canUpdate}
                />
            ),
        },
    ];

    return (
        <>
            <Head title="Pengumpulan Tugas" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Pengumpulan Tugas"
                    actions={
                        <Button variant="outline" asChild>
                            <Link href={assignmentIndex.url()}>
                                <ArrowLeft className="h-4 w-4" />
                                Kembali
                            </Link>
                        </Button>
                    }
                />

                <Card>
                    <CardHeader className="flex flex-row items-start justify-between gap-2">
                        <CardTitle>{assignment.title}</CardTitle>
                        <Badge
                            variant={
                                assignment.status === 'open'
                                    ? 'secondary'
                                    : 'destructive'
                            }
                        >
                            {AssignmentStatusLabels[assignment.status]}
                        </Badge>
                    </CardHeader>
                    <CardContent className="grid gap-1 text-sm text-muted-foreground">
                        <p>
                            Kelas: {assignment.course_class?.course?.code}{' '}
                            {assignment.course_class?.course?.name}
                        </p>
                        <p>
                            Batas Waktu:{' '}
                            {format(
                                new Date(assignment.deadline),
                                'd MMM yyyy, HH:mm',
                            )}
                        </p>
                        <p>Jumlah Pengumpulan: {submissions.length}</p>
                    </CardContent>
                </Card>

                <h2 className="text-lg font-semibold">Daftar Pengumpulan</h2>

                <DataTable columns={columns} data={submissions} />
            </div>
        </>
    );
}
