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 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 { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { usePermissions } from '@/hooks/use-permissions';
import { useServerTable } from '@/hooks/use-server-table';
import { richTextContentClass } from '@/lib/rich-text-content';
import { cn } from '@/lib/utils';
import {
    index as feedbackIndex,
    destroy,
    store,
    update,
    update_status,
} from '@/routes/admin/feedback';
import type { Feedback } from '@/types/feedback';
import { FeedbackStatusLabels, FeedbackTypeLabels } from '@/types/feedback';
import { createFeedbackColumns, FeedbackStatusVariants } 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 [viewing, setViewing] = useState<Feedback | null>(null);
    const { hasPermission } = usePermissions();
    const canCreate = hasPermission('create-feedback');
    const canUpdate = hasPermission('update-feedback');
    const canDelete = hasPermission('delete-feedback');
    const canUpdateStatus = hasPermission('update-feedback-status');

    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),
        });
    }

    function handleStatusChange(feedback: Feedback, status: string) {
        router.patch(
            update_status.url(feedback.id),
            { status },
            { preserveScroll: true },
        );
    }

    const columns = createFeedbackColumns({
        handleView: (feedback) => setViewing(feedback),
        handleEdit: (feedback) => setEditing(feedback),
        handleDeleteClick: (feedback) => setDeleting(feedback),
        handleStatusChange,
        statuses,
        canUpdateStatus,
        canUpdate,
        canDelete,
    });

    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"
                    actions={
                        canCreate && (
                            <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}
                />

                <ViewDetailDialog
                    open={viewing !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setViewing(null);
                        }
                    }}
                    feedback={viewing}
                />

                <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)}
            contentClassName="sm:max-w-4xl"
        >
            {({ 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)}
            contentClassName="sm:max-w-2xl"
        >
            {({ errors }) =>
                editing && (
                    <div className="grid gap-4">
                        <FeedbackFields
                            errors={errors}
                            editing={editing}
                            types={types}
                        />
                    </div>
                )
            }
        </FormDialog>
    );
}

function ViewDetailDialog({
    open,
    onOpenChange,
    feedback,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    feedback: Feedback | null;
}) {
    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="flex max-h-[85vh] flex-col overflow-hidden sm:max-w-3xl">
                <DialogHeader className="shrink-0">
                    <DialogTitle>Detail Kritik dan Saran</DialogTitle>
                </DialogHeader>

                {feedback && (
                    <div className="grid min-h-0 flex-1 gap-4 overflow-y-auto">
                        <div className="flex flex-wrap items-center gap-2">
                            <Badge variant="outline">
                                {FeedbackTypeLabels[feedback.type]}
                            </Badge>
                            <Badge
                                variant={
                                    FeedbackStatusVariants[feedback.status]
                                }
                            >
                                {FeedbackStatusLabels[feedback.status]}
                            </Badge>
                            <span className="text-xs text-muted-foreground">
                                Dikirim{' '}
                                {format(
                                    new Date(feedback.created_at),
                                    'd MMM yyyy, HH:mm',
                                )}
                            </span>
                        </div>

                        <div className="grid gap-1">
                            <Label className="text-muted-foreground">
                                Subjek
                            </Label>
                            <p className="font-medium">{feedback.subject}</p>
                        </div>

                        <div className="grid gap-1">
                            <Label className="text-muted-foreground">
                                Dibuat Oleh
                            </Label>
                            <p>{feedback.user?.profile?.full_name ?? '-'}</p>
                        </div>

                        <div className="grid gap-1">
                            <Label className="text-muted-foreground">
                                Ditindaklanjuti Oleh
                            </Label>
                            <p>
                                {feedback.handler?.profile?.full_name ??
                                    'Belum ditindaklanjuti'}
                            </p>
                        </div>

                        <div className="grid gap-1">
                            <Label className="text-muted-foreground">
                                Pesan
                            </Label>
                            <div
                                className={cn(
                                    'rounded-md border p-3 text-sm',
                                    richTextContentClass,
                                )}
                                dangerouslySetInnerHTML={{
                                    __html: feedback.message,
                                }}
                            />
                        </div>

                        {feedback.admin_notes && (
                            <div className="grid gap-1">
                                <Label className="text-muted-foreground">
                                    Catatan Admin
                                </Label>
                                <p className="rounded-md border bg-muted/50 p-3 text-sm whitespace-pre-line">
                                    {feedback.admin_notes}
                                </p>
                            </div>
                        )}
                    </div>
                )}
            </DialogContent>
        </Dialog>
    );
}
