import { Head, useForm, usePage } from '@inertiajs/react';
import { Pencil, Plus, Star, Trash2 } from 'lucide-react';
import { useState } from 'react';
import type { FormEvent } from 'react';
import FaqController from '@/actions/App/Http/Controllers/Admin/FaqController';
import { MissingTranslations, PublishedBadge } from '@/components/admin/badges';
import { ConfirmDialog } from '@/components/admin/confirm-dialog';
import { EmptyState } from '@/components/admin/empty-state';
import { SwitchField, TextField } from '@/components/admin/field';
import { LocaleTabs } from '@/components/admin/locale-tabs';
import { PageContainer, PageHeader } from '@/components/admin/page-header';
import { TranslatedField } from '@/components/admin/translated-field';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Spinner } from '@/components/ui/spinner';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { useEditingLocale } from '@/hooks/use-editing-locale';
import { localesWithErrors, missingLocales } from '@/lib/translations';
import type { FormErrors, Translations } from '@/types';

/** The state the dialog edits — exactly what the server validates. */
type Values = {
    question: Translations;
    answer: Translations;
    sort_order: number;
    is_featured: boolean;
    is_published: boolean;
};

type Faq = Values & {
    id: number;
    /** Languages the question or its answer is missing in. */
    missing: string[];
};

type Props = {
    faqs: Faq[];
    /** Position a new question gets unless the editor changes it. */
    nextSortOrder: number;
};

export default function FaqIndex({ faqs, nextSortOrder }: Props) {
    const { locales } = usePage().props;
    const defaultLocale =
        locales.find((locale) => locale.default) ?? locales[0];
    // The question being edited, 'new' while adding one, null when closed.
    const [editing, setEditing] = useState<Faq | 'new' | null>(null);

    return (
        <>
            <Head title="SSS" />

            <PageContainer>
                <PageHeader
                    title="Sık sorulan sorular"
                    description="SSS sayfasındaki genel sorular. Öne çıkanlar anasayfada da gösterilir. Bir soru, hem sorusu hem cevabı girilmiş olan dillerde yayınlanır."
                    actions={
                        <Button size="sm" onClick={() => setEditing('new')}>
                            <Plus />
                            Yeni soru
                        </Button>
                    }
                />

                {faqs.length === 0 ? (
                    <EmptyState
                        title="Henüz soru yok"
                        description="İlk soruyu ekleyerek SSS sayfasını oluşturun."
                        action={
                            <Button size="sm" onClick={() => setEditing('new')}>
                                <Plus />
                                Yeni soru
                            </Button>
                        }
                    />
                ) : (
                    <div className="rounded-xl border">
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead className="w-16 pl-4">
                                        Sıra
                                    </TableHead>
                                    <TableHead>Soru</TableHead>
                                    <TableHead>Öne çıkan</TableHead>
                                    <TableHead>Durum</TableHead>
                                    <TableHead className="pr-4">
                                        <span className="sr-only">
                                            İşlemler
                                        </span>
                                    </TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {faqs.map((faq) => (
                                    <TableRow key={faq.id}>
                                        <TableCell className="pl-4 text-muted-foreground tabular-nums">
                                            {faq.sort_order}
                                        </TableCell>
                                        <TableCell className="whitespace-normal">
                                            <div className="flex flex-wrap items-center gap-2">
                                                <button
                                                    type="button"
                                                    onClick={() =>
                                                        setEditing(faq)
                                                    }
                                                    className="text-left font-medium underline-offset-4 hover:underline"
                                                >
                                                    {faq.question[
                                                        defaultLocale.code
                                                    ] ?? ''}
                                                </button>
                                                <MissingTranslations
                                                    locales={faq.missing}
                                                />
                                            </div>
                                        </TableCell>
                                        <TableCell>
                                            {faq.is_featured ? (
                                                <Badge variant="outline">
                                                    <Star />
                                                    Öne çıkan
                                                </Badge>
                                            ) : (
                                                <span className="text-muted-foreground">
                                                    —
                                                </span>
                                            )}
                                        </TableCell>
                                        <TableCell>
                                            <PublishedBadge
                                                published={faq.is_published}
                                            />
                                        </TableCell>
                                        <TableCell className="pr-4">
                                            <div className="flex justify-end gap-1">
                                                <Button
                                                    variant="ghost"
                                                    size="sm"
                                                    onClick={() =>
                                                        setEditing(faq)
                                                    }
                                                >
                                                    <Pencil />
                                                    Düzenle
                                                </Button>
                                                <ConfirmDialog
                                                    action={FaqController.destroy.form(
                                                        faq.id,
                                                    )}
                                                    title="Soru silinsin mi?"
                                                    description={`“${faq.question[defaultLocale.code] ?? ''}” sorusu bütün dillerdeki cevabıyla birlikte kalıcı olarak silinir.`}
                                                >
                                                    <Button
                                                        variant="ghost"
                                                        size="sm"
                                                    >
                                                        <Trash2 />
                                                        Sil
                                                    </Button>
                                                </ConfirmDialog>
                                            </div>
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </div>
                )}
            </PageContainer>

            {/* Mounted only while open: every opening starts from fresh state. */}
            {editing !== null && (
                <FaqDialog
                    faq={editing === 'new' ? null : editing}
                    nextSortOrder={nextSortOrder}
                    blank={Object.fromEntries(
                        locales.map((locale) => [locale.code, '']),
                    )}
                    onClose={() => setEditing(null)}
                />
            )}
        </>
    );
}

type DialogProps = {
    /** The question to edit; null to add a new one. */
    faq: Faq | null;
    nextSortOrder: number;
    /** An empty translatable value: '' for every language. */
    blank: Translations;
    onClose: () => void;
};

function FaqDialog({ faq, nextSortOrder, blank, onClose }: DialogProps) {
    const { locales, defaultLocale, locale, setLocale, revealErrors } =
        useEditingLocale();

    const form = useForm<Values>({
        question: faq?.question ?? blank,
        answer: faq?.answer ?? blank,
        sort_order: faq?.sort_order ?? nextSortOrder,
        is_featured: faq?.is_featured ?? false,
        is_published: faq?.is_published ?? true,
    });
    const { data } = form;
    const errors: FormErrors = form.errors;

    const set = <K extends keyof Values>(key: K, value: Values[K]): void => {
        form.setData((current) => ({ ...current, [key]: value }));
    };

    const submit = (event: FormEvent<HTMLFormElement>): void => {
        event.preventDefault();

        form.submit(
            faq === null ? FaqController.store() : FaqController.update(faq.id),
            {
                preserveScroll: true,
                onSuccess: onClose,
                onError: revealErrors,
            },
        );
    };

    return (
        <Dialog
            open
            onOpenChange={(open) => {
                if (!open) {
                    onClose();
                }
            }}
        >
            <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-2xl">
                <form
                    onSubmit={submit}
                    noValidate
                    className="grid grid-cols-1 gap-6"
                >
                    <DialogHeader>
                        <DialogTitle>
                            {faq === null ? 'Yeni soru' : 'Soruyu düzenle'}
                        </DialogTitle>
                        <DialogDescription>
                            Soru ve cevap her dil için ayrı yazılır.{' '}
                            {defaultLocale.name} zorunludur; diğer dillerde
                            ikisi birlikte girilir ya da ikisi de boş bırakılır.
                        </DialogDescription>
                    </DialogHeader>

                    <LocaleTabs
                        locales={locales}
                        value={locale.code}
                        onChange={setLocale}
                        missing={missingLocales(
                            locales,
                            data.question,
                            data.answer,
                        )}
                        invalid={localesWithErrors(locales, errors)}
                    />

                    <TranslatedField
                        name="question"
                        label="Soru"
                        locale={locale}
                        value={data.question}
                        onChange={(value) => set('question', value)}
                        errors={errors}
                        required
                    />

                    <TranslatedField
                        name="answer"
                        label="Cevap"
                        locale={locale}
                        value={data.answer}
                        onChange={(value) => set('answer', value)}
                        errors={errors}
                        rows={6}
                        required
                    />

                    <div className="grid grid-cols-1 items-start gap-6 sm:grid-cols-3">
                        <TextField
                            id="faq-sort-order"
                            label="Sıra"
                            type="number"
                            min={0}
                            inputMode="numeric"
                            value={String(data.sort_order)}
                            onChange={(value) =>
                                set('sort_order', Number(value) || 0)
                            }
                            error={errors.sort_order}
                        />
                        <div className="grid grid-cols-1 gap-4 sm:col-span-2">
                            <SwitchField
                                id="faq-published"
                                label="Yayında"
                                checked={data.is_published}
                                onChange={(published) =>
                                    set('is_published', published)
                                }
                                error={errors.is_published}
                            />
                            <SwitchField
                                id="faq-featured"
                                label="Öne çıkar"
                                checked={data.is_featured}
                                onChange={(featured) =>
                                    set('is_featured', featured)
                                }
                                error={errors.is_featured}
                                hint="Öne çıkan sorular anasayfada da gösterilir."
                            />
                        </div>
                    </div>

                    <DialogFooter>
                        <Button
                            type="button"
                            variant="outline"
                            onClick={onClose}
                        >
                            Vazgeç
                        </Button>
                        <Button type="submit" disabled={form.processing}>
                            {form.processing && <Spinner />}
                            {faq === null ? 'Soruyu ekle' : 'Kaydet'}
                        </Button>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    );
}

FaqIndex.layout = {
    breadcrumbs: [
        {
            title: 'SSS',
            href: FaqController.index(),
        },
    ],
};
