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 type { FilterField } from '@/components/filter-dialog';
import { FilterDialog } from '@/components/filter-dialog';
import { FormDialog } from '@/components/form-dialog';
import InputError from '@/components/input-error';
import { PageHeader } from '@/components/page-header';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { usePermissions } from '@/hooks/use-permissions';
import { useServerTable } from '@/hooks/use-server-table';
import {
    destroy,
    index as letterRequestIndex,
    store,
    update,
    update_status,
} from '@/routes/admin/services/letter-requests';
import type { LetterRequest } from '@/types/letter-request';
import { LetterStatuses, LetterStatusLabels } from '@/types/letter-request';
import { Head, router } from '@inertiajs/react';
import { Info, Plus } from 'lucide-react';
import { useState } from 'react';
import { createLetterRequestColumns } from './columns';

type Props = {
    letterRequests: {
        data: LetterRequest[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    highlight?: number;
    filters: {
        status?: string;
    };
};

export default function LetterRequestIndex({
    letterRequests,
    highlight,
    filters,
}: Props) {
    const [createOpen, setCreateOpen] = useState(false);
    const [editing, setEditing] = useState<LetterRequest | null>(null);
    const [deleting, setDeleting] = useState<LetterRequest | null>(null);
    const [processing, setProcessing] = useState<LetterRequest | null>(null);
    const { hasPermission } = usePermissions();
    const canCreate = hasPermission('create-letter-requests');
    const canUpdate = hasPermission('update-letter-requests');
    const canDelete = hasPermission('delete-letter-requests');
    const canProcess = hasPermission('update-letter-requests-status');

    const filterFields: FilterField[] = [
        {
            key: 'status',
            label: 'Status',
            options: LetterStatuses.map((status) => ({
                value: status,
                label: LetterStatusLabels[status],
            })),
        },
    ];

    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,
        applyFilters,
    } = useServerTable({
        route: () => letterRequestIndex.url(),
        pagination,
        filters,
    });

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

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

    function handleStatusChange(letterRequest: LetterRequest, status: string) {
        if (status === 'completed') {
            setProcessing(letterRequest);

            return;
        }

        router.patch(
            update_status.url(letterRequest.id),
            { status },
            { preserveScroll: true },
        );
    }

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

    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={
                        canCreate && (
                            <Button asChild>
                                <button
                                    type="button"
                                    onClick={() => setCreateOpen(true)}
                                >
                                    <Plus className="h-4 w-4" />
                                    Ajukan
                                </button>
                            </Button>
                        )
                    }
                />

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

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

                <ProcessForm
                    key={processing?.id}
                    open={processing !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setProcessing(null);
                        }
                    }}
                    processing={processing}
                />

                {canProcess && (
                    <Alert>
                        <Info />
                        <AlertTitle>Ubah status permohonan</AlertTitle>
                        <AlertDescription>
                            Klik badge Status pada tabel untuk mengubah status
                            permohonan secara langsung.
                        </AlertDescription>
                    </Alert>
                )}

                <DataTable
                    columns={columns}
                    data={letterRequests.data}
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                    searchKey="student"
                    toolbar={
                        <FilterDialog
                            fields={filterFields}
                            activeFilters={filters}
                            onApply={applyFilters}
                        />
                    }
                />

                <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.user?.profile?.full_name ?? 'mahasiswa ini'}"? Tindakan ini tidak dapat dibatalkan.`
                    }
                    onConfirm={handleDelete}
                />
            </div>
        </>
    );
}

function LetterRequestFields({
    errors,
    editing,
}: {
    errors: Record<string, string>;
    editing?: LetterRequest;
}) {
    return (
        <>
            <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>
        </>
    );
}

function CreateForm({
    open,
    onOpenChange,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
}) {
    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Ajukan Surat Permohonan"
            action={store()}
            resetOnSuccess
            onSuccess={() => onOpenChange(false)}
        >
            {({ errors }) => (
                <div className="grid gap-4">
                    <LetterRequestFields errors={errors} />
                </div>
            )}
        </FormDialog>
    );
}

function ProcessForm({
    open,
    onOpenChange,
    processing,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    processing: LetterRequest | null;
}) {
    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Selesaikan Surat Permohonan"
            action={processing ? update_status(processing.id) : ''}
            resetOnSuccess
            onSuccess={() => onOpenChange(false)}
        >
            {({ errors }) =>
                processing && (
                    <div className="grid gap-4">
                        <p className="text-sm text-muted-foreground">
                            Unggah dokumen hasil untuk menandai surat ini
                            sebagai selesai.
                        </p>
                        <FileUploadField
                            name="result"
                            label="Dokumen Hasil"
                            existingFileName={processing.result_name}
                            existingFileUrl={processing.result_url}
                            error={errors.result}
                        />
                    </div>
                )
            }
        </FormDialog>
    );
}

function EditForm({
    open,
    onOpenChange,
    editing,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    editing: LetterRequest | null;
}) {
    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} />
                    </div>
                )
            }
        </FormDialog>
    );
}
