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 { 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 TiptapEditor from '@/components/rich-text-editor';
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 { useServerTable } from '@/hooks/use-server-table';
import {
    index as feedbackIndex,
    destroy,
    store,
    update,
} from '@/routes/admin/feedback';
import type { Feedback } from '@/types/feedback';
import { createFeedbackColumns } from './columns';

type FeedbackTypeOption = { value: string; label: string };

type Props = {
    feedbacks: {
        data: Feedback[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    types: FeedbackTypeOption[];
    statuses: FeedbackTypeOption[];
    filters: {
        type?: string;
        status?: string;
    };
};

export default function FeedbackIndex({
    feedbacks,
    types,
    statuses,
    filters,
}: Props) {
    const [createOpen, setCreateOpen] = useState(false);
    const [editing, setEditing] = useState<Feedback | null>(null);
    const [deleting, setDeleting] = useState<Feedback | null>(null);

    const filterFields: FilterField[] = [
        {
            key: 'type',
            label: 'Jenis',
            options: types,
        },
        {
            key: 'status',
            label: 'Status',
            options: statuses,
        },
    ];

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

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

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

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

    const columns = createFeedbackColumns({
        handleEdit: (feedback) => setEditing(feedback),
        handleDeleteClick: (feedback) => setDeleting(feedback),
    });

    return (
        <>
            <Head title="Kritik dan Saran" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Kritik dan Saran"
                    description={
                        <p className="mt-1 text-sm text-muted-foreground">
                            Sampaikan kritik, saran, atau aduan Anda kepada
                            kami.
                        </p>
                    }
                    actions={
                        <Button asChild>
                            <button
                                type="button"
                                onClick={() => setCreateOpen(true)}
                            >
                                <Plus className="h-4 w-4" />
                                Tambah
                            </button>
                        </Button>
                    }
                />

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

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

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

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

function FeedbackFields({
    errors,
    editing,
    types,
}: {
    errors: Record<string, string>;
    editing?: Feedback;
    types: FeedbackTypeOption[];
}) {
    const [message, setMessage] = useState(editing?.message ?? '');

    return (
        <>
            <div className="grid gap-2">
                <Label>
                    Jenis <span className="text-destructive">*</span>
                </Label>
                {!editing && <input type="hidden" name="type" />}
                <Select name="type" defaultValue={editing?.type ?? 'kritik'}>
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Pilih jenis" />
                    </SelectTrigger>
                    <SelectContent>
                        {types.map((type) => (
                            <SelectItem key={type.value} value={type.value}>
                                {type.label}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
                <InputError message={errors.type} />
            </div>
            <div className="grid gap-2">
                <Label htmlFor={editing ? 'edit-subject' : 'subject'}>
                    Subjek <span className="text-destructive">*</span>
                </Label>
                <Input
                    id={editing ? 'edit-subject' : 'subject'}
                    name="subject"
                    placeholder="Ringkasan singkat"
                    defaultValue={editing?.subject ?? ''}
                />
                <InputError message={errors.subject} />
            </div>
            <div className="grid gap-2">
                <Label>
                    Pesan <span className="text-destructive">*</span>
                </Label>
                <TiptapEditor
                    name="message"
                    value={message}
                    onChange={setMessage}
                    placeholder="Jelaskan kritik, saran, atau aduan Anda secara rinci"
                    error={errors.message}
                />
            </div>
        </>
    );
}

function CreateForm({
    open,
    onOpenChange,
    types,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    types: FeedbackTypeOption[];
}) {
    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Tambah Kritik dan Saran"
            action={store()}
            resetOnSuccess
            onSuccess={() => onOpenChange(false)}
        >
            {({ errors }) => (
                <div className="grid gap-4">
                    <FeedbackFields errors={errors} types={types} />
                </div>
            )}
        </FormDialog>
    );
}

function EditForm({
    open,
    onOpenChange,
    editing,
    types,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    editing: Feedback | null;
    types: FeedbackTypeOption[];
}) {
    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Edit Kritik dan Saran"
            action={editing ? update(editing.id) : ''}
            resetOnSuccess
            onSuccess={() => onOpenChange(false)}
        >
            {({ errors }) =>
                editing && (
                    <div className="grid gap-4">
                        <FeedbackFields
                            errors={errors}
                            editing={editing}
                            types={types}
                        />
                    </div>
                )
            }
        </FormDialog>
    );
}
