import { useState, useMemo, useEffect } from "react";
import AppLayout from "@/Layouts/AppLayout";
import { Head, Link, router, usePage } from "@inertiajs/react";
import { toast } from "sonner";
import {
    Plus,
    Pencil,
    Trash2,
    Search,
    ChevronLeft,
    ChevronRight,
    FileText,
    Layers,
    Link2,
} from "lucide-react";
import PageHeader from "@/Components/PageHeader";
import { Settings } from "lucide-react";
import { Button } from "@/Components/ui/button";
import { Badge } from "@/Components/ui/badge";
import { Input } from "@/Components/ui/input";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/Components/ui/select";
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/Components/ui/table";
import SortableHead from "@/Components/ui/sortable-head";
import useTableSort from "@/hooks/useTableSort";
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
    AlertDialogTrigger,
} from "@/Components/ui/alert-dialog";

const ITEMS_PER_PAGE = 10;

const STATUS_VARIANT = {
    active: "default",
    inactive: "secondary",
    blocked: "outline",
};

export default function Index({ templates, tabs, statuses }) {
    const { flash } = usePage().props;
    const [search, setSearch] = useState("");

    useEffect(() => {
        if (flash?.success) toast.success(flash.success);
        if (flash?.error) toast.error(flash.error);
    }, [flash?.success, flash?.error]);
    const [tabFilter, setTabFilter] = useState("all");
    const [statusFilter, setStatusFilter] = useState("all");
    const [page, setPage] = useState(1);

    const filtered = useMemo(() => {
        setPage(1);
        return templates.filter((t) => {
            const matchSearch = t.name
                .toLowerCase()
                .includes(search.toLowerCase());
            const matchTab = tabFilter === "all" || t.tab === tabFilter;
            const matchStatus =
                statusFilter === "all" || t.status === statusFilter;
            return matchSearch && matchTab && matchStatus;
        });
    }, [templates, search, tabFilter, statusFilter]);

    const { sortedData, sortField, sortDir, handleSort } = useTableSort(filtered, {
        accessors: {
            tab: "tab_label",
            status: "status_label",
            blocks: "enabled_blocks_count",
            usage: "usage_count",
        },
    });

    const totalPages = Math.max(
        1,
        Math.ceil(sortedData.length / ITEMS_PER_PAGE)
    );
    const currentPage = Math.min(page, totalPages);
    const paginated = sortedData.slice(
        (currentPage - 1) * ITEMS_PER_PAGE,
        currentPage * ITEMS_PER_PAGE
    );

    function handleDelete(id) {
        router.delete(route("templates.destroy", id), {
            preserveScroll: true,
        });
    }

    return (
        <AppLayout>
            <Head title="Templates" />

            <div className="mx-auto flex w-full max-w-[1200px] flex-col gap-4">
                <PageHeader
                    title="Templates"
                    breadcrumb={[{ label: "Configurações", href: "configuracoes.index", icon: Settings }]}
                >
                    <Button asChild className="w-full sm:w-auto">
                        <Link href={route("templates.create")}>
                            <Plus />
                            Novo Template
                        </Link>
                    </Button>
                </PageHeader>
            {/* Filters */}
            <div className="flex flex-col sm:flex-row gap-2">
                <div className="relative flex-1 sm:flex-none">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
                    <Input
                        placeholder="Buscar por nome..."
                        value={search}
                        onChange={(e) => setSearch(e.target.value)}
                        className="pl-9 w-full sm:w-56"
                    />
                </div>

                <Select value={tabFilter} onValueChange={setTabFilter}>
                    <SelectTrigger className="w-full sm:w-44">
                        <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem value="all">Todas as abas</SelectItem>
                        {Object.entries(tabs).map(([key, label]) => (
                            <SelectItem key={key} value={key}>
                                {label}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>

                <Select value={statusFilter} onValueChange={setStatusFilter}>
                    <SelectTrigger className="w-full sm:w-40">
                        <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem value="all">Todos status</SelectItem>
                        {Object.entries(statuses).map(([key, label]) => (
                            <SelectItem key={key} value={key}>
                                {label}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
            </div>

            {/* Table */}
            <div className="rounded-md border">
                <Table>
                    <TableHeader>
                        <TableRow>
                            <SortableHead field="name" sortField={sortField} sortDir={sortDir} onSort={handleSort}>Nome</SortableHead>
                            <SortableHead field="tab" sortField={sortField} sortDir={sortDir} onSort={handleSort}>Aba</SortableHead>
                            <SortableHead field="status" sortField={sortField} sortDir={sortDir} onSort={handleSort} className="hidden sm:table-cell">Status</SortableHead>
                            <SortableHead field="blocks" sortField={sortField} sortDir={sortDir} onSort={handleSort} className="hidden sm:table-cell">Blocos</SortableHead>
                            <SortableHead field="usage" sortField={sortField} sortDir={sortDir} onSort={handleSort} className="hidden md:table-cell">Uso</SortableHead>
                            <TableHead className="w-[96px]" />
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {paginated.length === 0 ? (
                            <TableRow>
                                <TableCell
                                    colSpan={6}
                                    className="h-48 text-center"
                                >
                                    <div className="flex flex-col items-center gap-2 text-muted-foreground">
                                        <Layers className="h-8 w-8" />
                                        <span className="text-sm">
                                            {templates.length === 0
                                                ? "Nenhum template cadastrado."
                                                : "Nenhum template encontrado para os filtros aplicados."}
                                        </span>
                                    </div>
                                </TableCell>
                            </TableRow>
                        ) : (
                            paginated.map((template) => (
                                <TableRow key={template.id}>
                                    <TableCell className="font-medium">
                                        <div className="flex items-center gap-2">
                                            <FileText className="h-4 w-4 text-muted-foreground shrink-0" />
                                            <span>{template.name}</span>
                                            {template.is_default && (
                                                <Badge
                                                    variant="outline"
                                                    className="text-[10px]"
                                                >
                                                    Padrão
                                                </Badge>
                                            )}
                                        </div>
                                    </TableCell>
                                    <TableCell>
                                        <Badge variant="secondary">
                                            {template.tab_label}
                                        </Badge>
                                    </TableCell>
                                    <TableCell className="hidden sm:table-cell">
                                        <Badge
                                            variant={
                                                STATUS_VARIANT[
                                                    template.status
                                                ] ?? "outline"
                                            }
                                        >
                                            {template.status_label}
                                        </Badge>
                                    </TableCell>
                                    <TableCell className="hidden sm:table-cell">
                                        <span className="text-sm text-muted-foreground">
                                            {template.enabled_blocks_count} /{" "}
                                            {template.total_blocks_count}
                                        </span>
                                    </TableCell>
                                    <TableCell className="hidden md:table-cell">
                                        {template.usage_count > 0 ? (
                                            <span className="inline-flex items-center gap-1 text-sm text-muted-foreground">
                                                <Link2 className="h-3.5 w-3.5" />
                                                {template.usage_count} projeto{template.usage_count !== 1 ? "s" : ""}
                                            </span>
                                        ) : (
                                            <span className="text-sm text-muted-foreground/50">-</span>
                                        )}
                                    </TableCell>
                                    <TableCell>
                                        <div className="flex items-center gap-1 justify-end">
                                            <Button
                                                variant="ghost"
                                                size="icon"
                                                asChild
                                            >
                                                <Link
                                                    href={route(
                                                        "templates.edit",
                                                        template.id
                                                    )}
                                                >
                                                    <Pencil className="h-4 w-4" />
                                                </Link>
                                            </Button>

                                            {!template.is_default && (
                                                template.usage_count > 0 ? (
                                                    <Button
                                                        variant="ghost"
                                                        size="icon"
                                                        disabled
                                                        title={`Em uso por ${template.usage_count} projeto(s)`}
                                                    >
                                                        <Trash2 className="h-4 w-4" />
                                                    </Button>
                                                ) : (
                                                    <AlertDialog>
                                                        <AlertDialogTrigger asChild>
                                                            <Button
                                                                variant="ghost"
                                                                size="icon"
                                                            >
                                                                <Trash2 className="h-4 w-4" />
                                                            </Button>
                                                        </AlertDialogTrigger>
                                                        <AlertDialogContent>
                                                            <AlertDialogHeader>
                                                                <AlertDialogTitle>
                                                                    Excluir
                                                                    template?
                                                                </AlertDialogTitle>
                                                                <AlertDialogDescription>
                                                                    O template "
                                                                    {template.name}
                                                                    " será excluído
                                                                    permanentemente.
                                                                </AlertDialogDescription>
                                                            </AlertDialogHeader>
                                                            <AlertDialogFooter>
                                                                <AlertDialogCancel>
                                                                    Cancelar
                                                                </AlertDialogCancel>
                                                                <AlertDialogAction
                                                                    onClick={() =>
                                                                        handleDelete(
                                                                            template.id
                                                                        )
                                                                    }
                                                                >
                                                                    Excluir
                                                                </AlertDialogAction>
                                                            </AlertDialogFooter>
                                                        </AlertDialogContent>
                                                    </AlertDialog>
                                                )
                                            )}
                                        </div>
                                    </TableCell>
                                </TableRow>
                            ))
                        )}
                    </TableBody>
                </Table>
            </div>

            {/* Pagination */}
            {totalPages > 1 && (
                <div className="flex items-center justify-between">
                    <p className="text-sm text-muted-foreground">
                        {filtered.length} template
                        {filtered.length !== 1 ? "s" : ""}
                    </p>

                    <div className="flex items-center gap-1">
                        <Button
                            variant="outline"
                            size="icon"
                            disabled={currentPage <= 1}
                            onClick={() => setPage(currentPage - 1)}
                        >
                            <ChevronLeft className="h-4 w-4" />
                        </Button>

                        <span className="px-2 text-sm sm:hidden">
                            {currentPage} / {totalPages}
                        </span>
                        <div className="hidden sm:flex items-center gap-1">
                            {Array.from({ length: totalPages }, (_, i) => (
                                <Button
                                    key={i + 1}
                                    variant={
                                        currentPage === i + 1
                                            ? "default"
                                            : "outline"
                                    }
                                    size="icon"
                                    onClick={() => setPage(i + 1)}
                                >
                                    {i + 1}
                                </Button>
                            ))}
                        </div>

                        <Button
                            variant="outline"
                            size="icon"
                            disabled={currentPage >= totalPages}
                            onClick={() => setPage(currentPage + 1)}
                        >
                            <ChevronRight className="h-4 w-4" />
                        </Button>
                    </div>
                </div>
            )}
            </div>
        </AppLayout>
    );
}
