import { Head, router } from '@inertiajs/react';
import { format } from 'date-fns';
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 { FormDialog } from '@/components/form-dialog';
import InputError from '@/components/input-error';
import { PageHeader } from '@/components/page-header';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
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 {
    index as announcementIndex,
    destroy,
    store,
    update,
} from '@/routes/admin/manage/announcements';
import type { Announcement } from '@/types/announcement';
import {
    AnnouncementTargetRoleLabels,
    AnnouncementTargetRoles,
} from '@/types/announcement';
import { createAnnouncementColumns } from './columns';

type Props = {
    announcements: {
        data: Announcement[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    highlight?: number;
};

export default function AnnouncementIndex({
    announcements,
    highlight,
}: Props) {
    const [createOpen, setCreateOpen] = useState(false);
    const [editing, setEditing] = useState<Announcement | null>(null);
    const [deleting, setDeleting] = useState<Announcement | null>(null);
    const [viewing, setViewing] = useState<Announcement | null>(null);
    const { hasPermission } = usePermissions();
    const canCreate = hasPermission('create-announcements');
    const canUpdate = hasPermission('update-announcements');
    const canDelete = hasPermission('delete-announcements');

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

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

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

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

    const columns = createAnnouncementColumns({
        handleView: (announcement) => setViewing(announcement),
        handleEdit: (announcement) => setEditing(announcement),
        handleDeleteClick: (announcement) => setDeleting(announcement),
        canUpdate,
        canDelete,
        showTargetRoles: canCreate || canUpdate,
    });

    return (
        <>
            <Head title="Pengumuman" />

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

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

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

                <ViewDetailDialog
                    open={viewing !== null}
                    showTargetRoles={canCreate || canUpdate}
                    onOpenChange={(open) => {
                        if (!open) {
                            setViewing(null);
                        }
                    }}
                    announcement={viewing}
                />

                <DataTable
                    columns={columns}
                    data={announcements.data}
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                    searchKey="title"
                />

                <DeleteConfirmDialog
                    target={deleting}
                    onOpenChange={(open) => {
                        if (!open) {
                            setDeleting(null);
                        }
                    }}
                    title="Hapus Pengumuman"
                    description={(announcement) =>
                        `Apakah Anda yakin ingin menghapus pengumuman "${announcement.title}"? Tindakan ini tidak dapat dibatalkan.`
                    }
                    onConfirm={handleDelete}
                />
            </div>
        </>
    );
}

function ViewDetailDialog({
    open,
    onOpenChange,
    announcement,
    showTargetRoles,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    announcement: Announcement | null;
    showTargetRoles: boolean;
}) {
    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="flex max-h-[85vh] flex-col overflow-hidden sm:max-w-lg">
                <DialogHeader className="shrink-0">
                    <DialogTitle>Detail Pengumuman</DialogTitle>
                </DialogHeader>

                {announcement && (
                    <div className="grid min-h-0 flex-1 gap-4 overflow-x-hidden overflow-y-auto">
                        <span className="text-xs text-muted-foreground">
                            Dibuat oleh{' '}
                            {announcement.creator?.profile?.full_name ?? '-'}{' '}
                            &middot;{' '}
                            {format(
                                new Date(announcement.created_at),
                                'd MMM yyyy, HH:mm',
                            )}
                        </span>

                        {showTargetRoles && (
                            <div className="grid gap-1">
                                <Label className="text-muted-foreground">
                                    Ditujukan Untuk
                                </Label>
                                <div className="flex flex-wrap gap-1">
                                    {announcement.target_roles.map((role) => (
                                        <Badge key={role} variant="secondary">
                                            {AnnouncementTargetRoleLabels[role]}
                                        </Badge>
                                    ))}
                                </div>
                            </div>
                        )}

                        <div className="grid gap-1">
                            <Label className="text-muted-foreground">
                                Judul
                            </Label>
                            <p className="font-medium">
                                {announcement.title}
                            </p>
                        </div>

                        <div className="grid gap-1">
                            <Label className="text-muted-foreground">
                                Isi
                            </Label>
                            <p className="whitespace-pre-line">
                                {announcement.content}
                            </p>
                        </div>
                    </div>
                )}
            </DialogContent>
        </Dialog>
    );
}

function AnnouncementFields({
    errors,
    editing,
}: {
    errors: Record<string, string>;
    editing?: Announcement;
}) {
    return (
        <>
            <div className="grid gap-2">
                <Label htmlFor="title">
                    Judul <span className="text-destructive">*</span>
                </Label>
                <Input
                    id="title"
                    name="title"
                    placeholder="Judul pengumuman"
                    defaultValue={editing?.title ?? ''}
                    aria-invalid={!!errors.title}
                />
                <InputError message={errors.title} />
            </div>
            <div className="grid gap-2">
                <Label htmlFor="content">
                    Isi <span className="text-destructive">*</span>
                </Label>
                <Textarea
                    id="content"
                    name="content"
                    placeholder="Isi pengumuman"
                    defaultValue={editing?.content ?? ''}
                    aria-invalid={!!errors.content}
                />
                <InputError message={errors.content} />
            </div>
            <div className="grid gap-2">
                <Label>
                    Ditujukan Untuk{' '}
                    <span className="text-destructive">*</span>
                </Label>
                <div className="flex flex-wrap gap-4">
                    {AnnouncementTargetRoles.map((role) => (
                        <div key={role} className="flex items-center gap-2">
                            <Checkbox
                                id={`target-role-${role}`}
                                name="target_roles[]"
                                value={role}
                                defaultChecked={editing?.target_roles.includes(
                                    role,
                                )}
                            />
                            <Label
                                htmlFor={`target-role-${role}`}
                                className="font-normal"
                            >
                                {AnnouncementTargetRoleLabels[role]}
                            </Label>
                        </div>
                    ))}
                </div>
                <InputError message={errors.target_roles} />
            </div>
        </>
    );
}

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

function EditForm({
    open,
    onOpenChange,
    editing,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    editing: Announcement | null;
}) {
    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Edit Pengumuman"
            action={editing ? update(editing.id) : ''}
            resetOnSuccess
            onSuccess={() => onOpenChange(false)}
        >
            {({ errors }) =>
                editing && (
                    <div className="grid gap-4">
                        <AnnouncementFields
                            errors={errors}
                            editing={editing}
                        />
                    </div>
                )
            }
        </FormDialog>
    );
}
