import { useEffect, useMemo, useState } from "react";
import { Badge } from "../components/ui/badge";
import { Button } from "../components/ui/button";
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from "../components/ui/card";
import { Alert, AlertDescription, AlertTitle } from "../components/ui/alert";
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../components/ui/empty";
import { Input } from "../components/ui/input";
import {
    Pagination,
    PaginationContent,
    PaginationEllipsis,
    PaginationItem,
    PaginationLink,
    PaginationNext,
    PaginationPrevious,
} from "../components/ui/pagination";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "../components/ui/select";
import { Skeleton } from "../components/ui/skeleton";
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "../components/ui/table";
import { getSubscribedUsers } from "../firebase/firestore";
import { isFirebaseReady } from "../firebase/firebase";
import { useTitle } from "../hooks/useTitle";

const DEFAULT_PAGE_SIZE = 10;

function getVisiblePages(currentPage, totalPages) {
    if (totalPages <= 7) {
        return Array.from({ length: totalPages }, (_, index) => index + 1);
    }

    if (currentPage <= 4) {
        return [1, 2, 3, 4, 5, "ellipsis-end", totalPages];
    }

    if (currentPage >= totalPages - 3) {
        return [1, "ellipsis-start", totalPages - 4, totalPages - 3, totalPages - 2, totalPages - 1, totalPages];
    }

    return [1, "ellipsis-start", currentPage - 1, currentPage, currentPage + 1, "ellipsis-end", totalPages];
}

function getExpiration(value) {
    if (!value) return null;
    const date = value?.toDate ? value.toDate() : new Date(value);
    return Number.isNaN(date.getTime()) ? null : date;
}

export default function SubscriptionsPage() {
    useTitle("Subscriptions");

    const [items, setItems] = useState([]);
    const [loading, setLoading] = useState(isFirebaseReady);
    const [search, setSearch] = useState("");
    const [tierFilter, setTierFilter] = useState("all");
    const [statusFilter, setStatusFilter] = useState("all");
    const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);
    const [currentPage, setCurrentPage] = useState(1);

    useEffect(() => {
        async function load() {
            if (!isFirebaseReady) return;
            try {
                setItems(await getSubscribedUsers());
            } catch {
                setItems([]);
            } finally {
                setLoading(false);
            }
        }
        load();
    }, []);

    useEffect(() => {
        setCurrentPage(1);
    }, [search, tierFilter, statusFilter, pageSize]);

    const tiers = useMemo(() => {
        return Array.from(
            new Set(items.map((item) => item.subscriptionTier).filter(Boolean))
        ).sort((a, b) => a.localeCompare(b));
    }, [items]);

    const filtered = useMemo(() => {
        const q = search.trim().toLowerCase();
        return items.filter((item) => {
            const name = (item.profile?.name || "").toLowerCase();
            const email = (item.profile?.email || "").toLowerCase();
            const tier = item.subscriptionTier || "";
            const expiresAt = getExpiration(item.subscriptionExpiresAt);
            const isActive = expiresAt ? expiresAt > new Date() : false;

            const matchesSearch = !q || name.includes(q) || email.includes(q) || tier.toLowerCase().includes(q);
            const matchesTier = tierFilter === "all" || tier === tierFilter;
            const matchesStatus =
                statusFilter === "all" ||
                (statusFilter === "active" ? isActive : !isActive);

            return matchesSearch && matchesTier && matchesStatus;
        });
    }, [items, search, tierFilter, statusFilter]);

    const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
    const safeCurrentPage = Math.min(currentPage, totalPages);
    const pageStart = (safeCurrentPage - 1) * pageSize;
    const pageEnd = pageStart + pageSize;
    const paginatedItems = filtered.slice(pageStart, pageEnd);
    const visiblePages = getVisiblePages(safeCurrentPage, totalPages);
    const hasActiveFilters = search || tierFilter !== "all" || statusFilter !== "all";

    function goToPage(page) {
        setCurrentPage(Math.min(Math.max(page, 1), totalPages));
    }

    function resetFilters() {
        setSearch("");
        setTierFilter("all");
        setStatusFilter("all");
    }

    return (
        <section className="space-y-4">
            <Card>
                <CardHeader>
                    <CardTitle className="text-2xl font-semibold">Subscriptions</CardTitle>
                    <CardDescription>
                        Read-only mirror of subscription data. RevenueCat is the source of truth.
                    </CardDescription>
                </CardHeader>
            </Card>

            <Alert className="border-poot-info/40 bg-poot-info/10 text-poot-info">
                <AlertTitle>Support reference only</AlertTitle>
                <AlertDescription className="text-poot-info">
                    Use RevenueCat dashboard for subscription management.
                </AlertDescription>
            </Alert>

            <Card>
                <CardContent className="grid gap-3 sm:grid-cols-2 lg:grid-cols-[minmax(240px,1fr)_180px_160px_120px_auto]">
                    <Input
                        value={search}
                        onChange={(event) => setSearch(event.target.value)}
                        placeholder="Search by name, email, or tier..."
                        className="!h-10 bg-poot-surface"
                    />
                    <Select value={tierFilter} onValueChange={setTierFilter}>
                        <SelectTrigger
                            aria-label="Filter by tier"
                            className="!h-10 w-full border-poot-border bg-poot-surface text-poot-text"
                        >
                            <SelectValue placeholder="All tiers" />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value="all">All tiers</SelectItem>
                            {tiers.map((tier) => (
                                <SelectItem key={tier} value={tier}>
                                    {tier}
                                </SelectItem>
                            ))}
                        </SelectContent>
                    </Select>
                    <Select value={statusFilter} onValueChange={setStatusFilter}>
                        <SelectTrigger
                            aria-label="Filter by status"
                            className="!h-10 w-full border-poot-border bg-poot-surface text-poot-text"
                        >
                            <SelectValue placeholder="All statuses" />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value="all">All statuses</SelectItem>
                            <SelectItem value="active">Active</SelectItem>
                            <SelectItem value="expired">Expired</SelectItem>
                        </SelectContent>
                    </Select>
                    <Select
                        value={String(pageSize)}
                        onValueChange={(value) => setPageSize(Number(value))}
                    >
                        <SelectTrigger
                            aria-label="Rows per page"
                            className="!h-10 w-full border-poot-border bg-poot-surface text-poot-text"
                        >
                            <SelectValue placeholder={`${DEFAULT_PAGE_SIZE} / page`} />
                        </SelectTrigger>
                        <SelectContent>
                            {[10, 25, 50, 100].map((size) => (
                                <SelectItem key={size} value={String(size)}>
                                    {size} / page
                                </SelectItem>
                            ))}
                        </SelectContent>
                    </Select>
                    <Button
                        type="button"
                        variant="secondary"
                        onClick={resetFilters}
                        disabled={!hasActiveFilters}
                        className="h-10"
                    >
                        Reset
                    </Button>
                </CardContent>
            </Card>

            <Card>
                <CardContent className="p-0">
                    {loading ? (
                        <div className="grid gap-3 p-4">
                            {Array.from({ length: 6 }).map((_, index) => (
                                <Skeleton key={index} className="h-10 w-full" />
                            ))}
                        </div>
                    ) : filtered.length ? (
                        <Table className="min-w-[720px]">
                            <TableHeader className="bg-poot-bg">
                                <TableRow className="hover:bg-transparent">
                                    {["User", "Email", "Tier", "Expires At", "Status"].map((header) => (
                                        <TableHead
                                            key={header}
                                            className="px-4 py-3 text-xs font-semibold uppercase tracking-[0.04em] text-poot-muted"
                                        >
                                            {header}
                                        </TableHead>
                                    ))}
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {paginatedItems.map((item) => {
                                    const name = item.profile?.name || item.profile?.email || item.id;
                                    const email = item.profile?.email || "-";
                                    const tier = item.subscriptionTier || "-";
                                    const expiresAt = getExpiration(item.subscriptionExpiresAt);
                                    const isActive = expiresAt ? expiresAt > new Date() : false;

                                    return (
                                        <TableRow key={item.id} className="hover:bg-poot-bg/60">
                                            <TableCell className="px-4 py-3 text-poot-text">{name}</TableCell>
                                            <TableCell className="px-4 py-3 text-poot-text">{email}</TableCell>
                                            <TableCell className="px-4 py-3 text-poot-text">{tier}</TableCell>
                                            <TableCell className="px-4 py-3 text-poot-text">
                                                {expiresAt ? expiresAt.toLocaleDateString() : "-"}
                                            </TableCell>
                                            <TableCell className="px-4 py-3">
                                                <Badge variant={isActive ? "default" : "outline"}>
                                                    {isActive ? "Active" : "Expired"}
                                                </Badge>
                                            </TableCell>
                                        </TableRow>
                                    );
                                })}
                            </TableBody>
                        </Table>
                    ) : (
                        <Empty>
                            <EmptyHeader>
                                <EmptyTitle>No subscriptions found</EmptyTitle>
                                <EmptyDescription>
                                    No users with active or expired subscriptions.
                                </EmptyDescription>
                            </EmptyHeader>
                        </Empty>
                    )}
                </CardContent>
            </Card>

            {!loading && filtered.length ? (
                <Card>
                    <CardContent className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
                        <p className="text-sm text-poot-muted">
                            Showing {pageStart + 1}-{Math.min(pageEnd, filtered.length)} of {filtered.length} subscriptions
                        </p>
                        <Pagination className="mx-0 w-auto justify-start md:justify-end">
                            <PaginationContent>
                                <PaginationItem>
                                    <PaginationPrevious
                                        href="#"
                                        onClick={(event) => {
                                            event.preventDefault();
                                            goToPage(safeCurrentPage - 1);
                                        }}
                                        aria-disabled={safeCurrentPage === 1}
                                        className={safeCurrentPage === 1 ? "pointer-events-none opacity-50" : ""}
                                    />
                                </PaginationItem>
                                {visiblePages.map((page) => (
                                    <PaginationItem key={page}>
                                        {typeof page === "string" ? (
                                            <PaginationEllipsis />
                                        ) : (
                                            <PaginationLink
                                                href="#"
                                                isActive={page === safeCurrentPage}
                                                onClick={(event) => {
                                                    event.preventDefault();
                                                    goToPage(page);
                                                }}
                                            >
                                                {page}
                                            </PaginationLink>
                                        )}
                                    </PaginationItem>
                                ))}
                                <PaginationItem>
                                    <PaginationNext
                                        href="#"
                                        onClick={(event) => {
                                            event.preventDefault();
                                            goToPage(safeCurrentPage + 1);
                                        }}
                                        aria-disabled={safeCurrentPage === totalPages}
                                        className={safeCurrentPage === totalPages ? "pointer-events-none opacity-50" : ""}
                                    />
                                </PaginationItem>
                            </PaginationContent>
                        </Pagination>
                    </CardContent>
                </Card>
            ) : null}
        </section>
    );
}
