"use client";
import { usePermission } from "@/utils/auth/permission";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import axios from "axios";
import { Alert, Spinner } from "flowbite-react";
import { FC, useState } from "react";
import { HiInformationCircle } from "react-icons/hi";
import ActionButton from "../action-button";
import DeleteRecord from "../common/delete-record";
import DataTable from "../dataTable/data-table-fb";
import { TSpackageSchema } from "../forms/schema/package";
import PaymentMethodEdit from "./payment-method-edit";

type props = {
  initPaymentMethod: TSpackageSchema;
};

const PaymentMethodList: FC<props> = ({ initPaymentMethod }) => {
  const [isOpen, setOpen] = useState(false);
  const [paymentMethod_id, setZoneId] = useState<string | null>(null);

  const getZones = async () => {
    const { data } = await axios.get(`/api/payment-methods`);
    return data?.data;
  };
  const {
    data: paymentMethods,
    isLoading,
    isError,
    error = {} as any,
  } = useQuery({
    queryKey: ["payment-methods"],
    placeholderData: keepPreviousData,
    queryFn: () => getZones(),
    initialData: initPaymentMethod,
    retry: 0,
  });

  const columns = [
    {
      header: "SL",
      cell: ({ row }: any) => <div className="font-bold">{row.index + 1}</div>,
    },
    {
      header: "Name",
      accessorKey: "name",
    },
    {
      header: "Description",
      accessorKey: "description",
    },
    {
      header: "Actions",
      id: "testing",
      cell: ({ row }: any) => {
        const paymentMethod = row.original;
        const paymentMethod_id: string = String(paymentMethod.id);
        return (
          <>
            <div className=" flex">
              <div className="mr-2">
                {usePermission("payment-methods.edit") && (
                  <ActionButton
                    type="edit"
                    onClick={() => {
                      setOpen(true);
                      setZoneId(paymentMethod_id);
                    }}
                  />
                )}
              </div>
              {usePermission("payment-methods.delete") && (
                <DeleteRecord
                  keys="payment-methods"
                  url={`/api/payment-methods/${paymentMethod_id}`}
                  name="Payment Method"
                />
              )}
            </div>
          </>
        );
      },
    },
  ];

  return (
    <>
      {isLoading && (
        <div className="text-center">
          <Spinner
            aria-label="Center-aligned spinner example"
            className="mt-20"
            size="xl"
          />
        </div>
      )}
      {isError && (
        <Alert color="failure" icon={HiInformationCircle}>
          <span className="font-medium">Info alert!</span>
          {error?.response?.data?.error?.message}
        </Alert>
      )}
      {isOpen && (
        <PaymentMethodEdit
          paymentMethodId={paymentMethod_id}
          setOpen={setOpen as () => void}
          isOpen={isOpen}
        />
      )}
      {paymentMethods !== undefined && (
        <div className="user-list pb-20 shadow-md">
          <div className="border-b overflow-x-auto">
            <DataTable
              data={paymentMethods}
              columns={columns}
              loading={isOpen}
            />
          </div>
        </div>
      )}
    </>
  );
};
export default PaymentMethodList;
