"use client";

import { usePermission } from "@/utils/auth/permission";
import { cellIndex } from "@/utils/lib/helpers";
import { Spinner } from "flowbite-react";
import { FC, useEffect, useState } from "react";
import DeleteRecord from "../common/delete-record";
import { ExpandableTextCell, useExpandableCells } from "../common/expandable-text-cell";
import CustomPagination from "../common/pagination";
import DataTable from "../dataTable/data-table-fb";
import { useCommunicationLogs, QUERY_KEY } from "@/hooks/use-communication-logs";
import type { CommunicationLog } from "@/types/communication-log";

interface CommunicationLogsListProps {
  filterValue?: string;
}

const CommunicationLogsList: FC<CommunicationLogsListProps> = ({
  filterValue = "#",
}) => {
  const [currentPage, setCurrentPage] = useState(1);
  const [pagination, setPagination] = useState<Pagination>({} as Pagination);
  const { expandedIds, toggle } = useExpandableCells([currentPage, filterValue]);

  const { data, isLoading, isFetching, refetch } = useCommunicationLogs({
    page: currentPage,
    filterValue,
  });

  useEffect(() => {
    if (data) {
      setPagination(data.pagination);
    }
  }, [data]);

  useEffect(() => {
    if (!filterValue.includes("#")) {
      setCurrentPage(1);
      refetch();
    }
  }, [filterValue, refetch]);

  const onPageChange = (page: number) => setCurrentPage(page);

  const columns = [
    {
      header: "SL",
      cell: ({ row }: { row: { index: number } }) => (
        <div className="font-bold">{cellIndex(row.index, pagination)}</div>
      ),
    },
    {
      header: "Channel",
      accessorKey: "channel",
      cell: ({ row }: { row: { original: CommunicationLog } }) => (
        <span className="capitalize">{row.original.channel}</span>
      ),
    },
    {
      header: "Body",
      accessorKey: "body",
      cell: ({ row }: { row: { original: CommunicationLog } }) => (
        <ExpandableTextCell
          text={row.original.body ?? ""}
          rowId={row.original.id}
          isExpanded={expandedIds.has(row.original.id)}
          onToggle={toggle}
        />
      ),
    },
    {
      header: "Type",
      accessorKey: "sms_type",
      cell: ({ row }: { row: { original: CommunicationLog } }) => (
        <div className="capitalize">
          {row.original.sms_type?.split("_")?.join(" ") ?? "-"}
        </div>
      ),
    },
    {
      header: "Count",
      accessorKey: "sms_count",
      cell: ({ row }: { row: { original: CommunicationLog } }) => (
        <div className="text-center">
          {row.original.sms_count}
        </div>
      ),
    },
    {
      header: "Cost",
      accessorKey: "cost",
      cell: ({ row }: { row: { original: CommunicationLog } }) => (
        <div className="text-center">
          {row.original.unit_price}
        </div>
      ),
    },
    {
      header: "From",
      accessorKey: "sms_from",
    },
    {
      header: "To",
      accessorKey: "sms_to",
    },
    {
      header: "Status",
      accessorKey: "status",
    },
    {
      header: "Sent At",
      accessorKey: "send_at",
    },
    {
      header: "Actions",
      id: "actions",
      cell: ({ row }: { row: { original: CommunicationLog } }) => {
        const log = row.original;
        return (
          <div className="flex">
            {usePermission("communication-logs.delete") && (
              <DeleteRecord
                url={`/api/communication-logs/${log.id}`}
                name="Communication log"
                keys={QUERY_KEY}
              />
            )}
          </div>
        );
      },
    },
  ];

  return (
    <>
      {(isLoading || isFetching) && (
        <div className="relative">
          <div className="grid fixed left-2/4 top-1/2 z-50">
            <Spinner size="xl" color="purple" />
          </div>
        </div>
      )}
      {data !== undefined && (
        <div className="user-list pb-20 shadow-md">
          <div className="border-b overflow-x-auto">
            <DataTable
              data={data.data}
              columns={columns}
              loading={false}
              initSorting={{ id: "body", desc: false }}
            />
          </div>
          <CustomPagination
            pagination={pagination}
            currentPage={currentPage}
            onPageChange={onPageChange}
            keys={QUERY_KEY}
          />
        </div>
      )}
    </>
  );
};

export default CommunicationLogsList;
