import { Form, Head } from '@inertiajs/react';
import { ArrowRight, Plus, Trash2 } from 'lucide-react';
import RedirectController from '@/actions/App/Http/Controllers/Admin/RedirectController';
import { ConfirmDialog } from '@/components/admin/confirm-dialog';
import { EmptyState } from '@/components/admin/empty-state';
import { FormSection } from '@/components/admin/form-section';
import { PageContainer, PageHeader } from '@/components/admin/page-header';
import { Pagination } from '@/components/admin/pagination';
import InputError from '@/components/input-error';
import { Badge } from '@/components/ui/badge';
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 { Spinner } from '@/components/ui/spinner';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import type { Paginated } from '@/types';

type Redirect = {
    id: number;
    fromPath: string;
    toPath: string;
    statusCode: number;
    hits: number;
    lastHitAt: string | null;
};

type Props = {
    redirects: Paginated<Redirect>;
};

export default function RedirectIndex({ redirects }: Props) {
    return (
        <>
            <Head title="Yönlendirmeler" />

            <PageContainer>
                <PageHeader
                    title="Yönlendirmeler"
                    description="Artık var olmayan bir adrese gelen ziyaretçiyi yeni adrese gönderir. Yayındaki bir işlemin ya da kategorinin adres uzantısı değiştiğinde yönlendirme buraya kendiliğinden eklenir."
                />

                <FormSection
                    title="Yeni yönlendirme"
                    description="Yalnızca site içi yolları yazın (alan adı olmadan). Yönlendirme, eski adreste artık bir sayfa bulunmadığında çalışır."
                >
                    <Form
                        {...RedirectController.store.form()}
                        options={{ preserveScroll: true }}
                        resetOnSuccess={['from_path', 'to_path']}
                        className="grid grid-cols-1 items-start gap-4 lg:grid-cols-[1fr_1fr_12rem_auto]"
                    >
                        {({ processing, errors }) => (
                            <>
                                <div className="grid grid-cols-1 gap-2">
                                    <Label htmlFor="from_path">
                                        Eski adres
                                    </Label>
                                    <Input
                                        id="from_path"
                                        name="from_path"
                                        placeholder="/eski-sayfa"
                                        autoComplete="off"
                                        spellCheck={false}
                                        className="font-mono"
                                        aria-invalid={
                                            errors.from_path ? true : undefined
                                        }
                                    />
                                    <InputError message={errors.from_path} />
                                </div>

                                <div className="grid grid-cols-1 gap-2">
                                    <Label htmlFor="to_path">Yeni adres</Label>
                                    <Input
                                        id="to_path"
                                        name="to_path"
                                        placeholder="/yeni-sayfa"
                                        autoComplete="off"
                                        spellCheck={false}
                                        className="font-mono"
                                        aria-invalid={
                                            errors.to_path ? true : undefined
                                        }
                                    />
                                    <InputError message={errors.to_path} />
                                </div>

                                <div className="grid grid-cols-1 gap-2">
                                    <Label htmlFor="status_code">Tür</Label>
                                    <Select
                                        name="status_code"
                                        defaultValue="301"
                                    >
                                        <SelectTrigger
                                            id="status_code"
                                            className="w-full"
                                        >
                                            <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="301">
                                                301 · Kalıcı
                                            </SelectItem>
                                            <SelectItem value="302">
                                                302 · Geçici
                                            </SelectItem>
                                        </SelectContent>
                                    </Select>
                                    <InputError message={errors.status_code} />
                                </div>

                                <Button
                                    disabled={processing}
                                    className="lg:mt-[1.375rem]"
                                >
                                    {processing ? <Spinner /> : <Plus />}
                                    Ekle
                                </Button>
                            </>
                        )}
                    </Form>
                </FormSection>

                {redirects.data.length === 0 ? (
                    <EmptyState
                        title="Henüz yönlendirme yok"
                        description="Adres değişikliklerinde eski adresler burada listelenir."
                    />
                ) : (
                    <div className="rounded-xl border">
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead className="pl-4">
                                        Eski adres
                                    </TableHead>
                                    <TableHead>Yeni adres</TableHead>
                                    <TableHead>Tür</TableHead>
                                    <TableHead className="text-right">
                                        Kullanım
                                    </TableHead>
                                    <TableHead>Son kullanım</TableHead>
                                    <TableHead className="pr-4">
                                        <span className="sr-only">
                                            İşlemler
                                        </span>
                                    </TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {redirects.data.map((redirect) => (
                                    <TableRow key={redirect.id}>
                                        <TableCell className="pl-4 font-mono text-xs break-all whitespace-normal">
                                            {redirect.fromPath}
                                        </TableCell>
                                        <TableCell className="font-mono text-xs break-all whitespace-normal">
                                            <span className="flex items-center gap-2">
                                                <ArrowRight
                                                    aria-hidden="true"
                                                    className="size-3.5 shrink-0 text-muted-foreground"
                                                />
                                                {redirect.toPath}
                                            </span>
                                        </TableCell>
                                        <TableCell>
                                            <Badge
                                                variant={
                                                    redirect.statusCode === 301
                                                        ? 'secondary'
                                                        : 'outline'
                                                }
                                            >
                                                {redirect.statusCode}
                                            </Badge>
                                        </TableCell>
                                        <TableCell className="text-right tabular-nums">
                                            {redirect.hits}
                                        </TableCell>
                                        <TableCell className="whitespace-nowrap text-muted-foreground tabular-nums">
                                            {redirect.lastHitAt ?? '—'}
                                        </TableCell>
                                        <TableCell className="pr-4 text-right">
                                            <ConfirmDialog
                                                action={RedirectController.destroy.form(
                                                    redirect.id,
                                                )}
                                                title="Yönlendirme silinsin mi?"
                                                description={`${redirect.fromPath} adresine gelen ziyaretçiler artık yönlendirilmez ve “sayfa bulunamadı” hatası görür.`}
                                            >
                                                <Button
                                                    variant="ghost"
                                                    size="sm"
                                                >
                                                    <Trash2 />
                                                    Sil
                                                </Button>
                                            </ConfirmDialog>
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </div>
                )}

                <Pagination paginator={redirects} />
            </PageContainer>
        </>
    );
}

RedirectIndex.layout = {
    breadcrumbs: [
        {
            title: 'Yönlendirmeler',
            href: RedirectController.index(),
        },
    ],
};
