"use client";
import {
  TableCell,
  TableRow,
  Table,
  TableHeader,
  TableColumn,
  TableBody,
  Pagination,
  Checkbox,
  Dropdown,
  DropdownTrigger,
  DropdownMenu,
  DropdownItem,
  Input,
} from "@nextui-org/react";
import { Button } from "@nextui-org/button";
import React, {
  Key,
  Suspense,
  useCallback,
  useEffect,
  useMemo,
  useState,
} from "react";
import { SearchIcon, UserIcon } from "@/components/icons";

import { close, loading } from "@/config/swal";

import { getListTranscript } from "@/service/generate-article";
import { textEllipsis } from "@/utils/global";

const columns = [
  { name: "No", uid: "no" },
  { name: "Title", uid: "title" },
  { name: "Prompt", uid: "prompt" },
  { name: "Content", uid: "content" },
];

export default function TranscriptDraftTable(props: {
  initTranscriptId?: string;
  transriptContent: (data: string) => void;
}) {
  const [selectedTableRow, setSelectedTableRow] = useState<any>(new Set([""]));
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState("");
  const [totalPage, setTotalPage] = useState(1);
  const [dataTableTranscript, setDataTableTranscript] = useState<any[]>([]);

  useEffect(() => {
    setSelectedTableRow(new Set([props.initTranscriptId]));
    const now = findDataTable(Array.from(selectedTableRow)[0]);
    props.transriptContent(now?.content ? now?.content : "");
  }, [dataTableTranscript, props.initTranscriptId]);

  useEffect(() => {
    initFetch();
  }, [page]);

  const initFetch = async () => {
    loading();
    const res = await getListTranscript({
      query: search || "",
      page: page,
      clientId: "humasClientIdTest",
      limit: 10,
      createdBy: null,

      status: [0, 2],
      sort: [
        {
          column: "id",
          sort: "desc",
        },
      ],
    });
    close();
    setTotalPage(Math.ceil(res?.data?.total / 10));
    const data = res?.data?.data;
    const startIndex = 10 * (page - 1);
    let iterate = 0;
    const newData = data?.map((value: any) => {
      iterate++;
      value.no = startIndex + iterate;
      return value;
    });
    setDataTableTranscript(newData);
  };

  const renderCell = useCallback((article: any, columnKey: any) => {
    const cellValue = article[columnKey];

    switch (columnKey) {
      case "content":
        return <p>{textEllipsis(cellValue, 200)}</p>;
      default:
        return cellValue;
    }
  }, []);

  const handleSelected = (e: any) => {
    setSelectedTableRow(new Set([e.currentKey]));
    const now = findDataTable(e.currentKey);
    props.transriptContent(now?.content ? now?.content : "");
  };

  const handleSearch = () => {
    initFetch();
  };

  const findDataTable = (data: any) => {
    const temp = dataTableTranscript.find((item: any) => item.id == data);
    return temp;
  };

  return (
    <Suspense>
      <div className="mt-3 flex flex-row gap-3">
        <div className="w-full">
          <Input
            type="title"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            label=""
            variant="bordered"
            placeholder="Search"
            labelPlacement="outside"
          />
        </div>
        <Button color="primary" onPress={handleSearch}>
          Search
          <SearchIcon />
        </Button>
      </div>
      <div className="mt-4">
        <div className="flex flex-col items-center rounded-2xl">
          <Table
            selectionMode="multiple"
            aria-label="transcript-table"
            className="rounded-xl"
            classNames={{
              th: "bg-white text-black border-b-1",
              base: "bg-white",
              wrapper: "min-h-[50px] bg-transpararent text-black",
            }}
            checkboxesProps={{
              classNames: {
                wrapper:
                  "after:bg-foreground after:text-background text-background",
              },
            }}
            selectedKeys={selectedTableRow}
            onSelectionChange={handleSelected}
          >
            <TableHeader columns={columns}>
              {(column) => (
                <TableColumn key={column.uid}>{column.name}</TableColumn>
              )}
            </TableHeader>
            <TableBody
              items={dataTableTranscript}
              emptyContent={"No data to display."}
            >
              {(item) => (
                <TableRow key={item.id}>
                  {(columnKey) => (
                    <TableCell>{renderCell(item, columnKey)}</TableCell>
                  )}
                </TableRow>
              )}
            </TableBody>
          </Table>
          <div className="mt-2">
            <Pagination
              isCompact
              showControls
              showShadow
              color="primary"
              classNames={{
                base: "bg-transparent",
                wrapper: "bg-transparent",
              }}
              page={page}
              total={totalPage}
              onChange={(page) => setPage(page)}
            />
          </div>
        </div>
      </div>
    </Suspense>
  );
}
