import { Head, router } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useState } from 'react';
import type { PaginationState } from '@/components/data-table';
import { DataTable } from '@/components/data-table';
import { DeleteConfirmDialog } from '@/components/delete-confirm-dialog';
import { FileUploadField } from '@/components/file-upload-field';
import { FormDialog } from '@/components/form-dialog';
import InputError from '@/components/input-error';
import { PageHeader } from '@/components/page-header';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { useServerTable } from '@/hooks/use-server-table';
import {
    index as letterRequestIndex,
    destroy,
    store,
    update,
} from '@/routes/admin/services/letter-requests';
import type {
    LetterRequest,
    LetterRequestStudent,
} from '@/types/letter-request';
import { LetterStatuses, LetterStatusLabels } from '@/types/letter-request';
import { createLetterRequestColumns } from './columns';

type Props = {
    letterRequests: {
        data: LetterRequest[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    students: LetterRequestStudent[];
    highlight?: number;
};

function studentLabel(student: LetterRequestStudent): string {
    return `${student.user?.profile?.full_name ?? 'N/A'} - ${student.student_number}`;
}

export default function LetterRequestIndex({
    letterRequests,
    students,
    highlight,
}: Props) {
    const [createOpen, setCreateOpen] = useState(false);
    const [editing, setEditing] = useState<LetterRequest | null>(null);
    const [deleting, setDeleting] = useState<LetterRequest | null>(null);

    const pagination: PaginationState = {
        current_page: letterRequests.current_page,
        last_page: letterRequests.last_page,
        per_page: letterRequests.per_page,
        total: letterRequests.total,
    };

    const {
        search,
        handlePageChange,
        handlePerPageChange,
        handleSearchChange,
    } = useServerTable({
        route: () => letterRequestIndex.url(),
        pagination,
    });

    function handleDelete() {
        if (!deleting) {
            return;
        }

        router.delete(destroy(deleting.id), {
            onSuccess: () => setDeleting(null),
        });
    }

    const columns = createLetterRequestColumns({
        handleEdit: (letterRequest) => setEditing(letterRequest),
        handleDeleteClick: (letterRequest) => setDeleting(letterRequest),
    });

    return (
        <>
            <Head title="Surat Permohonan" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Surat Permohonan"
                    description={
                        highlight && (
                            <p className="mt-1 text-sm text-muted-foreground">
                                Menampilkan surat permohonan dari notifikasi.
                            </p>
                        )
                    }
                    actions={
                        <Button asChild>
                            <button
                                type="button"
                                onClick={() => setCreateOpen(true)}
                            >
                                <Plus className="h-4 w-4" />
                                Tambah
                            </button>
                        </Button>
                    }
                />

                <CreateForm
                    open={createOpen}
                    onOpenChange={setCreateOpen}
                    students={students}
                />

                <EditForm
                    key={editing?.id}
                    open={editing !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setEditing(null);
                        }
                    }}
                    editing={editing}
                    students={students}
                />

                <DataTable
                    columns={columns}
                    data={letterRequests.data}
                    emptyText="Belum ada surat permohonan."
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                    searchKey="student"
                    searchPlaceholder="Cari nama, NIM, atau jenis surat..."
                />

                <DeleteConfirmDialog
                    target={deleting}
                    onOpenChange={(open) => {
                        if (!open) {
                            setDeleting(null);
                        }
                    }}
                    title="Hapus Surat Permohonan"
                    description={(letterRequest) =>
                        `Apakah Anda yakin ingin menghapus permohonan "${letterRequest.letter_type}" milik "${letterRequest.student?.user?.profile?.full_name ?? 'mahasiswa ini'}"? Tindakan ini tidak dapat dibatalkan.`
                    }
                    onConfirm={handleDelete}
                />
            </div>
        </>
    );
}

function LetterRequestFields({
    errors,
    editing,
    students,
    resetKey,
}: {
    errors: Record<string, string>;
    editing?: LetterRequest;
    students: LetterRequestStudent[];
    resetKey?: string;
}) {
    return (
        <>
            <div className="grid gap-2">
                <Label>
                    Mahasiswa <span className="text-destructive">*</span>
                </Label>
                {!editing && <input type="hidden" name="student_id" />}
                <Select
                    name="student_id"
                    defaultValue={
                        editing ? String(editing.student_id) : undefined
                    }
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Pilih mahasiswa" />
                    </SelectTrigger>
                    <SelectContent>
                        {students.map((student) => (
                            <SelectItem
                                key={student.id}
                                value={String(student.id)}
                            >
                                {studentLabel(student)}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
                <InputError message={errors.student_id} />
            </div>
            <div className="grid gap-2">
                <Label htmlFor="letter_type">
                    Jenis Surat <span className="text-destructive">*</span>
                </Label>
                <Input
                    id="letter_type"
                    name="letter_type"
                    placeholder="Contoh: Surat Aktif Kuliah"
                    defaultValue={editing?.letter_type ?? ''}
                    aria-invalid={!!errors.letter_type}
                />
                <InputError message={errors.letter_type} />
            </div>
            <div className="grid gap-2">
                <Label htmlFor="purpose">Keperluan</Label>
                <Textarea
                    id="purpose"
                    name="purpose"
                    placeholder="Keperluan pengajuan surat"
                    defaultValue={editing?.purpose ?? ''}
                    aria-invalid={!!errors.purpose}
                />
                <InputError message={errors.purpose} />
            </div>
            <div className="grid gap-2">
                <Label>Status</Label>
                <input type="hidden" name="status" />
                <Select
                    name="status"
                    defaultValue={editing?.status ?? 'submitted'}
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Pilih status" />
                    </SelectTrigger>
                    <SelectContent>
                        {LetterStatuses.map((status) => (
                            <SelectItem key={status} value={status}>
                                {LetterStatusLabels[status]}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
                <InputError message={errors.status} />
            </div>
            <FileUploadField
                key={resetKey}
                name="result"
                label="Dokumen Hasil"
                existingFileName={editing?.result_name}
                existingFileUrl={editing?.result_url}
                error={errors.result}
            />
        </>
    );
}

function CreateForm({
    open,
    onOpenChange,
    students,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    students: LetterRequestStudent[];
}) {
    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Tambah Surat Permohonan"
            action={store()}
            resetOnSuccess
            onSuccess={() => onOpenChange(false)}
        >
            {({ errors }) => (
                <div className="grid gap-4">
                    <LetterRequestFields
                        errors={errors}
                        students={students}
                        resetKey={open ? 'open' : 'closed'}
                    />
                </div>
            )}
        </FormDialog>
    );
}

function EditForm({
    open,
    onOpenChange,
    editing,
    students,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    editing: LetterRequest | null;
    students: LetterRequestStudent[];
}) {
    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Edit Surat Permohonan"
            action={editing ? update(editing.id) : ''}
            resetOnSuccess
            onSuccess={() => onOpenChange(false)}
        >
            {({ errors }) =>
                editing && (
                    <div className="grid gap-4">
                        <LetterRequestFields
                            errors={errors}
                            editing={editing}
                            students={students}
                        />
                    </div>
                )
            }
        </FormDialog>
    );
}
