"use client";
import { usePermission } from "@/utils/auth/permission";
import { cellIndex } from "@/utils/lib/helpers";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import axios from "axios";
import { Alert, Pagination, Spinner } from "flowbite-react";
import Link from "next/link";
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";

const SmsTemplateList: FC = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const [pagination, setPagination] = useState<any>({});

  const onPageChange = (page: number) => setCurrentPage(page);
  const getZones = async () => {
    const {
      data: { data },
      data: {
        data: { pagination },
      },
    } = await axios.get(`/api/sms-templates?page=${currentPage}`);
    setPagination(pagination);
    return data?.data;
  };
  const {
    data: smsTemplates,
    isLoading,
    isError,
    isSuccess,
    error = {} as any,
  } = useQuery({
    queryKey: ["sms-templates", { currentPage }],
    placeholderData: keepPreviousData,
    queryFn: () => getZones(),
    retry: 0,
  });

  const columns = [
    {
      header: "SL",
      cell: ({ row }: any) => (
        <div className="font-bold">{cellIndex(row.index, pagination)}</div>
      ),
    },
    {
      header: "Name",
      accessorKey: "name",
    },
    ,
    {
      header: "message",
      accessorKey: "message",
    },
    {
      header: "Actions",
      id: "testing",
      cell: ({ row }: any) => {
        const smsTemplate = row.original;
        const smsTemplate_id: string = String(smsTemplate.id);
        return (
          <>
            <div className=" flex">
              <div className="mr-2">
                {usePermission("sms-templates.edit") && (
                  <Link href={`/sms-templates/edit/${smsTemplate_id}`}>
                    <ActionButton type="edit" />
                  </Link>
                )}
              </div>
              {usePermission("sms-templates.delete") && (
                <DeleteRecord
                  url={`/api/sms-templates/${smsTemplate_id}`}
                  name="Sms Template"
                  keys="sms-templates"
                />
              )}
            </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>
      )}
      {smsTemplates !== undefined && (
        <div className="user-list pb-20 shadow-md">
          <div className="border-b overflow-x-auto">
            <DataTable data={smsTemplates} columns={columns} />
          </div>

          <div className="flex justify-between overflow-x-auto">
            <div className="flex">
              <Pagination
                className="ml-2 mt-2"
                layout="navigation"
                currentPage={currentPage}
                totalPages={pagination.total_pages || 0}
                onPageChange={onPageChange}
                showIcons
                nextLabel=""
                previousLabel=""
              />
              <div className="ml-2 mt-5">
                <p className="text-gray-500">
                  Showing
                  <span className="ml-2 mr-1 mt-1 text-gray-900">
                    {(pagination.current_page - 1) * 10 < 1
                      ? 1
                      : (pagination.current_page - 1) * 10}{" "}
                    - {pagination.current_page * 10}
                  </span>{" "}
                  of <span className="text-gray-900"> {pagination.total}</span>{" "}
                </p>
              </div>
            </div>
            <Pagination
              currentPage={currentPage}
              totalPages={pagination.total_pages || 0}
              onPageChange={onPageChange}
              className="mr-2 mt-2 text-blue-900 sm:justify-end"
              showIcons
              color="blue"
            />
          </div>
        </div>
      )}
    </>
  );
};
export default SmsTemplateList;
