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 { DatePicker } from '@/components/date-picker';
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 { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { useServerTable } from '@/hooks/use-server-table';
import {
    index as academicTermIndex,
    destroy,
    store,
    update,
} from '@/routes/admin/master/academic-terms';
import type { AcademicTerm } from '@/types/academic-term';
import { Semester, SemesterLabels } from '@/types/academic-term';
import { createAcademicTermColumns } from './columns';

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

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

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

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

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

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

    const columns = createAcademicTermColumns({
        handleEdit: (academicTerm) => setEditing(academicTerm),
        handleDeleteClick: (academicTerm) => setDeleting(academicTerm),
    });

    return (
        <>
            <Head title="Periode Akademik" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Periode Akademik"
                    description={
                        highlight && (
                            <p className="mt-1 text-sm text-muted-foreground">
                                Menampilkan periode akademik dari notifikasi.
                                <button
                                    onClick={() => {
                                        router.get(
                                            academicTermIndex.url(),
                                            {},
                                            {
                                                replace: true,
                                                preserveState: true,
                                            },
                                        );
                                    }}
                                    className="ml-1 text-primary underline underline-offset-4 hover:text-primary/80"
                                >
                                    Tampilkan semua
                                </button>
                            </p>
                        )
                    }
                    actions={
                        <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}
                />

                <DataTable
                    columns={columns}
                    data={academicTerms.data}
                    searchKey="name"
                    searchPlaceholder="Cari periode akademik..."
                    emptyText="Belum ada data periode akademik."
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                />

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

function CreateForm({
    open,
    onOpenChange,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
}) {
    const [startDate, setStartDate] = useState<Date | undefined>();
    const [endDate, setEndDate] = useState<Date | undefined>();

    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Tambah Periode Akademik"
            action={store()}
            resetOnSuccess
            onSuccess={() => {
                onOpenChange(false);
                setStartDate(undefined);
                setEndDate(undefined);
            }}
        >
            {({ errors }) => (
                <div className="grid gap-4">
                    <div className="grid gap-2">
                        <Label htmlFor="name">
                            Nama <span className="text-destructive">*</span>
                        </Label>
                        <Input
                            id="name"
                            name="name"
                            placeholder="Masukkan nama periode akademik"
                        />
                        <InputError message={errors.name} />
                    </div>
                    <div className="grid gap-2">
                        <Label>
                            Semester <span className="text-destructive">*</span>
                        </Label>
                        <RadioGroup
                            name="semester"
                            defaultValue=""
                            className="flex flex-row gap-4"
                        >
                            {Object.values(Semester).map((value) => (
                                <div key={value} className="flex items-center gap-2">
                                    <RadioGroupItem value={value} id={`create-${value}`} />
                                    <Label htmlFor={`create-${value}`} className="font-normal">
                                        {SemesterLabels[value]}
                                    </Label>
                                </div>
                            ))}
                        </RadioGroup>
                        <InputError message={errors.semester} />
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                        <div className="grid gap-2">
                            <Label>
                                Tanggal Mulai <span className="text-destructive">*</span>
                            </Label>
                            <input type="hidden" name="start_date" value={startDate ? startDate.toISOString().split('T')[0] : ''} />
                            <DatePicker
                                value={startDate}
                                onChange={setStartDate}
                                placeholder="Pilih tanggal mulai"
                            />
                            <InputError message={errors.start_date} />
                        </div>
                        <div className="grid gap-2">
                            <Label>Tanggal Selesai <span className="text-destructive">*</span></Label>
                            <input type="hidden" name="end_date" value={endDate ? endDate.toISOString().split('T')[0] : ''} />
                            <DatePicker
                                value={endDate}
                                onChange={setEndDate}
                                placeholder="Pilih tanggal selesai"
                            />
                            <InputError message={errors.end_date} />
                        </div>
                    </div>
                    <div className="flex items-center gap-2">
                        <input type="hidden" name="is_active" value="0" />
                        <Checkbox id="is_active" name="is_active" value="1" />
                        <Label htmlFor="is_active">Aktif</Label>
                    </div>
                </div>
            )}
        </FormDialog>
    );
}

function EditForm({
    open,
    onOpenChange,
    editing,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    editing: AcademicTerm | null;
}) {
    const [startDate, setStartDate] = useState<Date | undefined>(
        editing?.start_date ? new Date(editing.start_date) : undefined,
    );
    const [endDate, setEndDate] = useState<Date | undefined>(
        editing?.end_date ? new Date(editing.end_date) : undefined,
    );

    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Edit Periode Akademik"
            action={editing ? update(editing.id) : ''}
            resetOnSuccess
            onSuccess={() => {
                onOpenChange(false);
                setStartDate(undefined);
                setEndDate(undefined);
            }}
        >
            {({ errors }) =>
                editing && (
                    <div className="grid gap-4">
                        <div className="grid gap-2">
                            <Label htmlFor="edit-name">
                                Nama{' '}
                                <span className="text-destructive">*</span>
                            </Label>
                            <Input
                                id="edit-name"
                                name="name"
                                placeholder="Masukkan nama periode akademik"
                                defaultValue={editing.name}
                            />
                            <InputError message={errors.name} />
                        </div>
                        <div className="grid gap-2">
                            <Label>
                                Semester <span className="text-destructive">*</span>
                            </Label>
                            <RadioGroup
                                name="semester"
                                defaultValue={editing.semester}
                                className="flex flex-row gap-4"
                            >
                                {Object.values(Semester).map((value) => (
                                    <div key={value} className="flex items-center gap-2">
                                        <RadioGroupItem value={value} id={`edit-${value}`} />
                                        <Label htmlFor={`edit-${value}`} className="font-normal">
                                            {SemesterLabels[value]}
                                        </Label>
                                    </div>
                                ))}
                            </RadioGroup>
                            <InputError message={errors.semester} />
                        </div>
                        <div className="grid grid-cols-2 gap-4">
                            <div className="grid gap-2">
                                <Label>Tanggal Mulai <span className="text-destructive">*</span></Label>
                                <input type="hidden" name="start_date" value={startDate ? startDate.toISOString().split('T')[0] : ''} />
                                <DatePicker
                                    value={startDate}
                                    onChange={setStartDate}
                                    placeholder="Pilih tanggal mulai"
                                />
                                <InputError message={errors.start_date} />
                            </div>
                            <div className="grid gap-2">
                                <Label>Tanggal Selesai <span className="text-destructive">*</span></Label>
                                <input type="hidden" name="end_date" value={endDate ? endDate.toISOString().split('T')[0] : ''} />
                                <DatePicker
                                    value={endDate}
                                    onChange={setEndDate}
                                    placeholder="Pilih tanggal selesai"
                                />
                                <InputError message={errors.end_date} />
                            </div>
                        </div>
                        <div className="flex items-center gap-2">
                            <input type="hidden" name="is_active" value="0" />
                            <Checkbox
                                id="edit-is_active"
                                name="is_active"
                                value="1"
                                defaultChecked={editing.is_active}
                            />
                            <Label htmlFor="edit-is_active">Aktif</Label>
                        </div>
                    </div>
                )
            }
        </FormDialog>
    );
}
