import { Head, router } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useRef, useState } from 'react';
import type { PaginationState } from '@/components/data-table';
import { DataTable } from '@/components/data-table';
import { DeleteConfirmDialog } from '@/components/delete-confirm-dialog';
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 { 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 announcementIndex,
    destroy,
    store,
    update,
} from '@/routes/admin/manage/announcements';
import type {
    Announcement,
    AnnouncementDepartment,
} from '@/types/announcement';
import { formatDepartmentLabel } from '@/types/department';
import { createAnnouncementColumns } from './columns';

type Props = {
    announcements: {
        data: Announcement[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    departments: AnnouncementDepartment[];
    highlight?: number;
    filters: {
        department_id?: string;
    };
};

export default function AnnouncementIndex({
    announcements,
    departments,
    highlight,
    filters,
}: Props) {
    const [createOpen, setCreateOpen] = useState(false);
    const [editing, setEditing] = useState<Announcement | null>(null);
    const [deleting, setDeleting] = useState<Announcement | null>(null);

    const filterFields: FilterField[] = [
        {
            key: 'department_id',
            label: 'Jurusan',
            options: departments.map((department) => ({
                value: String(department.id),
                label: formatDepartmentLabel(department),
            })),
        },
    ];

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

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

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

    const columns = createAnnouncementColumns({
        handleEdit: (announcement) => setEditing(announcement),
        handleDeleteClick: (announcement) => setDeleting(announcement),
    });

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

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

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

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

                <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 AnnouncementFields({
    errors,
    editing,
    departments,
}: {
    errors: Record<string, string>;
    editing?: Announcement;
    departments: AnnouncementDepartment[];
}) {
    const hiddenDeptRef = useRef<HTMLInputElement>(null);
    const initialDeptValue = editing?.department_id
        ? String(editing.department_id)
        : '';

    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>Jurusan</Label>
                <input
                    ref={hiddenDeptRef}
                    type="hidden"
                    name="department_id"
                    defaultValue={initialDeptValue}
                />
                <Select
                    defaultValue={initialDeptValue || 'none'}
                    onValueChange={(value) => {
                        if (hiddenDeptRef.current) {
                            hiddenDeptRef.current.value =
                                value === 'none' ? '' : value;
                        }
                    }}
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Semua Jurusan" />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem value="none">Semua Jurusan</SelectItem>
                        {departments.map((department) => (
                            <SelectItem
                                key={department.id}
                                value={String(department.id)}
                            >
                                {formatDepartmentLabel(department)}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
                <InputError message={errors.department_id} />
            </div>
            <div className="grid gap-2">
                <Label htmlFor="enrollment_year">Angkatan</Label>
                <Input
                    id="enrollment_year"
                    name="enrollment_year"
                    type="number"
                    placeholder="Kosongkan untuk semua angkatan"
                    defaultValue={editing?.enrollment_year ?? ''}
                    aria-invalid={!!errors.enrollment_year}
                />
                <InputError message={errors.enrollment_year} />
            </div>
        </>
    );
}

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

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