"use client";
import React, { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Ellipsis, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { ResourceList } from "@/components/ui/resource-list/resource-list";
import { ResourceListToolbar } from "@/components/ui/resource-list/resource-list-toolbar";
import { ResourceListTable } from "@/components/ui/resource-list/resource-list-table";
import { ResourceListField } from "@/components/ui/resource-list/resource-list-field";
import { ResourceListPagination } from "@/components/ui/resource-list/resource-list-pagination";
import { ResourceListFilters } from "@/components/ui/resource-list/resource-list-filters";
import { ResourceListActionBar } from "@/components/ui/resource-list/resource-list-action-bar";
import { ResourceListBulkAction } from "@/components/ui/resource-list/resource-list-bulk-action";
import { Badge } from "@/components/ui/badge";
import { DeleteDialog } from "@/components/dashboard/delete-dialog";
import { Routes } from "@/config/routes";
import { api } from "@/lib/trpc/client";
import type { AppRouterOutput } from "@/lib/trpc/router";
import { useQueryStates } from "@/lib/hooks/use-query-states";
import { PriceListQuerySchema } from "@/server/modules/payment/payment.validators";
import { formatDate } from "@/lib/utils/format";

type Price = AppRouterOutput["payment"]["planPrice"]["list"][number];

type Props = {
    planId?: string;
};

export const PriceList: React.FC<Props> = ({ planId }) => {
    const router = useRouter();
    const [toDelete, setToDelete] = useState<Price[]>([]);

    const [params, setParams] = useQueryStates(PriceListQuerySchema, {
        history: "replace",
        scroll: false,
        shallow: true,
        clearOnDefault: true
    });

    const effectivePlanId = planId || params.planId;

    const {
        data: count = 0,
        refetch: refetchCount
    } = api.payment.planPrice.count.useQuery({
        planId: effectivePlanId || undefined,
        access: "dashboard"
    });

    const {
        data: prices = [],
        refetch: refetchList
    } = api.payment.planPrice.list.useQuery({
        planId: effectivePlanId || undefined,
        offset: params.page * params.perPage,
        limit: params.perPage,
        orderDir: params.orderDir,
        access: "dashboard"
    });

    const deleteManyMutation = api.payment.planPrice.deleteMany.useMutation({
        async onSuccess() {
            await Promise.all([refetchCount(), refetchList()]);
            setToDelete([]);
        }
    });

    return (
        <ResourceList<Price>
          selection
          data={prices}
          total={count}
          page={params.page}
          perPage={params.perPage}
          orderBy={params.orderBy}
          orderDir={params.orderDir}
          onOrderByChange={(orderBy) => setParams({ orderBy })}
          onOrderDirChange={(orderDir) => setParams({ orderDir })}
          onPageChange={(page) => setParams({ page })}
          onPerPageChange={(perPage) => setParams({ perPage })}>
            <ResourceListToolbar>
                <ResourceListFilters filters={params} onChange={setParams}>
                </ResourceListFilters>
            </ResourceListToolbar>

            <ResourceListTable>
                <ResourceListField<Price, "name">
                  enableSorting
                  label="Name"
                  name="name"
                  render={(name, row) => (
                    <Link
                      className="hover:text-primary flex items-center gap-1 hover:underline"
                      href={Routes.DASHBOARD.PAYMENT_PRICE_EDIT(row.planId, row.id)}>
                        {name}
                    </Link>
                  )} />

                <ResourceListField<Price, "price">
                  enableSorting
                  label="Price"
                  name="price"
                  render={(price) => price !== null ? (price / 100).toFixed(2) : "N/A"} />

                <ResourceListField<Price, "period">
                  enableSorting
                  label="Period"
                  name="period"
                  render={(period) => (
                    <Badge variant="outline" className="py-1">{period}</Badge>
                  )} />

                <ResourceListField<Price, "isActive">
                  enableSorting
                  label="Status"
                  name="isActive"
                  render={(isActive) => (
                    <Badge variant={isActive ? "default" : "secondary"}>
                        {isActive ? "Active" : "Inactive"}
                    </Badge>
                  )} />

                <ResourceListField<Price, "createdAt">
                  enableSorting
                  label="Created At"
                  name="createdAt"
                  render={(createdAt) => formatDate(createdAt)} />

                <ResourceListField<Price, "id">
                  label=""
                  name="id"
                  render={(id, price) => (
                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <Button
                              className="data-[state=open]:bg-muted flex size-8 p-0"
                              variant="ghost"
                              aria-label="Open menu">
                                <Ellipsis className="size-4" aria-hidden="true" />
                            </Button>
                        </DropdownMenuTrigger>

                        <DropdownMenuContent>
                            <DropdownMenuItem onClick={() => router.push(Routes.DASHBOARD.PAYMENT_PRICE_EDIT(price.planId, id))}>
                                Edit
                            </DropdownMenuItem>

                            {/*<DropdownMenuItem
                              variant="destructive"
                              onClick={() => setToDelete([price])}>
                                Delete
                            </DropdownMenuItem>*/}
                        </DropdownMenuContent>
                    </DropdownMenu>
                  )} />
            </ResourceListTable>

            <ResourceListPagination />

            <ResourceListActionBar>
                <ResourceListBulkAction<Price>
                  size="icon"
                  variant="destructive"
                  onClick={(rows) => setToDelete(rows.map(r => r.original))}>
                    <Trash2 />
                </ResourceListBulkAction>
            </ResourceListActionBar>

            <DeleteDialog
              open={toDelete.length > 0}
              pending={deleteManyMutation.isPending}
              onConfirm={async () => {
                await deleteManyMutation.mutateAsync({ ids: toDelete.map(f => f.id) });
              }}
              onCancel={() => setToDelete([])} />
        </ResourceList>
    );
};
