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 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 { 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 { usePermissions } from '@/hooks/use-permissions';
import { useServerTable } from '@/hooks/use-server-table';
import {
    index as academicTermIndex,
    destroy,
    store,
    update,
    update_status,
} 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;
    filters: {
        semester?: string;
        is_active?: string;
    };
};

const filterFields: FilterField[] = [
    {
        key: 'semester',
        label: 'Semester',
        options: Object.values(Semester).map((value) => ({
            value,
            label: SemesterLabels[value],
        })),
    },
    {
        key: 'is_active',
        label: 'Status',
        options: [
            { value: 'true', label: 'Aktif' },
            { value: 'false', label: 'Tidak Aktif' },
        ],
    },
];

export default function AcademicTermIndex({
    academicTerms,
    highlight,
    filters,
}: Props) {
    const [createOpen, setCreateOpen] = useState(false);
    const [editing, setEditing] = useState<AcademicTerm | null>(null);
    const [deleting, setDeleting] = useState<AcademicTerm | null>(null);
    const { hasPermission } = usePermissions();
    const canCreate = hasPermission('create-academic-terms');
    const canUpdate = hasPermission('update-academic-terms');
    const canDelete = hasPermission('delete-academic-terms');
    const canUpdateStatus = hasPermission('update-academic-terms-status');

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

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

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

    function handleStatusChange(academicTerm: AcademicTerm, isActive: boolean) {
        router.patch(
            update_status.url(academicTerm.id),
            { is_active: isActive },
            { preserveScroll: true },
        );
    }

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

    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={
                        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}
                />

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

                <DeleteConfirmDialog
                    target={deleting}
                    onOpenChange={(open) => {
                        if (!open) {
                            setDeleting(null);
                        }
                    }}
                    title="Hapus Periode Akademik"
                    description={(academicTerm) =>
                        `Apakah Anda yakin ingin menghapus periode akademik "${academicTerm.academic_year}"? 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="academic_year">
                            Tahun Ajaran{' '}
                            <span className="text-destructive">*</span>
                        </Label>
                        <Input
                            id="academic_year"
                            name="academic_year"
                            placeholder="Masukkan tahun ajaran, contoh: 2025/2026"
                        />
                        <InputError message={errors.academic_year} />
                    </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>
                    <OpenSemestersField idPrefix="create" />
                </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-academic_year">
                                Tahun Ajaran{' '}
                                <span className="text-destructive">*</span>
                            </Label>
                            <Input
                                id="edit-academic_year"
                                name="academic_year"
                                placeholder="Masukkan tahun ajaran, contoh: 2025/2026"
                                defaultValue={editing.academic_year}
                            />
                            <InputError message={errors.academic_year} />
                        </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>
                        <OpenSemestersField
                            idPrefix="edit"
                            defaultValue={editing.open_semesters ?? []}
                        />
                    </div>
                )
            }
        </FormDialog>
    );
}

function OpenSemestersField({
    idPrefix,
    defaultValue = [],
}: {
    idPrefix: string;
    defaultValue?: number[];
}) {
    return (
        <div className="grid gap-2">
            <Label>Semester Dibuka untuk KRS</Label>
            <p className="text-xs text-muted-foreground">
                Kosongkan untuk menutup semua semester. Centang semester
                tertentu untuk membuka pendaftaran KRS pada semester itu.
            </p>
            <div className="grid grid-cols-4 gap-2">
                {[1, 2, 3, 4, 5, 6, 7, 8].map((semester) => (
                    <div key={semester} className="flex items-center gap-2">
                        <Checkbox
                            id={`${idPrefix}-open-semester-${semester}`}
                            name="open_semesters[]"
                            value={semester}
                            defaultChecked={defaultValue.includes(semester)}
                        />
                        <Label
                            htmlFor={`${idPrefix}-open-semester-${semester}`}
                            className="font-normal"
                        >
                            Semester {semester}
                        </Label>
                    </div>
                ))}
            </div>
        </div>
    );
}
